adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! Whisper encoder/decoder on MLX.
//!
//! Architecture and safetensors key names follow ml-explore/mlx-examples
//! `whisper/mlx_whisper/whisper.py`. Conv1d weights are MLX NLC layout
//! `[out, kernel, in]`; linear weights are `[out, in]`.

use mlx_rs::error::Exception;
use mlx_rs::fast::{self, ScaledDotProductAttentionMask};
use mlx_rs::ops::indexing::TryIndexOp;
use mlx_rs::{Array, Dtype, ops};

use super::decode::KvCache;
use super::{mlx_err, stt_error};
use crate::error::AudioResult;
use crate::mlx::checkpoint::{Checkpoint, WhisperDims};

/// `nn.LayerNorm` default epsilon.
const LN_EPS: f32 = 1e-5;

/// Supplies the tensor for `name` with the expected `shape` while building a
/// model (from a checkpoint or a random initialiser).
pub(super) type WeightSource<'a> = dyn FnMut(&str, &[i32]) -> AudioResult<Array> + 'a;

type MlxResult<T> = Result<T, Exception>;

struct Linear {
    /// `[in, out]` (lazy transpose of the stored `[out, in]` weight).
    weight_t: Array,
    bias: Option<Array>,
}

impl Linear {
    fn build(
        src: &mut WeightSource<'_>,
        prefix: &str,
        n_in: i32,
        n_out: i32,
        bias: bool,
    ) -> AudioResult<Self> {
        let weight = src(&format!("{prefix}.weight"), &[n_out, n_in])?;
        let bias = if bias { Some(src(&format!("{prefix}.bias"), &[n_out])?) } else { None };
        Ok(Self { weight_t: weight.t(), bias })
    }

    fn forward(&self, x: &Array) -> MlxResult<Array> {
        match &self.bias {
            Some(bias) => ops::addmm(bias, x, &self.weight_t, None, None),
            None => x.matmul(&self.weight_t),
        }
    }
}

struct LayerNorm {
    weight: Array,
    bias: Array,
}

impl LayerNorm {
    fn build(src: &mut WeightSource<'_>, prefix: &str, n_state: i32) -> AudioResult<Self> {
        Ok(Self {
            weight: src(&format!("{prefix}.weight"), &[n_state])?,
            bias: src(&format!("{prefix}.bias"), &[n_state])?,
        })
    }

    fn forward(&self, x: &Array) -> MlxResult<Array> {
        fast::layer_norm(x, &self.weight, &self.bias, LN_EPS)
    }
}

struct Attention {
    query: Linear,
    key: Linear,
    value: Linear,
    out: Linear,
    n_head: i32,
    /// `head_dim^-0.5`; equivalent to whisper.py scaling q and k by `head_dim^-0.25`.
    scale: f32,
}

impl Attention {
    fn build(
        src: &mut WeightSource<'_>,
        prefix: &str,
        n_state: i32,
        n_head: i32,
    ) -> AudioResult<Self> {
        if n_head <= 0 || n_state % n_head != 0 {
            return Err(stt_error(format!(
                "n_state {n_state} is not divisible by n_head {n_head} ({prefix})"
            )));
        }
        Ok(Self {
            query: Linear::build(src, &format!("{prefix}.query"), n_state, n_state, true)?,
            key: Linear::build(src, &format!("{prefix}.key"), n_state, n_state, false)?,
            value: Linear::build(src, &format!("{prefix}.value"), n_state, n_state, true)?,
            out: Linear::build(src, &format!("{prefix}.out"), n_state, n_state, true)?,
            n_head,
            scale: ((n_state / n_head) as f32).powf(-0.5),
        })
    }

    /// `[1, L, H * D]` or `[L, H * D]` → `[1, H, L, D]` (batch is always 1).
    fn split_heads(&self, x: &Array) -> MlxResult<Array> {
        let s = x.shape();
        let len = s[s.len() - 2];
        x.reshape(&[1, len, self.n_head, -1])?.transpose_axes(&[0, 2, 1, 3])
    }

