use std::path::Path;
use mlx_rs::Array;
use super::decode::{DecodeScratch, KvCache, greedy, read_id, step};
use super::mel::{MelFrontend, N_SAMPLES};
use super::mlx_err;
use super::model::Whisper;
use crate::error::AudioResult;
use crate::mlx::checkpoint::{self, WhisperDims};
const SMALL_TEXT_CTX: u32 = 64;
fn small_dims() -> WhisperDims {
WhisperDims {
n_mels: 80,
n_audio_ctx: 8,
n_audio_state: 32,
n_audio_head: 2,
n_audio_layer: 2,
n_vocab: 64,
n_text_ctx: SMALL_TEXT_CTX,
n_text_state: 32,
n_text_head: 2,
n_text_layer: 2,
}
}
fn whisper_tiny_dims() -> WhisperDims {
WhisperDims {
n_mels: 80,
n_audio_ctx: 1500,
n_audio_state: 384,
n_audio_head: 6,
n_audio_layer: 4,
n_vocab: 51865,
n_text_ctx: 448,
n_text_state: 384,
n_text_head: 6,
n_text_layer: 4,
}
}
pub struct DecodeProbe {
model: Whisper,
audio: Array,
cache: KvCache,
scratch: DecodeScratch,
suppress: Array,
next: Array,
}
impl DecodeProbe {
pub fn random_small() -> AudioResult<Self> {
Self::new(Whisper::random(small_dims(), 7)?)
}
pub fn random_whisper_tiny() -> AudioResult<Self> {
Self::new(Whisper::random(whisper_tiny_dims(), 7)?)
}
pub fn from_checkpoint(model_dir: &Path) -> AudioResult<Self> {
Self::new(Whisper::load(&checkpoint::inspect(model_dir)?)?)
}
fn new(model: Whisper) -> AudioResult<Self> {
let d = *model.dims();
let key = mlx_rs::random::key(1234).map_err(mlx_err("probe mel"))?;
let shape = [1, 2 * d.n_audio_ctx as i32, d.n_mels as i32];
let mel = mlx_rs::random::normal::<f32>(&shape[..], None, None, &key)
.map_err(mlx_err("probe mel"))?;
let audio = model.encode(&mel)?;
mlx_rs::transforms::eval([&audio]).map_err(mlx_err("probe encode"))?;
let mut bias = vec![0.0f32; d.n_vocab as usize];
bias[0] = f32::NEG_INFINITY;
let suppress = Array::from_slice(&bias, &[d.n_vocab as i32]);
mlx_rs::transforms::eval([&suppress]).map_err(mlx_err("probe suppress"))?;
let cache = KvCache::new(&model)?;
let scratch = DecodeScratch::new(&d);
let next = Array::from_slice(&[0u32], &[1, 1]);
let mut probe = Self { model, audio, cache, scratch, suppress, next };
probe.reset()?;
Ok(probe)
}
pub fn reset(&mut self) -> AudioResult<()> {
self.scratch.tokens.clear();
self.cache.prime(&self.model, &self.audio)?;
let prompt = Array::from_slice(&[1u32], &[1, 1]);
self.next = step(&self.model, &prompt, &self.suppress, &mut self.cache)?;
read_id(&self.next).map(drop)
}
pub fn remaining(&self) -> usize {
self.model.dims().n_text_ctx as usize - self.cache.len
}
pub fn step(&mut self) -> AudioResult<u32> {
self.next = step(&self.model, &self.next, &self.suppress, &mut self.cache)?;
let id = read_id(&self.next)?;
self.scratch.tokens.push(id);
Ok(id)
}
pub fn greedy_window(&mut self) -> AudioResult<usize> {
const PROMPT: [u32; 4] = [1, 2, 3, 4];
greedy(
&self.model,
&self.audio,
&PROMPT,
0,
&self.suppress,
&mut self.cache,
&mut self.scratch,
)?;
Ok(self.scratch.tokens.len())
}
}
pub struct MelProbe {
frontend: MelFrontend,
pcm: Array,
}
impl MelProbe {
pub fn new(pcm: &[f32]) -> AudioResult<Self> {
let mut window = vec![0.0f32; N_SAMPLES];
let n = pcm.len().min(N_SAMPLES);
window[..n].copy_from_slice(&pcm[..n]);
let pcm = Array::from_slice(&window, &[N_SAMPLES as i32]);
mlx_rs::transforms::eval([&pcm]).map_err(mlx_err("probe pcm"))?;
Ok(Self { frontend: MelFrontend::new(80)?, pcm })
}
pub fn from_frame(frame: &crate::frame::AudioFrame) -> AudioResult<Self> {
let mut mono = Vec::new();
crate::pcm::pcm16_to_f32_mono_into(&frame.data, frame.channels, &mut mono);
let samples = if frame.sample_rate == 16_000 {
mono
} else {
let mut resampled = Vec::new();
crate::pcm::resample_to_16khz_into(&mono, frame.sample_rate, &mut resampled);
resampled
};
Self::new(&samples)
}
pub fn run(&self) -> AudioResult<()> {
let mel = self.frontend.log_mel(&self.pcm)?;
mlx_rs::transforms::eval([&mel]).map_err(mlx_err("log-mel"))
}
}