adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
Documentation
//! Benchmark and allocation-probe hooks; not a public API.
//!
//! Re-exported as `adk_audio::mlx::__bench` (`#[doc(hidden)]`, Apple Silicon
//! only) so `benches/mlx_whisper.rs` and `tests/mlx_alloc_tests.rs`, which
//! are separate crates, can drive the crate-private decode and mel paths
//! without widening the real API. The decode probe calls the same `step` /
//! `read_id` functions as production greedy decoding.

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};

/// Decoder self-attention context of `DecodeProbe::random_small`: room for
/// the one-token prompt plus warmup and measured steps.
const SMALL_TEXT_CTX: u32 = 64;

/// Random weights at tiny test dimensions (fast to build).
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,
    }
}

/// `openai/whisper-tiny` dimensions.
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,
    }
}

/// One window's greedy decode state, stepped one token at a time or per window.
pub struct DecodeProbe {
    model: Whisper,
    /// Encoder output for a fixed noise window.
    audio: Array,
    cache: KvCache,
    scratch: DecodeScratch,
    /// `[n_vocab]` f32 bias with `-inf` on token 0 (`eot`) so free-running decode
    /// never terminates early on random weights.
    suppress: Array,
    /// Device-side id fed to the next step.
    next: Array,
}

impl DecodeProbe {
    /// Random model at tiny test dimensions with a 64-token context.
    pub fn random_small() -> AudioResult<Self> {
        Self::new(Whisper::random(small_dims(), 7)?)
    }

    /// Random f32 model at `openai/whisper-tiny` dimensions.
    pub fn random_whisper_tiny() -> AudioResult<Self> {
        Self::new(Whisper::random(whisper_tiny_dims(), 7)?)
    }

    /// Real weights from an MLX Whisper checkpoint directory.
    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)
    }

    /// Starts the window over: primes the cross-attention cache, clears host
    /// token scratch, and decodes a one-token prompt (id 1).
    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)
    }

    /// Decode steps left before the context is full and `reset` is needed.
    pub fn remaining(&self) -> usize {
        self.model.dims().n_text_ctx as usize - self.cache.len
    }

    /// One greedy decoder step (as in production decoding); records and returns
    /// the generated token id. Errors once the context is full (`remaining() == 0`).
    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)
    }

    /// Runs a full `greedy` window (4-token prompt, `eot = 0` suppressed so it
    /// decodes until `n_text_ctx`), returning the number of generated tokens.
    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())
    }
}

/// The 80-mel front end over one fixed 30 s window.
pub struct MelProbe {
    frontend: MelFrontend,
    pcm: Array,
}

impl MelProbe {
    /// `pcm` (16 kHz mono) is zero-padded or truncated to 30 s.
    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 })
    }

    /// Downmixes and resamples `frame` to 16 kHz mono, then zero-pads or
    /// truncates to 30 s on the device.
    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)
    }

    /// Computes and evaluates the `[1, 3000, 80]` log-mel spectrogram.
    pub fn run(&self) -> AudioResult<()> {
        let mel = self.frontend.log_mel(&self.pcm)?;
        mlx_rs::transforms::eval([&mel]).map_err(mlx_err("log-mel"))
    }
}