    /// Attention over `[B, H, L, D]` heads, merged and projected → `[B, L, H * D]`.
    fn attend(&self, q: &Array, k: &Array, v: &Array, causal: bool) -> MlxResult<Array> {
        let mask = causal.then_some(ScaledDotProductAttentionMask::Causal);
        let o = fast::scaled_dot_product_attention(q, k, v, self.scale, mask, None)?;
        let s = o.shape();
        let merged = o.transpose_axes(&[0, 2, 1, 3])?.reshape(&[s[0], s[2], -1])?;
        self.out.forward(&merged)
    }

    /// Unmasked self-attention without cache (encoder).
    fn forward_self(&self, x: &Array) -> MlxResult<Array> {
        let q = self.split_heads(&self.query.forward(x)?)?;
        let k = self.split_heads(&self.key.forward(x)?)?;
        let v = self.split_heads(&self.value.forward(x)?)?;
        self.attend(&q, &k, &v, false)
    }
}

/// Exact (erf) GELU `x/2 * (1 + erf(x / sqrt 2))`, as `nn.gelu`.
///
/// Not `mlx_rs::nn::gelu`: its `compile` wrapper allocates on the Rust heap on
/// every call. Constants are stored in the weight dtype so f16 stays f16.
struct Gelu {
    half: Array,
    inv_sqrt2: Array,
    one: Array,
}

impl Gelu {
    fn new(dtype: Dtype) -> AudioResult<Self> {
        let c = |v: f32| Array::from_f32(v).as_dtype(dtype).map_err(mlx_err("gelu constants"));
        Ok(Self { half: c(0.5)?, inv_sqrt2: c(std::f32::consts::FRAC_1_SQRT_2)?, one: c(1.0)? })
    }

    fn forward(&self, x: &Array) -> MlxResult<Array> {
        let erf = ops::erf(x.multiply(&self.inv_sqrt2)?)?;
        x.multiply(&self.half)?.multiply(erf.add(&self.one)?)
    }
}

/// Pre-LN feed-forward: `x + mlp2(gelu(mlp1(mlp_ln(x))))`.
struct Mlp {
    mlp1: Linear,
    mlp2: Linear,
    mlp_ln: LayerNorm,
    gelu: Gelu,
}

impl Mlp {
    fn build(src: &mut WeightSource<'_>, prefix: &str, n_state: i32) -> AudioResult<Self> {
        let n_mlp = n_state * 4;
        let mlp1 = Linear::build(src, &format!("{prefix}.mlp1"), n_state, n_mlp, true)?;
        let gelu = Gelu::new(mlp1.weight_t.dtype())?;
        Ok(Self {
            mlp1,
            mlp2: Linear::build(src, &format!("{prefix}.mlp2"), n_mlp, n_state, true)?,
            mlp_ln: LayerNorm::build(src, &format!("{prefix}.mlp_ln"), n_state)?,
            gelu,
        })
    }

    fn residual(&self, x: &Array) -> MlxResult<Array> {
        let h = self.mlp1.forward(&self.mlp_ln.forward(x)?)?;
        x.add(self.mlp2.forward(&self.gelu.forward(&h)?)?)
    }
}

struct EncoderBlock {
    attn: Attention,
    attn_ln: LayerNorm,
    mlp: Mlp,
}

impl EncoderBlock {
    fn build(
        src: &mut WeightSource<'_>,
        prefix: &str,
        n_state: i32,
        n_head: i32,
    ) -> AudioResult<Self> {
        Ok(Self {
            attn: Attention::build(src, &format!("{prefix}.attn"), n_state, n_head)?,
            attn_ln: LayerNorm::build(src, &format!("{prefix}.attn_ln"), n_state)?,
            mlp: Mlp::build(src, prefix, n_state)?,
        })
    }

