mod common;
use coremlit::embeddings::clap::{
AudioEncoder, MeanRenormalized, ScoreMode, TextAnchor, TextEncoder, WindowPlan,
aggregate::{CoverageWeightedMean, aggregate},
score,
};
const TOTAL_SAMPLES: usize = 9_240_000;
const EXPECTED_WINDOWS: usize = 20;
const TOP_LABEL: &str = "This is a sound of a person speaking";
const TOP_SCORE_LO: f32 = 8.3;
const TOP_SCORE_HI: f32 = 9.3;
const AGG_SELF_COSINE_LO: f32 = 0.97;
const TOP_SCORE_INT8_LO: f32 = 8.4;
const TOP_SCORE_INT8_HI: f32 = 9.4;
const ANCHORS: &[&str] = &[
"This is a sound of a person speaking",
"This is a sound of music",
"This is a sound of a dog barking",
"This is a sound of rain falling",
];
fn tiled_speech_clip() -> Vec<f32> {
let jfk = common::read_wav_48k_mono(&common::fixture_path("audio/speech_jfk_48k.wav"));
let mut clip = Vec::with_capacity(TOTAL_SAMPLES + jfk.len());
while clip.len() < TOTAL_SAMPLES {
clip.extend_from_slice(&jfk);
}
clip.truncate(TOTAL_SAMPLES);
clip
}
fn cosine(a: &[f32], b: &[f32]) -> f32 {
assert_eq!(
a.len(),
b.len(),
"cosine operands differ in length: {} vs {}",
a.len(),
b.len()
);
assert!(
a.iter().chain(b).all(|v| v.is_finite()),
"cosine operand contains a non-finite value (NaN/inf) — the reducer must fail closed"
);
let c: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
assert!(c.is_finite(), "cosine produced a non-finite value: {c}");
c
}
#[test]
#[should_panic(expected = "non-finite")]
fn cosine_rejects_non_finite_operand() {
let a = [f32::NAN, 0.0, 0.0];
let b = [1.0, 0.0, 0.0];
let _ = cosine(&a, &b);
}
#[test]
#[should_panic(expected = "differ in length")]
fn cosine_rejects_length_mismatch() {
let a = [1.0, 0.0, 0.0];
let b = [1.0, 0.0];
let _ = cosine(&a, &b);
}
#[test]
#[ignore = "requires clapkit models (CLAPKIT_TEST_MODELS)"]
fn multi_minute_pipeline_pins_windows_aggregate_and_top_label() {
let audio = AudioEncoder::from_file(common::audio_model_path()).unwrap();
let text = TextEncoder::from_file(common::text_model_path()).unwrap();
run_pipeline_and_pin(&audio, &text, "fp16", TOP_SCORE_LO, TOP_SCORE_HI);
}
#[test]
#[ignore = "requires clapkit int8 models (CLAPKIT_TEST_MODELS)"]
fn multi_minute_pipeline_int8_pins_top_label() {
let audio = AudioEncoder::from_file(common::audio_model_int8_path()).unwrap();
let text = TextEncoder::from_file(common::text_model_int8_path()).unwrap();
run_pipeline_and_pin(&audio, &text, "int8", TOP_SCORE_INT8_LO, TOP_SCORE_INT8_HI);
}
#[test]
#[ignore = "requires clapkit models (CLAPKIT_TEST_MODELS)"]
fn prewarm_then_reuse_both_towers() {
let audio = AudioEncoder::from_file(common::audio_model_path()).unwrap();
let text = TextEncoder::from_file(common::text_model_path()).unwrap();
audio.prewarm().expect("audio prewarm");
text.prewarm().expect("text prewarm");
let window = common::deterministic_window(coremlit::embeddings::clap::audio::TARGET_SAMPLES);
let a = audio
.embed_window(&window)
.expect("audio embed after prewarm");
let t = text
.embed("a violin playing a slow melody")
.expect("text embed after prewarm");
assert!(
(a.cosine(&a) - 1.0).abs() <= 1e-5,
"audio embedding is unit-norm after prewarm"
);
assert!(
(t.cosine(&t) - 1.0).abs() <= 1e-5,
"text embedding is unit-norm after prewarm"
);
}
fn run_pipeline_and_pin(
audio: &AudioEncoder,
text: &TextEncoder,
tier: &str,
top_score_lo: f32,
top_score_hi: f32,
) {
let clip = tiled_speech_clip();
let plan = WindowPlan::new(); let windows = audio.embed_windows(&clip, &plan).unwrap();
println!(
"[e2e/{tier}] {} windows over {} samples",
windows.len(),
clip.len()
);
assert_eq!(
windows.len(),
plan.spans(clip.len()).unwrap().len(),
"embed_windows count must match the plan geometry"
);
assert_eq!(
windows.len(),
EXPECTED_WINDOWS,
"pinned window count drifted"
);
assert_eq!(windows[0].span().coverage(), 1.0);
assert!((windows[EXPECTED_WINDOWS - 1].span().coverage() - 0.25).abs() < 1e-6);
let clip_embedding = aggregate(&MeanRenormalized, &windows).unwrap();
let norm_sq: f32 = clip_embedding.as_slice().iter().map(|x| x * x).sum();
assert!((norm_sq - 1.0).abs() < 1e-5, "aggregate not unit-norm");
let self_cos = cosine(clip_embedding.as_slice(), windows[0].value().as_slice());
println!("[e2e/{tier}] aggregate↔window[0] cosine = {self_cos:.6}");
assert!(
self_cos >= AGG_SELF_COSINE_LO,
"aggregate {self_cos:.6} diverged from its windows (below {AGG_SELF_COSINE_LO})"
);
let cov_embedding = aggregate(&CoverageWeightedMean, &windows).unwrap();
assert!(cov_embedding.is_close_cosine(&clip_embedding, 1e-3));
let anchor_embeddings: Vec<_> = ANCHORS.iter().map(|p| text.embed(p).unwrap()).collect();
let anchors: Vec<TextAnchor<'_>> = ANCHORS
.iter()
.zip(anchor_embeddings.iter())
.map(|(label, emb)| TextAnchor::new(label, emb))
.collect();
let ranked = score(&clip_embedding, &anchors, ScoreMode::LogitScaled);
for r in &ranked {
println!("[e2e/{tier}] {:<30} logit = {:.6}", r.label(), r.score());
}
assert_eq!(ranked[0].label(), TOP_LABEL, "top zero-shot label drifted");
let top = ranked[0].score();
assert!(
(top_score_lo..=top_score_hi).contains(&top),
"top logit {top:.6} outside pinned band [{top_score_lo}, {top_score_hi}]"
);
assert!(
ranked[0].score() > ranked[1].score(),
"speech anchor did not win outright"
);
}