adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
Documentation
//! Cross-platform inspection of local MLX Whisper model checkpoints.

use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};

use crate::error::{AudioError, AudioResult};

const MAX_SAFETENSORS_HEADER_BYTES: u64 = 100 * 1024 * 1024;
const QUANTIZED_ERROR_MSG: &str = "quantized MLX checkpoints are not supported yet; use an fp16 \
                                   repo such as mlx-community/whisper-tiny-fp16";

/// Whisper architecture dimensions parsed from `config.json`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
pub(crate) struct WhisperDims {
    pub(crate) n_mels: u32,
    pub(crate) n_audio_ctx: u32,
    pub(crate) n_audio_state: u32,
    pub(crate) n_audio_head: u32,
    pub(crate) n_audio_layer: u32,
    pub(crate) n_vocab: u32,
    pub(crate) n_text_ctx: u32,
    pub(crate) n_text_state: u32,
    pub(crate) n_text_head: u32,
    pub(crate) n_text_layer: u32,
}

/// Validated MLX Whisper checkpoint metadata and weights file path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Checkpoint {
    pub dims: WhisperDims,
    pub weights: PathBuf,
}

fn mlx_error(message: impl Into<String>) -> AudioError {
    AudioError::Stt { provider: "MLX".into(), message: message.into() }
}

fn read_config(model_dir: &Path) -> AudioResult<WhisperDims> {
    let config_path = model_dir.join("config.json");
    let bytes = std::fs::read(&config_path)
        .map_err(|e| mlx_error(format!("failed to read {}: {e}", config_path.display())))?;
    let value: serde_json::Value = serde_json::from_slice(&bytes)
        .map_err(|e| mlx_error(format!("failed to parse {}: {e}", config_path.display())))?;

    if value.as_object().is_some_and(|obj| obj.get("quantization").is_some_and(|v| !v.is_null())) {
        return Err(mlx_error(QUANTIZED_ERROR_MSG));
    }

    let dims = serde_json::from_value::<WhisperDims>(value).map_err(|e| {
        mlx_error(format!("invalid Whisper config in {}: {e}", config_path.display()))
    })?;
    if !matches!(dims.n_mels, 80 | 128) {
        return Err(mlx_error(format!("unsupported n_mels {}", dims.n_mels)));
    }
    Ok(dims)
}

fn select_weights(model_dir: &Path) -> AudioResult<PathBuf> {
    let weights = model_dir.join("weights.safetensors");
    if weights.is_file() {
        return Ok(weights);
    }

    let model = model_dir.join("model.safetensors");
    if model.is_file() {
        return Ok(model);
    }

    let npz = model_dir.join("weights.npz");
    if npz.is_file() {
        return Err(mlx_error(format!(
            "MLX checkpoint at {} is weights.npz, which mlx-rs cannot load; use a safetensors \
             repo such as mlx-community/whisper-large-v3-turbo or mlx-community/whisper-tiny-fp16",
            model_dir.display()
        )));
    }

    Err(mlx_error(format!(
        "no weights.safetensors or model.safetensors in {}",
        model_dir.display()
    )))
}

fn check_safetensors_header(weights_path: &Path) -> AudioResult<()> {
    let mut file = File::open(weights_path)
        .map_err(|e| mlx_error(format!("failed to open {}: {e}", weights_path.display())))?;

    let mut len_buf = [0u8; 8];
    file.read_exact(&mut len_buf).map_err(|e| {
        mlx_error(format!(
            "failed to read safetensors header length in {}: {e}",
            weights_path.display()
        ))
    })?;

    let header_len = u64::from_le_bytes(len_buf);
    if header_len > MAX_SAFETENSORS_HEADER_BYTES {
        return Err(mlx_error(format!(
            "safetensors header too large ({header_len} bytes, max {MAX_SAFETENSORS_HEADER_BYTES}) \
             in {}",
            weights_path.display()
        )));
    }

    let file_len = file
        .metadata()
        .map_err(|e| mlx_error(format!("failed to stat {}: {e}", weights_path.display())))?
        .len();
    if header_len > file_len.saturating_sub(8) {
        return Err(mlx_error(format!(
            "safetensors header in {} is truncated",
            weights_path.display()
        )));
    }

    let header_len = usize::try_from(header_len)
        .map_err(|_| mlx_error("safetensors header length exceeds platform usize"))?;
    let mut header_buf = vec![0u8; header_len];
    file.read_exact(&mut header_buf).map_err(|e| {
        mlx_error(format!("failed to read safetensors header in {}: {e}", weights_path.display()))
    })?;

    let header: serde_json::Value = serde_json::from_slice(&header_buf).map_err(|e| {
        mlx_error(format!("failed to parse safetensors header in {}: {e}", weights_path.display()))
    })?;

    let obj = header.as_object().ok_or_else(|| {
        mlx_error(format!("safetensors header in {} is not a JSON object", weights_path.display()))
    })?;

    if obj.keys().any(|key| key.ends_with(".scales") || key.ends_with(".biases")) {
        return Err(mlx_error(QUANTIZED_ERROR_MSG));
    }

    Ok(())
}