    fn forward(&self, x: &Array) -> MlxResult<Array> {
        let x = x.add(self.attn.forward_self(&self.attn_ln.forward(x)?)?)?;
        self.mlp.residual(&x)
    }
}

struct DecoderBlock {
    attn: Attention,
    attn_ln: LayerNorm,
    cross_attn: Attention,
    cross_attn_ln: LayerNorm,
    mlp: Mlp,
}

impl DecoderBlock {
    fn build(
        src: &mut WeightSource<'_>,
        prefix: &str,
        n_state: i32,
        n_head: i32,
    ) -> AudioResult<Self> {
        Ok(Self {
            attn: Attention::build(src, &format!("{prefix}.attn"), n_state, n_head)?,
            attn_ln: LayerNorm::build(src, &format!("{prefix}.attn_ln"), n_state)?,
            cross_attn: Attention::build(src, &format!("{prefix}.cross_attn"), n_state, n_head)?,
            cross_attn_ln: LayerNorm::build(src, &format!("{prefix}.cross_attn_ln"), n_state)?,
            mlp: Mlp::build(src, prefix, n_state)?,
        })
    }
}

/// Fixed sinusoidal positions `[length, channels]` (whisper.py `sinusoids`).
fn sinusoids(length: usize, channels: usize) -> Vec<f32> {
    let half = channels / 2;
    let increment = 10_000f64.ln() / (half as f64 - 1.0);
    let mut out = vec![0.0f32; length * channels];
    for (t, row) in out.chunks_exact_mut(channels).enumerate() {
        let (sin, cos) = row.split_at_mut(half);
        for (i, (s, c)) in sin.iter_mut().zip(cos.iter_mut()).enumerate() {
            let angle = t as f64 * (-increment * i as f64).exp();
            *s = angle.sin() as f32;
            *c = angle.cos() as f32;
        }
    }
    out
}

struct AudioEncoder {
    conv1_weight: Array,
    conv1_bias: Array,
    conv2_weight: Array,
    conv2_bias: Array,
    /// `[n_audio_ctx, n_audio_state]` in the weight dtype; computed, not stored.
    positional: Array,
    gelu: Gelu,
    blocks: Vec<EncoderBlock>,
    ln_post: LayerNorm,
    /// Expected mel input `[1, 2 * n_audio_ctx, n_mels]`.
    mel_shape: [i32; 3],
}

impl AudioEncoder {
    fn build(src: &mut WeightSource<'_>, d: &WhisperDims) -> AudioResult<Self> {
        let (n_mels, n_ctx, n_state) =
            (d.n_mels as i32, d.n_audio_ctx as i32, d.n_audio_state as i32);
        if n_state < 4 || n_state % 2 != 0 {
            return Err(stt_error(format!("n_audio_state {n_state} must be even and >= 4")));
        }
        let conv1_weight = src("encoder.conv1.weight", &[n_state, 3, n_mels])?;
        let conv1_bias = src("encoder.conv1.bias", &[n_state])?;
        let conv2_weight = src("encoder.conv2.weight", &[n_state, 3, n_state])?;
        let conv2_bias = src("encoder.conv2.bias", &[n_state])?;
        let blocks = (0..d.n_audio_layer)
            .map(|i| {
                EncoderBlock::build(
                    src,
                    &format!("encoder.blocks.{i}"),
                    n_state,
                    d.n_audio_head as i32,
                )
            })
            .collect::<AudioResult<Vec<_>>>()?;
        let ln_post = LayerNorm::build(src, "encoder.ln_post", n_state)?;
        let positional =
            Array::from_slice(&sinusoids(n_ctx as usize, n_state as usize), &[n_ctx, n_state])
                .as_dtype(conv1_weight.dtype())
                .map_err(mlx_err("encoder positional embedding"))?;
        let gelu = Gelu::new(conv1_weight.dtype())?;
        Ok(Self {
            conv1_weight,
            conv1_bias,
            conv2_weight,
            conv2_bias,
            positional,
            blocks,
            ln_post,
            gelu,
            mel_shape: [1, 2 * n_ctx, n_mels],
        })
    }

