use mlx_rs::ops::indexing::{TryIndexOp, argmax_axis};
use mlx_rs::{Array, Dtype};
use super::model::Whisper;
use super::{mlx_err, stt_error};
use crate::error::AudioResult;
use crate::mlx::checkpoint::WhisperDims;
pub(crate) struct KvCache {
pub(super) keys: Vec<Array>,
pub(super) values: Vec<Array>,
pub(super) cross_keys: Vec<Array>,
pub(super) cross_values: Vec<Array>,
pub(super) len: usize,
}
impl KvCache {
pub fn new(model: &Whisper) -> AudioResult<Self> {
let d = model.dims();
let layers = d.n_text_layer as usize;
let shape = [1, d.n_text_ctx as i32, d.n_text_state as i32];
let zeros = || mlx_rs::ops::zeros_dtype(&shape, model.dtype());
let mut keys = Vec::with_capacity(layers);
let mut values = Vec::with_capacity(layers);
for _ in 0..layers {
keys.push(zeros().map_err(mlx_err("allocate KV cache"))?);
values.push(zeros().map_err(mlx_err("allocate KV cache"))?);
}
mlx_rs::transforms::eval(keys.iter().chain(&values))
.map_err(mlx_err("allocate KV cache"))?;
Ok(Self {
keys,
values,
cross_keys: Vec::with_capacity(layers),
cross_values: Vec::with_capacity(layers),
len: 0,
})
}
pub fn prime(&mut self, model: &Whisper, audio: &Array) -> AudioResult<()> {
model.cross_kv(audio, &mut self.cross_keys, &mut self.cross_values)?;
mlx_rs::transforms::eval(self.cross_keys.iter().chain(&self.cross_values))
.map_err(mlx_err("cross-attention K/V"))?;
self.len = 0;
Ok(())
}
}
pub(crate) struct DecodeScratch {
pub(crate) tokens: Vec<u32>,
}
impl DecodeScratch {
pub fn new(dims: &WhisperDims) -> Self {
Self { tokens: Vec::with_capacity(dims.n_text_ctx as usize) }
}
}
fn next_token(model: &Whisper, hidden: &Array, suppress: &Array) -> AudioResult<Array> {
model
.project(hidden)?
.as_dtype(Dtype::Float32)
.and_then(|logits| logits.add(suppress))
.and_then(|logits| argmax_axis(&logits, -1, None))
.map_err(mlx_err("argmax"))
}
pub(super) fn step(
model: &Whisper,
token: &Array,
suppress: &Array,
cache: &mut KvCache,
) -> AudioResult<Array> {
let hidden = model.decode_hidden(token, cache)?;
next_token(model, &hidden, suppress)
}
pub(super) fn read_id(next: &Array) -> AudioResult<u32> {
next.try_item_exact::<u32>().map_err(|e| stt_error(format!("read next token: {e}")))
}
pub(crate) fn greedy(
model: &Whisper,
audio: &Array,
prompt: &[u32],
eot: u32,
suppress: &Array,
cache: &mut KvCache,
scratch: &mut DecodeScratch,
) -> AudioResult<()> {
scratch.tokens.clear();
let d = model.dims();
let n_ctx = d.n_text_ctx as usize;
if prompt.is_empty() || prompt.len() >= n_ctx {
return Err(stt_error(format!(
"prompt length {} must be in 1..{n_ctx} (n_text_ctx)",
prompt.len()
)));
}
if suppress.shape() != [d.n_vocab as i32] {
return Err(stt_error(format!(
"suppress bias must be [{}], got {:?}",
d.n_vocab,
suppress.shape()
)));
}
let max_new = n_ctx - prompt.len();
cache.prime(model, audio)?;
let ids = Array::from_slice(prompt, &[1, prompt.len() as i32]);
let hidden = model.decode_hidden(&ids, cache)?;
let p = prompt.len() as i32;
let n_state = d.n_text_state as i32;
let last = hidden
.reshape(&[p, n_state])
.and_then(|h| h.try_index(p - 1..p))
.and_then(|h| h.reshape(&[1, 1, n_state]))
.map_err(mlx_err("decode"))?;
let mut next = next_token(model, &last, suppress)?;
loop {
let id = read_id(&next)?;
if id == eot {
break;
}
scratch.tokens.push(id);
if scratch.tokens.len() == max_new {
break;
}
next = step(model, &next, suppress, cache)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use mlx_rs::Array;
use mlx_rs::ops::indexing::TryIndexOp;
use super::*;
use crate::mlx::whisper::model::tests::{full_logits, max_abs_diff, tiny_dims, tiny_mel};
fn bias(n_vocab: usize, entries: &[(u32, f32)]) -> Array {
let mut b = vec![0.0f32; n_vocab];
for &(token, value) in entries {
b[token as usize] = value;
}
Array::from_slice(&b, &[n_vocab as i32])
}
#[test]
fn cached_step_matches_full_forward() {
let dims = tiny_dims();
let model = Whisper::random(dims, 3).unwrap();
let mel = tiny_mel(&dims);
let tokens = [5u32, 9, 3, 17, 2, 40];
let full = full_logits(&model, &mel, &tokens);
let audio = model.encode(&mel).unwrap();
let mut cache = KvCache::new(&model).unwrap();
cache.prime(&model, &audio).unwrap();
for (k, &token) in tokens.iter().enumerate() {
let id = Array::from_slice(&[token], &[1, 1]);
let hidden = model.decode_hidden(&id, &mut cache).unwrap();
let step = model.project(&hidden).unwrap().reshape(&[64]).unwrap();
let expected = full.try_index((0, k as i32)).unwrap();
let diff = max_abs_diff(&step, &expected);
assert!(diff <= 1e-3, "pos {k}: max abs diff {diff}");
}
}
fn positional_model(dims: WhisperDims) -> Whisper {
Whisper::build(dims, &mut |name, shape| {
let mut data = vec![0.0f32; shape.iter().product::<i32>() as usize];
let cols = shape[shape.len() - 1] as usize;
if name.ends_with("ln.weight") || name.ends_with("ln_post.weight") {
data.fill(1.0);
} else if name == "decoder.token_embedding.weight" {
(0..cols).for_each(|i| data[i * cols + i] = 1.0);
} else if name == "decoder.positional_embedding" {
(0..shape[0] as usize).for_each(|p| data[p * cols + p] = 10.0);
}
Ok(Array::from_slice(&data, shape))
})
.unwrap()
}
#[test]
fn greedy_stops_at_eot() {
let dims = tiny_dims();
let model = positional_model(dims);
let audio = model.encode(&tiny_mel(&dims)).unwrap();
let prompt = [7u32, 9];
let mut cache = KvCache::new(&model).unwrap();
let mut scratch = DecodeScratch::new(&dims);
let none = bias(64, &[]);
greedy(&model, &audio, &prompt, 63, &none, &mut cache, &mut scratch).unwrap();
assert_eq!(scratch.tokens, (1..15).collect::<Vec<u32>>());
greedy(&model, &audio, &prompt, 4, &none, &mut cache, &mut scratch).unwrap();
assert_eq!(scratch.tokens, [1, 2, 3]);
let ban = bias(64, &[(4, f32::NEG_INFINITY)]);
greedy(&model, &audio, &prompt, 4, &ban, &mut cache, &mut scratch).unwrap();
assert_eq!(scratch.tokens.len(), 16 - prompt.len());
assert!(!scratch.tokens.contains(&4));
}
#[test]
fn greedy_stops_at_max_tokens_on_noise() {
let dims = tiny_dims();
let model = Whisper::random(dims, 5).unwrap();
let audio = model.encode(&tiny_mel(&dims)).unwrap();
let prompt = [1u32, 2, 3];
let eot = 0;
let suppress = bias(64, &[(eot, f32::NEG_INFINITY)]);
let mut cache = KvCache::new(&model).unwrap();
let mut scratch = DecodeScratch::new(&dims);
let cap = scratch.tokens.capacity();
greedy(&model, &audio, &prompt, eot, &suppress, &mut cache, &mut scratch).unwrap();
assert_eq!(scratch.tokens.len(), 16 - prompt.len());
assert!(!scratch.tokens.contains(&eot));
assert_eq!(scratch.tokens.capacity(), cap, "tokens reallocated");
let first = scratch.tokens.clone();
greedy(&model, &audio, &prompt, eot, &suppress, &mut cache, &mut scratch).unwrap();
assert_eq!(scratch.tokens, first);
}
#[test]
fn greedy_rejects_prompt_filling_context() {
let dims = tiny_dims();
let model = Whisper::random(dims, 5).unwrap();
let audio = model.encode(&tiny_mel(&dims)).unwrap();
let prompt = [1u32; 16];
let mut cache = KvCache::new(&model).unwrap();
let mut scratch = DecodeScratch::new(&dims);
let suppress = bias(64, &[]);
let err = greedy(&model, &audio, &prompt, 0, &suppress, &mut cache, &mut scratch);
assert!(matches!(err, Err(crate::error::AudioError::Stt { .. })));
}
}