/// Inspect a local MLX Whisper checkpoint directory.
///
/// Validates `config.json` (rejecting quantized checkpoints), selects
/// `weights.safetensors` or `model.safetensors` (rejecting `.npz`-only repos),
/// and reads only the safetensors JSON header to reject quantized `.scales` /
/// `.biases` tensors.
pub(crate) fn inspect(model_dir: &Path) -> AudioResult<Checkpoint> {
    let dims = read_config(model_dir)?;
    let weights = select_weights(model_dir)?;
    check_safetensors_header(&weights)?;
    Ok(Checkpoint { dims, weights })
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::sync::atomic::{AtomicU64, Ordering};

    use super::*;

    const TURBO_CONFIG_JSON: &str = r#"{"n_mels":128,"n_audio_ctx":1500,"n_audio_state":1280,"n_audio_head":20,"n_audio_layer":32,"n_vocab":51866,"n_text_ctx":448,"n_text_state":1280,"n_text_head":20,"n_text_layer":4,"model_type":"whisper"}"#;

    static NEXT_ID: AtomicU64 = AtomicU64::new(0);

    struct TempDir {
        path: PathBuf,
    }

    impl TempDir {
        fn new(name: &str) -> Self {
            let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
            let path = std::env::temp_dir()
                .join(format!("adk-audio-mlx-checkpoint-{}-{name}-{id}", std::process::id()));
            let _ = fs::remove_dir_all(&path);
            fs::create_dir_all(&path).expect("create temp dir");
            Self { path }
        }

        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }

    fn write_fake_safetensors(path: &Path, header_json: &str) {
        let header_bytes = header_json.as_bytes();
        let len_le = (header_bytes.len() as u64).to_le_bytes();
        let mut buf = Vec::with_capacity(8 + header_bytes.len());
        buf.extend_from_slice(&len_le);
        buf.extend_from_slice(header_bytes);
        fs::write(path, buf).expect("write fake safetensors");
    }

    fn simple_safetensors_header(tensor_name: &str) -> String {
        format!(r#"{{"{tensor_name}":{{"dtype":"F16","shape":[1],"data_offsets":[0,2]}}}}"#)
    }

    #[test]
    fn inspect_reads_turbo_dims() {
        let dir = TempDir::new("turbo");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );

        let ckpt = inspect(dir.path()).expect("inspect should succeed");
        assert_eq!(ckpt.dims.n_mels, 128);
        assert_eq!(ckpt.dims.n_vocab, 51866);
        assert_eq!(ckpt.dims.n_audio_layer, 32);
        assert_eq!(ckpt.dims.n_text_layer, 4);
        assert_eq!(ckpt.dims.n_text_ctx, 448);
        assert!(
            ckpt.weights.ends_with("weights.safetensors"),
            "unexpected weights path: {}",
            ckpt.weights.display()
        );
    }

    #[test]
    fn inspect_prefers_weights_over_model_safetensors() {
        let dir = TempDir::new("prefer-weights");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );
        write_fake_safetensors(
            &dir.path().join("model.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );

        let ckpt = inspect(dir.path()).expect("inspect should succeed");
        assert!(
            ckpt.weights.ends_with("weights.safetensors"),
            "expected weights.safetensors, got {}",
            ckpt.weights.display()
        );

        let model_only = TempDir::new("model-only");
        fs::write(model_only.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        write_fake_safetensors(
            &model_only.path().join("model.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );
        let ckpt_model = inspect(model_only.path()).expect("model.safetensors should work");
        assert!(
            ckpt_model.weights.ends_with("model.safetensors"),
            "expected model.safetensors, got {}",
            ckpt_model.weights.display()
        );
    }

    #[test]
    fn inspect_rejects_npz() {
        let dir = TempDir::new("npz");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        fs::write(dir.path().join("weights.npz"), b"PK\x03\x04").unwrap();

        let err = inspect(dir.path()).expect_err("npz must be rejected");
        let msg = err.to_string();
        assert!(
            msg.contains("is weights.npz, which mlx-rs cannot load; use a safetensors repo"),
            "unexpected error: {msg}"
        );
        assert!(msg.contains(&dir.path().display().to_string()), "missing dir in: {msg}");
    }

    #[test]
    fn inspect_rejects_quantized_config() {
        let dir = TempDir::new("quant-config");
        let quant_cfg = r#"{"n_mels":128,"n_audio_ctx":1500,"n_audio_state":1280,"n_audio_head":20,"n_audio_layer":32,"n_vocab":51866,"n_text_ctx":448,"n_text_state":1280,"n_text_head":20,"n_text_layer":4,"quantization":{"group_size":64,"bits":4}}"#;
        fs::write(dir.path().join("config.json"), quant_cfg).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );

        let err = inspect(dir.path()).expect_err("quantized config must be rejected");
        assert_eq!(
            err.to_string(),
            "STT error (MLX): quantized MLX checkpoints are not supported yet; use an fp16 repo \
             such as mlx-community/whisper-tiny-fp16"
        );
    }

    #[test]
    fn inspect_rejects_scales_tensor() {
        let dir = TempDir::new("scales");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.blocks.0.attn.query.scales"),
        );

        let err = inspect(dir.path()).expect_err(".scales tensor must be rejected");
        assert_eq!(
            err.to_string(),
            "STT error (MLX): quantized MLX checkpoints are not supported yet; use an fp16 repo \
             such as mlx-community/whisper-tiny-fp16"
        );
    }

    #[test]
    fn inspect_rejects_biases_tensor() {
        let dir = TempDir::new("biases");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.blocks.0.attn.query.biases"),
        );

        let err = inspect(dir.path()).expect_err(".biases tensor must be rejected");
        assert_eq!(
            err.to_string(),
            "STT error (MLX): quantized MLX checkpoints are not supported yet; use an fp16 repo \
             such as mlx-community/whisper-tiny-fp16"
        );
    }

    #[test]
    fn inspect_missing_weights() {
        let dir = TempDir::new("missing");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();

        let err = inspect(dir.path()).expect_err("missing weights must be rejected");
        assert_eq!(
            err.to_string(),
            format!(
                "STT error (MLX): no weights.safetensors or model.safetensors in {}",
                dir.path().display()
            )
        );
    }

    #[test]
    fn inspect_rejects_oversized_header() {
        let dir = TempDir::new("oversized");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        let oversized_len = (100_u64 * 1024 * 1024) + 1;
        fs::write(dir.path().join("weights.safetensors"), oversized_len.to_le_bytes()).unwrap();

        let err = inspect(dir.path()).expect_err("oversized header must be rejected");
        let msg = err.to_string();
        assert!(msg.contains("safetensors header too large"), "unexpected error: {msg}");
    }

    #[test]
    fn inspect_accepts_null_quantization() {
        let dir = TempDir::new("null-quant");
        let cfg = r#"{"n_mels":128,"n_audio_ctx":1500,"n_audio_state":1280,"n_audio_head":20,"n_audio_layer":32,"n_vocab":51866,"n_text_ctx":448,"n_text_state":1280,"n_text_head":20,"n_text_layer":4,"quantization":null}"#;
        fs::write(dir.path().join("config.json"), cfg).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );

        let ckpt = inspect(dir.path()).expect("null quantization should be accepted");
        assert_eq!(ckpt.dims.n_mels, 128);
        assert_eq!(ckpt.dims.n_vocab, 51866);
    }

    #[test]
    fn inspect_rejects_truncated_header() {
        let dir = TempDir::new("truncated");
        fs::write(dir.path().join("config.json"), TURBO_CONFIG_JSON).unwrap();
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&1024_u64.to_le_bytes());
        bytes.extend_from_slice(b"{\"a\":1}");
        fs::write(dir.path().join("weights.safetensors"), bytes).unwrap();

        let err = inspect(dir.path()).expect_err("truncated header must be rejected");
        let msg = err.to_string();
        assert!(msg.contains("is truncated"), "unexpected error: {msg}");
    }

    #[test]
    fn inspect_rejects_odd_n_mels() {
        let dir = TempDir::new("odd-n-mels");
        let cfg = TURBO_CONFIG_JSON.replace(r#""n_mels":128"#, r#""n_mels":96"#);
        fs::write(dir.path().join("config.json"), cfg).unwrap();
        write_fake_safetensors(
            &dir.path().join("weights.safetensors"),
            &simple_safetensors_header("encoder.conv1.weight"),
        );

        let err = inspect(dir.path()).expect_err("n_mels=96 must be rejected");
        assert!(matches!(err, AudioError::Stt { .. }), "unexpected error kind: {err:?}");
        let msg = err.to_string();
        assert!(msg.contains("unsupported n_mels 96"), "unexpected error: {msg}");
    }
}