    fn forward(&self, mel: &Array) -> MlxResult<Array> {
        let x = mel.as_dtype(self.conv1_weight.dtype())?;
        let x = ops::conv1d(&x, &self.conv1_weight, 1, 1, 1, 1)?.add(&self.conv1_bias)?;
        let x = self.gelu.forward(&x)?;
        let x = ops::conv1d(&x, &self.conv2_weight, 2, 1, 1, 1)?.add(&self.conv2_bias)?;
        let mut x = self.gelu.forward(&x)?.add(&self.positional)?;
        for block in &self.blocks {
            x = block.forward(&x)?;
        }
        self.ln_post.forward(&x)
    }
}

struct TextDecoder {
    /// `[n_vocab, n_text_state]`.
    token_embedding: Array,
    /// `[n_text_state, n_vocab]` (lazy transpose for the logits projection).
    token_embedding_t: Array,
    /// `[n_text_ctx, n_text_state]`.
    positional_embedding: Array,
    blocks: Vec<DecoderBlock>,
    ln: LayerNorm,
}

impl TextDecoder {
    fn build(src: &mut WeightSource<'_>, d: &WhisperDims) -> AudioResult<Self> {
        let n_state = d.n_text_state as i32;
        let token_embedding = src("decoder.token_embedding.weight", &[d.n_vocab as i32, n_state])?;
        let positional_embedding =
            src("decoder.positional_embedding", &[d.n_text_ctx as i32, n_state])?;
        let blocks = (0..d.n_text_layer)
            .map(|i| {
                DecoderBlock::build(
                    src,
                    &format!("decoder.blocks.{i}"),
                    n_state,
                    d.n_text_head as i32,
                )
            })
            .collect::<AudioResult<Vec<_>>>()?;
        let ln = LayerNorm::build(src, "decoder.ln", n_state)?;
        Ok(Self {
            token_embedding_t: token_embedding.t(),
            token_embedding,
            positional_embedding,
            blocks,
            ln,
        })
    }

    /// Runs `tokens` `[1, T]` at positions `cache.len..cache.len + T`, writing
    /// self-attention K/V into the cache in place. Returns `ln(x)` `[1, T, S]`.
    fn forward(&self, tokens: &Array, cache: &mut KvCache) -> MlxResult<Array> {
        let t = tokens.shape()[1];
        let pos = cache.len as i32;
        let end = pos + t;
        // Cache rows `[1, T, 1]` to overwrite. `put_along_axis` instead of
        // `try_index_mut`: mlx-rs's slice-assignment path collects the index
        // shape into a `Vec` on every call, while this path is pure FFI.
        let rows = if t == 1 {
            Array::from_slice(&[pos], &[1, 1, 1])
        } else {
            Array::arange::<_, i32>(pos, end, None)?.reshape(&[1, t, 1])?
        };
        // `[n_text_ctx, n_text_state]`, the 2-D view shape of each cache buffer.
        let ctx_shape = self.positional_embedding.shape();
        let rows2d = [ctx_shape[0], ctx_shape[1]];
        let mut x = self
            .token_embedding
            .take_axis(tokens, 0)?
            .add(self.positional_embedding.try_index(pos..end)?)?;
        for (l, block) in self.blocks.iter().enumerate() {
            let attn = &block.attn;
            let h = block.attn_ln.forward(&x)?;
            let q = attn.split_heads(&attn.query.forward(&h)?)?;
            cache.keys[l] = cache.keys[l].put_along_axis(&rows, attn.key.forward(&h)?, 1)?;
            cache.values[l] = cache.values[l].put_along_axis(&rows, attn.value.forward(&h)?, 1)?;
            // Read rows `0..end` as views: reshape `[1, N, S]` → `[N, S]`, then a
            // single-axis slice. Not `(.., 0..end, ..)` (mlx-rs's multi-axis
            // index path heap-allocates) and not `[0]` (a scalar index is a
            // gather that copies the whole cache).
            let k = attn.split_heads(&cache.keys[l].reshape(&rows2d)?.try_index(0..end)?)?;
            let v = attn.split_heads(&cache.values[l].reshape(&rows2d)?.try_index(0..end)?)?;
            // Causal mask is bottom-right aligned, so it is also correct for
            // a multi-token step at `pos > 0`; a single token sees everything.
            x = x.add(attn.attend(&q, &k, &v, t > 1)?)?;

            let cross = &block.cross_attn;
            let q = cross.split_heads(&cross.query.forward(&block.cross_attn_ln.forward(&x)?)?)?;
            x = x.add(cross.attend(&q, &cache.cross_keys[l], &cache.cross_values[l], false)?)?;
            x = block.mlp.residual(&x)?;
        }
        cache.len = end as usize;
        self.ln.forward(&x)
    }
}

