qualia_audio/models/aed_p64/
head.rs1use crate::models::loader::{parse_weight_blob, require_weights, WeightBlob, WeightState};
15use crate::types::{AudioError, AuditoryEvent};
16
17const AED_CLASS_BASE: u64 = 0x9E37_79B9_7F4A_7C15;
19
20#[derive(Debug, Default)]
22pub struct AedHead {
23 pub state: WeightState,
24}
25
26impl AedHead {
27 pub fn new() -> Self {
29 Self {
30 state: WeightState::Absent,
31 }
32 }
33
34 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 pub fn is_ready(&self) -> bool {
44 self.state.is_loaded()
45 }
46
47 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 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 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 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 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 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 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}