Skip to main content

qualia_audio/models/aed_p64/
head.rs

1//! Acoustic-event detection head (P64, fail-closed) — AU-LEARNED.
2//!
3//! `AedHead` is a learned acoustic-event classifier that loads its weights through the common
4//! fail-closed loader. **With no weights it abstains** (`BackendUnavailable`) — it never emits a
5//! fabricated event. With a (possibly synthetic/test) weight blob present it runs a CPU reference
6//! linear classifier over a caller-supplied feature vector and writes a single **low-assurance**
7//! event *proposal* (flagged `FLAG_LOW_ASSURANCE | FLAG_REFERENCE_BACKEND`), never ground truth.
8//!
9//! Blob convention: `dims = [num_classes, num_features]`, row-major `data` of
10//! `num_classes * num_features` weights followed by `num_classes` bias terms. The forward pass is
11//! `logit_c = bias_c + Σ_f weight[c,f] * features[f]`; the argmax class is proposed. Inference is
12//! the hot path and allocates nothing (streaming argmax over caller buffers).
13
14use crate::models::loader::{parse_weight_blob, require_weights, WeightBlob, WeightState};
15use crate::types::{AudioError, AuditoryEvent};
16
17/// Base for synthesized class hashes (a low-assurance proposal identifier, not a curated URI).
18const AED_CLASS_BASE: u64 = 0x9E37_79B9_7F4A_7C15;
19
20/// Learned acoustic-event detection head. Fail-closed: `Absent` state ⇒ inference abstains.
21#[derive(Debug, Default)]
22pub struct AedHead {
23    pub state: WeightState,
24}
25
26impl AedHead {
27    /// Construct with no weights — fails closed until [`AedHead::load`] succeeds.
28    pub fn new() -> Self {
29        Self {
30            state: WeightState::Absent,
31        }
32    }
33
34    /// Load weights from a P64 blob (cold path). On success the head leaves fail-closed mode.
35    pub fn load(&mut self, bytes: &[u8]) -> Result<(), AudioError> {
36        let blob = parse_weight_blob(bytes)?;
37        validate_shape(&blob)?;
38        self.state = WeightState::Loaded(blob);
39        Ok(())
40    }
41
42    /// Whether a real forward pass is available.
43    pub fn is_ready(&self) -> bool {
44        self.state.is_loaded()
45    }
46
47    /// Infer at most one low-assurance event proposal from `features` into `out_events`.
48    ///
49    /// - No weights ⇒ `Err(BackendUnavailable)` (abstain; nothing written).
50    /// - `features.len()` must equal the blob's `num_features`, else `InvalidParameter`.
51    /// - `out_events` must have room for ≥1 event, else `OutputBufferTooSmall`.
52    ///
53    /// Returns the number of events written (0 or 1). Hot path: no allocation.
54    pub fn infer(
55        &self,
56        features: &[f32],
57        out_events: &mut [AuditoryEvent],
58    ) -> Result<usize, AudioError> {
59        let blob = require_weights(&self.state)?;
60        let (num_classes, num_features) = shape(blob)?;
61        if features.len() != num_features {
62            return Err(AudioError::InvalidParameter);
63        }
64        if out_events.is_empty() {
65            return Err(AudioError::OutputBufferTooSmall);
66        }
67
68        // Streaming argmax over class logits (zero-heap).
69        let bias_off = num_classes * num_features;
70        let mut best_class = 0usize;
71        let mut best_logit = f32::NEG_INFINITY;
72        let mut sum_exp = 0.0f32;
73        // Two-pass would need storage; instead track max, then a running softmax denominator using
74        // the shift-by-current-max trick is awkward stateless. We keep it simple and bounded:
75        // first find the max logit, accumulating exp against a provisional max is unnecessary for a
76        // small class count, so compute logits twice (cheap; classes are few).
77        for c in 0..num_classes {
78            let logit = class_logit(blob, c, num_features, bias_off, features);
79            if logit > best_logit {
80                best_logit = logit;
81                best_class = c;
82            }
83        }
84        for c in 0..num_classes {
85            let logit = class_logit(blob, c, num_features, bias_off, features);
86            sum_exp += (logit - best_logit).exp();
87        }
88        // Softmax probability of the winning class ∈ (0,1].
89        let prob = if sum_exp > 0.0 { 1.0 / sum_exp } else { 0.0 };
90        let confidence_u16 = (prob.clamp(0.0, 1.0) * 65535.0) as u16;
91
92        out_events[0] = AuditoryEvent {
93            class_hash: class_hash(best_class),
94            source_hash: 0,
95            confidence_u16,
96            channel: 0,
97            start_frame: 0,
98            end_frame: 0,
99            track_id: 0,
100            flags: AuditoryEvent::FLAG_LOW_ASSURANCE | AuditoryEvent::FLAG_REFERENCE_BACKEND,
101        };
102        Ok(1)
103    }
104}
105
106#[inline]
107fn class_logit(
108    blob: &WeightBlob,
109    c: usize,
110    num_features: usize,
111    bias_off: usize,
112    features: &[f32],
113) -> f32 {
114    let row = c * num_features;
115    let mut acc = blob.data[bias_off + c];
116    for f in 0..num_features {
117        acc += blob.data[row + f] * features[f];
118    }
119    acc
120}
121
122#[inline]
123fn class_hash(idx: usize) -> u64 {
124    AED_CLASS_BASE
125        ^ (idx as u64)
126            .wrapping_add(1)
127            .wrapping_mul(0xD6E8_FEB8_6659_FD93)
128}
129
130fn shape(blob: &WeightBlob) -> Result<(usize, usize), AudioError> {
131    if blob.dims.len() != 2 {
132        return Err(AudioError::BackendUnavailable);
133    }
134    Ok((blob.dims[0] as usize, blob.dims[1] as usize))
135}
136
137fn validate_shape(blob: &WeightBlob) -> Result<(), AudioError> {
138    let (num_classes, num_features) = shape(blob)?;
139    if num_classes == 0 || num_features == 0 {
140        return Err(AudioError::BackendUnavailable);
141    }
142    let need = num_classes * num_features + num_classes;
143    if blob.data.len() != need {
144        return Err(AudioError::BackendUnavailable);
145    }
146    Ok(())
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use crate::models::loader::{make_blob, write_weight_blob};
153
154    fn synthetic_blob() -> Vec<u8> {
155        // 2 classes, 2 features. Class 1 responds strongly to feature[1].
156        // weights (row-major): c0=[1,0], c1=[0,1]; bias=[0,0].
157        let blob = make_blob(vec![2, 2], vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
158        write_weight_blob(&blob)
159    }
160
161    #[test]
162    fn absent_abstains_never_fabricates() {
163        let head = AedHead::new();
164        let mut out = [AuditoryEvent::empty(); 4];
165        assert_eq!(
166            head.infer(&[0.9, 0.1], &mut out),
167            Err(AudioError::BackendUnavailable)
168        );
169        // Nothing written.
170        assert_eq!(out[0], AuditoryEvent::empty());
171    }
172
173    #[test]
174    fn loaded_produces_low_assurance_proposal() {
175        let mut head = AedHead::new();
176        head.load(&synthetic_blob()).expect("load");
177        assert!(head.is_ready());
178        let mut out = [AuditoryEvent::empty(); 4];
179        // feature[1] dominant ⇒ class 1.
180        let n = head.infer(&[0.0, 5.0], &mut out).expect("infer");
181        assert_eq!(n, 1);
182        assert_eq!(out[0].class_hash, class_hash(1));
183        assert_ne!(out[0].flags & AuditoryEvent::FLAG_LOW_ASSURANCE, 0);
184        assert_ne!(out[0].flags & AuditoryEvent::FLAG_REFERENCE_BACKEND, 0);
185    }
186
187    #[test]
188    fn wrong_feature_len_is_invalid() {
189        let mut head = AedHead::new();
190        head.load(&synthetic_blob()).expect("load");
191        let mut out = [AuditoryEvent::empty(); 4];
192        assert_eq!(
193            head.infer(&[1.0], &mut out),
194            Err(AudioError::InvalidParameter)
195        );
196    }
197
198    #[test]
199    fn empty_out_buffer_rejected() {
200        let mut head = AedHead::new();
201        head.load(&synthetic_blob()).expect("load");
202        let mut out: [AuditoryEvent; 0] = [];
203        assert_eq!(
204            head.infer(&[0.0, 1.0], &mut out),
205            Err(AudioError::OutputBufferTooSmall)
206        );
207    }
208}