/// Whisper encoder–decoder with device-resident weights.
pub(crate) struct Whisper {
    encoder: AudioEncoder,
    decoder: TextDecoder,
    dims: WhisperDims,
}

impl Whisper {
    /// Builds the model, pulling every tensor from `src` in a fixed order.
    pub(super) fn build(dims: WhisperDims, src: &mut WeightSource<'_>) -> AudioResult<Self> {
        // Cross-attention K/V project `n_audio_state` features with
        // `n_text_state`-sized weights (as in whisper.py); all released
        // Whisper configs have them equal.
        if dims.n_audio_state != dims.n_text_state {
            return Err(stt_error(format!(
                "unsupported Whisper config: n_audio_state {} != n_text_state {}",
                dims.n_audio_state, dims.n_text_state
            )));
        }
        let encoder = AudioEncoder::build(src, &dims)?;
        let decoder = TextDecoder::build(src, &dims)?;
        Ok(Self { encoder, decoder, dims })
    }

    /// Builds the model from a safetensors checkpoint and uploads the weights.
    ///
    /// Every expected tensor must be present with the shape implied by
    /// `ck.dims`; `alignment_heads` is ignored; any other key is rejected.
    pub fn load(ck: &Checkpoint) -> AudioResult<Self> {
        let path = ck.weights.display();
        let mut tensors = Array::load_safetensors(&ck.weights)
            .map_err(|e| stt_error(format!("failed to load {path}: {e}")))?;
        tensors.remove("alignment_heads");

        let mut loaded = Vec::with_capacity(tensors.len());
        let model = Self::build(ck.dims, &mut |name, shape| {
            let array = tensors
                .remove(name)
                .ok_or_else(|| stt_error(format!("missing tensor {name} in {path}")))?;
            if array.shape() != shape {
                return Err(stt_error(format!(
                    "tensor {name} in {path} has shape {:?}, but config.json implies {shape:?}",
                    array.shape()
                )));
            }
            loaded.push(array.clone());
            Ok(array)
        })?;
        if !tensors.is_empty() {
            let mut names: Vec<&str> = tensors.keys().map(String::as_str).collect();
            names.sort_unstable();
            return Err(stt_error(format!(
                "unexpected tensors in {path}: {}; not an MLX Whisper checkpoint",
                names.join(", ")
            )));
        }
        mlx_rs::transforms::eval(&loaded).map_err(mlx_err("upload Whisper weights"))?;
        Ok(model)
    }

    /// Random f32 model for tests and allocation probes; never for inference.
    pub(crate) fn random(dims: WhisperDims, seed: u64) -> AudioResult<Self> {
        let mut init = random_init(seed);
        let mut created = Vec::new();
        let model = Self::build(dims, &mut |name, shape| {
            let array = init(name, shape)?;
            created.push(array.clone());
            Ok(array)
        })?;
        mlx_rs::transforms::eval(&created).map_err(mlx_err("init random Whisper"))?;
        Ok(model)
    }

