adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
Documentation
//! KV cache and greedy decoding for the MLX Whisper decoder.

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;

/// Per-layer decoder attention state for one 30 s window.
pub(crate) struct KvCache {
    /// Self-attention keys per layer, preallocated `[1, n_text_ctx, n_text_state]`
    /// and overwritten in place at `len..` each step.
    pub(super) keys: Vec<Array>,
    /// Self-attention values, same layout as `keys`.
    pub(super) values: Vec<Array>,
    /// Cross-attention key heads `[1, H, n_audio_ctx, D]` per layer, set by `prime`.
    pub(super) cross_keys: Vec<Array>,
    /// Cross-attention value heads, same layout as `cross_keys`.
    pub(super) cross_values: Vec<Array>,
    /// Tokens currently held in the self-attention cache.
    pub(super) len: usize,
}

impl KvCache {
    /// Allocates the self-attention buffers on the device in the model dtype.
    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,
        })
    }

    /// Starts a new window: computes cross-attention K/V once from the
    /// encoder output `audio` `[1, n_audio_ctx, n_audio_state]` and empties the
    /// self-attention cache (stale entries past `len` are never read).
    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(())
    }
}

/// Reusable host-side decode buffers.
pub(crate) struct DecodeScratch {
    /// Generated token ids (prompt excluded); capacity `n_text_ctx`.
    pub(crate) tokens: Vec<u32>,
}

impl DecodeScratch {
    pub fn new(dims: &WhisperDims) -> Self {
        Self { tokens: Vec::with_capacity(dims.n_text_ctx as usize) }
    }
}

/// Next-token ids `[1, 1]` (u32, on device) from the last hidden state
/// `[1, 1, n_text_state]`: `argmax(logits + suppress)`.
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"))
}

/// One cached decoder step: feeds `token` `[1, 1]` at `cache.len` and returns
/// the next id `[1, 1]` (lazy, on device). The per-token hot path.
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)
}

/// Evaluates `next` `[1, 1]` and copies the id to the host.
pub(super) fn read_id(next: &Array) -> AudioResult<u32> {
    next.try_item_exact::<u32>().map_err(|e| stt_error(format!("read next token: {e}")))
}

/// Greedy decoding of one window into `scratch.tokens` (generated ids only).
///
/// Primes `cache` with `audio`, runs the whole `prompt` in one causal step,
/// then one token per step until `eot` (not stored) or
/// `n_text_ctx - prompt.len()` tokens. `suppress` `[n_vocab]` f32 is added to
/// every step's logits (`-inf` bans a token). Only the chosen id crosses to
/// the host each step.
// PERF: eager, not `mlx_rs::transforms::compile`. mlx-rs 0.34 `compile` needs
// a `'static` closure over `&[Array]` with fixed shapes; here the attended K/V
// length grows each step (`0..pos + 1`) and the in-place cache write offset
// is a graph constant (mlx-rs does not wrap `slice_update` with a dynamic
// start), so the traced graph would change every step and retrace.
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;
    // Reshape to 2-D before the single-axis slice: mlx-rs's multi-axis tuple
    // index `(.., p - 1..p, ..)` heap-allocates a `Vec` on the host.
    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}");
        }
    }

    /// Hand-built model whose greedy output is the position index: all block
    /// weights are zero, so the decoder output is `ln(E[tok] + P[pos])` with
    /// one-hot `E[i] = e_i` and `P[p] = 10 e_p`, whose argmax is `pos`.
    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, &[]);

        // Free running: the model emits its position (last prompt pos = 1).
        greedy(&model, &audio, &prompt, 63, &none, &mut cache, &mut scratch).unwrap();
        assert_eq!(scratch.tokens, (1..15).collect::<Vec<u32>>());

        // eot = the 4th token → exactly 3 tokens, eot not stored.
        greedy(&model, &audio, &prompt, 4, &none, &mut cache, &mut scratch).unwrap();
        assert_eq!(scratch.tokens, [1, 2, 3]);

        // Banning the eot id with the bias lets decoding run past it.
        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");

        // Reusing the cache and scratch for a second window gives the same result.
        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 { .. })));
    }
}