    pub(crate) fn dims(&self) -> &WhisperDims {
        &self.dims
    }

    /// Weight dtype (f16 for mlx-community fp16 checkpoints).
    pub(crate) fn dtype(&self) -> Dtype {
        self.decoder.token_embedding.dtype()
    }

    /// Encodes a log-mel window `[1, 2 * n_audio_ctx, n_mels]` (NLC) to
    /// `[1, n_audio_ctx, n_audio_state]`. Lazy; the caller evaluates.
    pub fn encode(&self, mel: &Array) -> AudioResult<Array> {
        if mel.shape() != self.encoder.mel_shape {
            return Err(stt_error(format!(
                "expected mel shape {:?}, got {:?}",
                self.encoder.mel_shape,
                mel.shape()
            )));
        }
        self.encoder.forward(mel).map_err(mlx_err("encode"))
    }

    /// Cross-attention K/V heads `[1, H, n_audio_ctx, D]` per decoder layer,
    /// written into `keys` / `values` (cleared first; capacity reused).
    pub(super) fn cross_kv(
        &self,
        audio: &Array,
        keys: &mut Vec<Array>,
        values: &mut Vec<Array>,
    ) -> AudioResult<()> {
        let expected = [1, self.dims.n_audio_ctx as i32, self.dims.n_audio_state as i32];
        if audio.shape() != expected {
            return Err(stt_error(format!(
                "expected audio features {expected:?}, got {:?}",
                audio.shape()
            )));
        }
        keys.clear();
        values.clear();
        let err = mlx_err("cross-attention K/V");
        for block in &self.decoder.blocks {
            let cross = &block.cross_attn;
            keys.push(cross.key.forward(audio).and_then(|k| cross.split_heads(&k)).map_err(&err)?);
            values.push(
                cross.value.forward(audio).and_then(|v| cross.split_heads(&v)).map_err(&err)?,
            );
        }
        Ok(())
    }

    /// Decoder step over `tokens` `[1, T]` (u32 ids) at `cache.len`; returns
    /// the final normalised hidden state `[1, T, n_text_state]`.
    pub(super) fn decode_hidden(&self, tokens: &Array, cache: &mut KvCache) -> AudioResult<Array> {
        let t = tokens.shape();
        if t.len() != 2 || t[0] != 1 || t[1] < 1 {
            return Err(stt_error(format!("expected tokens [1, T], got {t:?}")));
        }
        if cache.cross_keys.len() != self.decoder.blocks.len() {
            return Err(stt_error("KV cache not primed with audio features"));
        }
        if cache.len + t[1] as usize > self.dims.n_text_ctx as usize {
            return Err(stt_error(format!(
                "decoder context overflow: {} + {} > n_text_ctx {}",
                cache.len, t[1], self.dims.n_text_ctx
            )));
        }
        self.decoder.forward(tokens, cache).map_err(mlx_err("decode"))
    }

    /// Logits `hidden @ token_embedding.T` → `[.., n_vocab]` in the weight dtype.
    pub(super) fn project(&self, hidden: &Array) -> AudioResult<Array> {
        hidden.matmul(&self.decoder.token_embedding_t).map_err(mlx_err("logits"))
    }
}

/// Deterministic random weights (one PRNG key per tensor): `N(1, 0.02)` for
/// LayerNorm scales, `N(0, 0.02)` for biases, `N(0, 1)` for embeddings and
/// `N(0, 1/fan_in)` for linear/conv weights.
pub(super) fn random_init(seed: u64) -> impl FnMut(&str, &[i32]) -> AudioResult<Array> {
    let mut counter = 0u64;
    move |name, shape| {
        let key =
            mlx_rs::random::key(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(counter))
                .map_err(mlx_err("random key"))?;
        counter += 1;
        let is_norm = name.ends_with("ln.weight") || name.ends_with("ln_post.weight");
        let (loc, scale) = if is_norm {
            (1.0, 0.02)
        } else if name.ends_with(".bias") {
            (0.0, 0.02)
        } else if name.contains("embedding") {
            (0.0, 1.0)
        } else {
            let fan_in: i32 = shape[1..].iter().product();
            (0.0, (fan_in as f32).powf(-0.5))
        };
        mlx_rs::random::normal::<f32>(shape, loc, scale, &key).map_err(mlx_err("random normal"))
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::path::PathBuf;

    use mlx_rs::Array;

    use super::*;
    use crate::error::AudioError;
    use crate::mlx::checkpoint::{Checkpoint, WhisperDims};
    use crate::mlx::whisper::decode::KvCache;

    pub(crate) fn tiny_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: 16,
            n_text_state: 32,
            n_text_head: 2,
            n_text_layer: 2,
        }
    }

    /// `[1, 2 * n_audio_ctx, n_mels]` deterministic noise.
    pub(crate) fn tiny_mel(dims: &WhisperDims) -> Array {
        let key = mlx_rs::random::key(1234).unwrap();
        let shape = [1, 2 * dims.n_audio_ctx as i32, dims.n_mels as i32];
        mlx_rs::random::normal::<f32>(&shape[..], None, None, &key).unwrap()
    }

    /// Non-incremental logits for all `tokens` at once: `[1, T, n_vocab]`.
    pub(crate) fn full_logits(model: &Whisper, mel: &Array, tokens: &[u32]) -> Array {
        let audio = model.encode(mel).unwrap();
        let mut cache = KvCache::new(model).unwrap();
        cache.prime(model, &audio).unwrap();
        let ids = Array::from_slice(tokens, &[1, tokens.len() as i32]);
        let hidden = model.decode_hidden(&ids, &mut cache).unwrap();
        let logits = model.project(&hidden).unwrap();
        logits.eval().unwrap();
        logits
    }

    pub(crate) fn max_abs_diff(a: &Array, b: &Array) -> f32 {
        a.subtract(b).unwrap().abs().unwrap().max(None).unwrap().item_cast::<f32>()
    }

    struct TempFile(PathBuf);

    impl TempFile {
        fn new(name: &str) -> Self {
            let path = std::env::temp_dir()
                .join(format!("adk-audio-mlx-model-{}-{name}.safetensors", std::process::id()));
            Self(path)
        }
    }

    impl Drop for TempFile {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.0);
        }
    }

    /// Random model whose weights are also written to `file` (plus an
    /// `alignment_heads` entry that `load` must skip).
    fn random_saved(dims: WhisperDims, seed: u64, file: &TempFile) -> Whisper {
        random_saved_with(dims, seed, file, &[])
    }

    fn random_saved_with(dims: WhisperDims, seed: u64, file: &TempFile, extra: &[&str]) -> Whisper {
        save_random_with(dims, seed, &file.0, extra)
    }

    /// Writes a random model to `path` as an MLX Whisper safetensors checkpoint.
    pub(crate) fn save_random(dims: WhisperDims, seed: u64, path: &std::path::Path) {
        save_random_with(dims, seed, path, &[]);
    }

    fn save_random_with(
        dims: WhisperDims,
        seed: u64,
        path: &std::path::Path,
        extra: &[&str],
    ) -> Whisper {
        let mut init = random_init(seed);
        let mut saved: Vec<(String, Array)> = Vec::new();
        let model = Whisper::build(dims, &mut |name, shape| {
            let array = init(name, shape)?;
            saved.push((name.to_owned(), array.clone()));
            Ok(array)
        })
        .unwrap();
        saved.push(("alignment_heads".to_owned(), Array::from_slice(&[1i32, 0], &[1, 2])));
        for name in extra {
            saved.push(((*name).to_owned(), Array::from_slice(&[0.0f32], &[1])));
        }
        Array::save_safetensors(saved.iter().map(|(n, a)| (n.as_str(), a)), None, path).unwrap();
        model
    }

    #[test]
    fn encode_shape() {
        let dims = tiny_dims();
        let model = Whisper::random(dims, 0).unwrap();
        let audio = model.encode(&tiny_mel(&dims)).unwrap();
        assert_eq!(audio.shape(), &[1, 8, 32]);
    }

    #[test]
    fn encode_rejects_wrong_mel_shape() {
        let dims = tiny_dims();
        let model = Whisper::random(dims, 0).unwrap();
        let mel = Array::zeros::<f32>(&[1, 10, 80]).unwrap();
        assert!(matches!(model.encode(&mel), Err(AudioError::Stt { .. })));
    }

    #[test]
    fn load_roundtrip() {
        let dims = tiny_dims();
        let file = TempFile::new("roundtrip");
        let original = random_saved(dims, 7, &file);
        let loaded = Whisper::load(&Checkpoint { dims, weights: file.0.clone() }).unwrap();

        let mel = tiny_mel(&dims);
        let tokens = [3u32, 1, 4, 1, 5];
        let a = full_logits(&original, &mel, &tokens);
        let b = full_logits(&loaded, &mel, &tokens);
        assert_eq!(a.shape(), &[1, 5, 64]);
        assert_eq!(max_abs_diff(&a, &b), 0.0);
    }

    #[test]
    fn load_rejects_shape_mismatch() {
        let dims = tiny_dims();
        let file = TempFile::new("mismatch");
        random_saved(dims, 7, &file);
        let wrong = WhisperDims { n_vocab: 65, ..dims };
        match Whisper::load(&Checkpoint { dims: wrong, weights: file.0.clone() }) {
            Err(AudioError::Stt { provider, message }) => {
                assert_eq!(provider, "MLX");
                assert!(message.contains("decoder.token_embedding.weight"), "{message}");
            }
            Err(e) => panic!("unexpected error {e}"),
            Ok(_) => panic!("shape mismatch accepted"),
        }
    }

    #[test]
    fn load_rejects_unexpected_tensors_sorted() {
        let dims = tiny_dims();
        let file = TempFile::new("unexpected");
        random_saved_with(dims, 7, &file, &["zz.extra", "model.encoder.x", "aa.extra"]);
        match Whisper::load(&Checkpoint { dims, weights: file.0.clone() }) {
            Err(AudioError::Stt { message, .. }) => assert!(
                message.contains(
                    ": aa.extra, model.encoder.x, zz.extra; not an MLX Whisper checkpoint"
                ),
                "{message}"
            ),
            Err(e) => panic!("unexpected error {e}"),
            Ok(_) => panic!("unexpected tensors accepted"),
        }
    }

    #[test]
    fn build_rejects_mismatched_audio_and_text_state() {
        let dims = WhisperDims { n_text_state: 64, ..tiny_dims() };
        match Whisper::random(dims, 0) {
            Err(AudioError::Stt { message, .. }) => assert_eq!(
                message,
                "unsupported Whisper config: n_audio_state 32 != n_text_state 64"
            ),
            Err(e) => panic!("unexpected error {e}"),
            Ok(_) => panic!("mismatched dims accepted"),
        }
    }

    #[test]
    fn gelu_matches_mlx_nn_gelu() {
        let x = Array::from_slice(&[-6.0f32, -2.5, -1.0, -0.1, 0.0, 0.3, 1.0, 2.0, 7.5], &[9]);
        let ours = Gelu::new(Dtype::Float32).unwrap().forward(&x).unwrap();
        let reference = mlx_rs::nn::gelu(&x).unwrap();
        assert!(max_abs_diff(&ours, &reference) <= 1e-6);
    }
}