coremlit 0.1.1

Safe, synchronous CoreML runtime for macOS (CPU/GPU/Neural Engine) with opt-in on-device multimodal pipelines: speech (Whisper STT, forced alignment, speaker diarization, Silero VAD), AudioSet sound-event tagging, and audio/text/image embeddings (CLAP, granite, SigLIP)
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
//! [`InferenceBackend`]: the seam every Whisper pipeline stage (mel
//! extraction, encoding, autoregressive decoding) drives without knowing
//! whether it is talking to a real CoreML model or a scripted test double
//! (spec §5.4). Also home to [`ModelDims`] (the static shape/vocabulary
//! description backends report — drives variant detection and buffer
//! sizing) and [`AlignmentView`]/[`AlignmentMatrix`] (the borrowed/owned
//! cross-attention alignment slice word-timestamp code reads and snapshots).
//!
//! Two implementations live here: [`coreml::CoreMlBackend`] — the real
//! one, owning the three `crate::Model`s (spec §5.4) — and
//! [`mock::MockBackend`], the scripted, hermetic test double every
//! decode-loop/fallback/windowing test downstream needs before a compiled
//! model exists at all (spec §9.1).

use crate::audio::whisper::model::is_model_multilingual;

pub mod coreml;
pub mod mock;

#[cfg(test)]
mod tests;

// ---------------------------------------------------------------------
// ModelDims
// ---------------------------------------------------------------------

/// Default [`ModelDims::vocab`] — tiny model decoder vocabulary size (Task
/// 1 ground truth: `logits` output shape `[1, 1, 51865]`).
pub const DEFAULT_VOCAB: usize = 51_865;
/// Default [`ModelDims::n_mels`] — tiny model mel-spectrogram bin count
/// (Task 1 ground truth: `melspectrogram_features` shape `[1, 80, 1,
/// 3000]`).
pub const DEFAULT_N_MELS: usize = 80;
/// Default [`ModelDims::embed_dim`] — tiny model encoder embedding width
/// (Task 1 ground truth: `encoder_output_embeds` shape `[1, 384, 1,
/// 1500]`).
pub const DEFAULT_EMBED_DIM: usize = 384;
/// Default [`ModelDims::kv_dim`] — tiny model decoder KV-cache channel
/// width, `embed_dim * decoder_layers` (Task 1 ground truth:
/// `key_cache`/`value_cache` shape `[1, 1536, 1, 224]`).
pub const DEFAULT_KV_DIM: usize = 1536;
/// Default [`ModelDims::max_token_context`] — shared by every model size
/// (Whisper's fixed `448 / 2` token budget, not tiny-specific), so this
/// reuses [`crate::audio::whisper::constants::MAX_TOKEN_CONTEXT`] rather than restating it.
pub const DEFAULT_MAX_TOKEN_CONTEXT: usize = crate::audio::whisper::constants::MAX_TOKEN_CONTEXT;
/// Default [`ModelDims::n_audio_ctx`] — tiny model encoder audio-context
/// length (Task 1 ground truth: `encoder_output_embeds`/
/// `alignment_heads_weights` trailing dim `1500`).
pub const DEFAULT_N_AUDIO_CTX: usize = 1500;
/// Default [`ModelDims::window_samples`] — shared by every model size
/// (fixed 30 s @ 16 kHz, not tiny-specific), so this reuses
/// [`crate::audio::whisper::constants::WINDOW_SAMPLES`] rather than restating it.
pub const DEFAULT_WINDOW_SAMPLES: usize = crate::audio::whisper::constants::WINDOW_SAMPLES;

/// Static shape/vocabulary description of a loaded Whisper model —
/// [`InferenceBackend::dims`] reports these for variant detection, buffer
/// sizing, and multilinguality (spec §5.4: "vocab, n_mels, n_ctx, embed —
/// drives variant detection").
///
/// [`Self::new`]/[`Default`] return the tiny model's dimensions
/// (introspected live from the real `openai_whisper-tiny` `.mlmodelc`
/// bundles and pinned by `tests/model_io.rs`) — every unit/doc test
/// in this crate implicitly targets that model. A real backend overrides
/// every field from its own model's introspection at load time; these
/// defaults exist for the tiny model and the mock/fallback case only, not
/// as a general-purpose guess for an arbitrary model size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModelDims {
  vocab: usize,
  n_mels: usize,
  embed_dim: usize,
  kv_dim: usize,
  max_token_context: usize,
  n_audio_ctx: usize,
  window_samples: usize,
}

impl Default for ModelDims {
  fn default() -> Self {
    Self::new()
  }
}

impl ModelDims {
  /// Dimensions matching the tiny model (Task 1 ground truth); backends
  /// override every field from real introspection at load time.
  pub const fn new() -> Self {
    Self {
      vocab: DEFAULT_VOCAB,
      n_mels: DEFAULT_N_MELS,
      embed_dim: DEFAULT_EMBED_DIM,
      kv_dim: DEFAULT_KV_DIM,
      max_token_context: DEFAULT_MAX_TOKEN_CONTEXT,
      n_audio_ctx: DEFAULT_N_AUDIO_CTX,
      window_samples: DEFAULT_WINDOW_SAMPLES,
    }
  }

  // -- vocab ----------------------------------------------------------
  /// Decoder output vocabulary size.
  #[inline(always)]
  pub const fn vocab(&self) -> usize {
    self.vocab
  }
  /// Builder form of [`Self::set_vocab`].
  #[must_use]
  #[inline(always)]
  pub const fn with_vocab(mut self, vocab: usize) -> Self {
    self.set_vocab(vocab);
    self
  }
  /// Sets [`Self::vocab`] in place.
  #[inline(always)]
  pub const fn set_vocab(&mut self, vocab: usize) -> &mut Self {
    self.vocab = vocab;
    self
  }

  // -- n_mels -----------------------------------------------------------
  /// Mel-spectrogram feature bins the mel stage produces.
  #[inline(always)]
  pub const fn n_mels(&self) -> usize {
    self.n_mels
  }
  /// Builder form of [`Self::set_n_mels`].
  #[must_use]
  #[inline(always)]
  pub const fn with_n_mels(mut self, n_mels: usize) -> Self {
    self.set_n_mels(n_mels);
    self
  }
  /// Sets [`Self::n_mels`] in place.
  #[inline(always)]
  pub const fn set_n_mels(&mut self, n_mels: usize) -> &mut Self {
    self.n_mels = n_mels;
    self
  }

  // -- embed_dim ----------------------------------------------------------
  /// Encoder output embedding width.
  #[inline(always)]
  pub const fn embed_dim(&self) -> usize {
    self.embed_dim
  }
  /// Builder form of [`Self::set_embed_dim`].
  #[must_use]
  #[inline(always)]
  pub const fn with_embed_dim(mut self, embed_dim: usize) -> Self {
    self.set_embed_dim(embed_dim);
    self
  }
  /// Sets [`Self::embed_dim`] in place.
  #[inline(always)]
  pub const fn set_embed_dim(&mut self, embed_dim: usize) -> &mut Self {
    self.embed_dim = embed_dim;
    self
  }

  // -- kv_dim -----------------------------------------------------------
  /// Decoder KV-cache channel width (`embed_dim * decoder_layers`).
  #[inline(always)]
  pub const fn kv_dim(&self) -> usize {
    self.kv_dim
  }
  /// Builder form of [`Self::set_kv_dim`].
  #[must_use]
  #[inline(always)]
  pub const fn with_kv_dim(mut self, kv_dim: usize) -> Self {
    self.set_kv_dim(kv_dim);
    self
  }
  /// Sets [`Self::kv_dim`] in place.
  #[inline(always)]
  pub const fn set_kv_dim(&mut self, kv_dim: usize) -> &mut Self {
    self.kv_dim = kv_dim;
    self
  }

  // -- max_token_context ------------------------------------------------
  /// Maximum decoder token context.
  #[inline(always)]
  pub const fn max_token_context(&self) -> usize {
    self.max_token_context
  }
  /// Builder form of [`Self::set_max_token_context`].
  #[must_use]
  #[inline(always)]
  pub const fn with_max_token_context(mut self, max_token_context: usize) -> Self {
    self.set_max_token_context(max_token_context);
    self
  }
  /// Sets [`Self::max_token_context`] in place.
  #[inline(always)]
  pub const fn set_max_token_context(&mut self, max_token_context: usize) -> &mut Self {
    self.max_token_context = max_token_context;
    self
  }

  // -- n_audio_ctx --------------------------------------------------------
  /// Encoder audio-context length (time steps in `encoder_output_embeds`).
  #[inline(always)]
  pub const fn n_audio_ctx(&self) -> usize {
    self.n_audio_ctx
  }
  /// Builder form of [`Self::set_n_audio_ctx`].
  #[must_use]
  #[inline(always)]
  pub const fn with_n_audio_ctx(mut self, n_audio_ctx: usize) -> Self {
    self.set_n_audio_ctx(n_audio_ctx);
    self
  }
  /// Sets [`Self::n_audio_ctx`] in place.
  #[inline(always)]
  pub const fn set_n_audio_ctx(&mut self, n_audio_ctx: usize) -> &mut Self {
    self.n_audio_ctx = n_audio_ctx;
    self
  }

  // -- window_samples -----------------------------------------------------
  /// Samples per encoder window.
  #[inline(always)]
  pub const fn window_samples(&self) -> usize {
    self.window_samples
  }
  /// Builder form of [`Self::set_window_samples`].
  #[must_use]
  #[inline(always)]
  pub const fn with_window_samples(mut self, window_samples: usize) -> Self {
    self.set_window_samples(window_samples);
    self
  }
  /// Sets [`Self::window_samples`] in place.
  #[inline(always)]
  pub const fn set_window_samples(&mut self, window_samples: usize) -> &mut Self {
    self.window_samples = window_samples;
    self
  }

  /// Whether this model understands languages other than English — every
  /// vocabulary size except English-only's `51864` (Swift
  /// `ModelUtilities.isModelMultilingual(logitsDim:)`,
  /// `WhisperKit/Utilities/ModelUtilities.swift:124-126`). Delegates to
  /// [`is_model_multilingual`] — the same check
  /// [`crate::audio::whisper::model::detect_variant`] uses — instead of
  /// restating the `51864` literal a third time in this crate.
  #[inline(always)]
  pub const fn is_multilingual(&self) -> bool {
    is_model_multilingual(self.vocab)
  }
}

// ---------------------------------------------------------------------
// AlignmentView
// ---------------------------------------------------------------------

/// Borrowed, read-only view over a flat `rows * cols` cross-attention
/// alignment-weight buffer, one column per encoder audio-context step
/// (spec §5.4's `AlignmentView<'_>`; mirrors Swift's raw `alignmentWeights`
/// `MLMultiArray` without copying it). When a backend produces it the row
/// count is FIXED at that backend's once-allocated size, not a high-water
/// mark: row `i` holds the weights the last
/// [`InferenceBackend::commit_alignment_row`] wrote for context token `i` —
/// committed by THIS window, left stale by an earlier one, or the
/// construction-time zero if no window ever committed it, exactly like
/// Swift's once-allocated tensor (`TextDecoder.swift:141`) which
/// `DecodingInputs.reset` never clears (`Models.swift:312-322`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AlignmentView<'a> {
  data: &'a [f32],
  rows: usize,
  cols: usize,
}

impl<'a> AlignmentView<'a> {
  /// Wraps `data` as a `rows * cols` row-major view.
  ///
  /// # Panics
  /// If `data.len() != rows * cols`.
  pub fn new(data: &'a [f32], rows: usize, cols: usize) -> Self {
    assert_eq!(
      data.len(),
      rows * cols,
      "AlignmentView: data.len() ({}) != rows ({rows}) * cols ({cols})",
      data.len()
    );
    Self { data, rows, cols }
  }

  /// Number of decoded-token rows.
  #[inline(always)]
  pub const fn rows(&self) -> usize {
    self.rows
  }

  /// Number of encoder audio-context columns.
  #[inline(always)]
  pub const fn cols(&self) -> usize {
    self.cols
  }

  /// The alignment weights for token row `index`.
  ///
  /// # Panics
  /// If `index >= self.rows()`.
  #[inline(always)]
  pub fn row(&self, index: usize) -> &'a [f32] {
    &self.data[index * self.cols..(index + 1) * self.cols]
  }

  /// The full flat `rows * cols` buffer, row-major.
  #[inline(always)]
  pub const fn data(&self) -> &'a [f32] {
    self.data
  }
}

// ---------------------------------------------------------------------
// AlignmentMatrix
// ---------------------------------------------------------------------

/// Owned `rows * cols` cross-attention alignment-weight buffer — the port
/// of Swift's per-attempt `decodingResult.cache?.alignmentWeights`
/// snapshot (`TranscribeTask.swift:198`). A fallback ladder tries several
/// decode attempts per window, and every later attempt's (or the next
/// window's) [`InferenceBackend::commit_alignment_row`] overwrites rows of
/// the shared live accumulator IN PLACE —
/// [`InferenceBackend::reset_decoder_state`] deliberately leaves the
/// buffer's contents, mirroring Swift's once-allocated tensor
/// (`TextDecoder.swift:141`) that `DecodingInputs.reset` never clears
/// (`Models.swift:312-322`) — so an [`AlignmentView`] borrowed from that
/// live state would not survive those overwrites, and the accepted
/// attempt's weights must be copied out into owned data before then.
/// Swift's by-reference `DecodingCache` is temporally safe only because
/// `addWordTimestamps` runs before the next decode; this owned snapshot is
/// the sync-Rust equivalent. See [`AlignmentView::to_matrix`] for the
/// copy-out.
#[derive(Debug, Clone, PartialEq)]
pub struct AlignmentMatrix {
  data: Vec<f32>,
  rows: usize,
  cols: usize,
}

impl AlignmentMatrix {
  /// Wraps `data` as an owned `rows * cols` row-major matrix.
  ///
  /// # Panics
  /// If `data.len() != rows * cols`.
  pub fn new(data: Vec<f32>, rows: usize, cols: usize) -> Self {
    assert_eq!(
      data.len(),
      rows * cols,
      "AlignmentMatrix: data.len() ({}) != rows ({rows}) * cols ({cols})",
      data.len()
    );
    Self { data, rows, cols }
  }

  /// Number of decoded-token rows.
  #[inline(always)]
  pub const fn rows(&self) -> usize {
    self.rows
  }

  /// Number of encoder audio-context columns.
  #[inline(always)]
  pub const fn cols(&self) -> usize {
    self.cols
  }

  /// Borrows this matrix as an [`AlignmentView`].
  #[inline(always)]
  pub fn view(&self) -> AlignmentView<'_> {
    AlignmentView::new(&self.data, self.rows, self.cols)
  }
}

impl AlignmentView<'_> {
  /// Copies this view's data out into an owned [`AlignmentMatrix`] (see
  /// its doc for why word-timestamp code needs the copy). The copy is the
  /// full fixed-size accumulator (`(max_token_context + 1) * n_audio_ctx`
  /// f32), not a written prefix — negligible against a window's decode
  /// cost, and a rows-cap "optimization" here would reintroduce the
  /// truncated-view divergence this fixed-size contract exists to prevent
  /// (whisper #41).
  pub fn to_matrix(&self) -> AlignmentMatrix {
    AlignmentMatrix::new(self.data.to_vec(), self.rows, self.cols)
  }
}

// ---------------------------------------------------------------------
// BackendError
// ---------------------------------------------------------------------

/// A model's output feature dictionary lacks an expected named output.
///
/// Payload of [`BackendError::MissingFeature`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingFeature {
  /// Which model produced the incomplete output (e.g. `"encoder"`).
  model: &'static str,
  /// The missing feature's name.
  name: &'static str,
}

impl MissingFeature {
  /// Construct from the model that produced the incomplete output and the
  /// missing feature's name.
  #[inline(always)]
  pub const fn new(model: &'static str, name: &'static str) -> Self {
    Self { model, name }
  }

  /// Which model produced the incomplete output (e.g. `"encoder"`).
  #[inline(always)]
  pub const fn model(&self) -> &'static str {
    self.model
  }

  /// The missing feature's name.
  #[inline(always)]
  pub const fn name(&self) -> &'static str {
    self.name
  }
}

/// The audio window's sample count doesn't match what the backend
/// expects.
///
/// Payload of [`BackendError::AudioLength`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AudioLength {
  /// Samples actually provided.
  got: usize,
  /// Samples the backend expects.
  expected: usize,
}

impl AudioLength {
  /// Construct from the samples actually provided and the samples the
  /// backend expects.
  #[inline(always)]
  pub const fn new(got: usize, expected: usize) -> Self {
    Self { got, expected }
  }

  /// Samples actually provided.
  #[inline(always)]
  pub const fn got(&self) -> usize {
    self.got
  }

  /// Samples the backend expects.
  #[inline(always)]
  pub const fn expected(&self) -> usize {
    self.expected
  }
}

/// A loaded model does not satisfy the load contract its door states.
///
/// Payload of [`BackendError::Contract`], carrying which of the three models it
/// is about beside the clause that failed.
///
/// # One variant for every clause, deliberately
///
/// `audio::identity` and `audio::speaker` give the two "unsatisfiable" clauses
/// — a REQUIRED input the contract does not name, and a declared state buffer —
/// error variants of their own, because those are about what the door cannot
/// SUPPLY rather than about a named feature's declared shape. Here they render
/// as expected/actual pairs on the same variant: this error type is the whisper
/// pipeline's transport, no caller branches on the distinction, and three more
/// arms on [`BackendError`] would be three more arms every match in the
/// pipeline has to carry. The message says which clause failed either way.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractMismatch {
  model: &'static str,
  feature: String,
  expected: String,
  actual: String,
}

impl ContractMismatch {
  /// Construct from the model's short name, the feature the clause is about,
  /// the contract's statement, and what the model declares.
  #[inline(always)]
  pub const fn new(model: &'static str, feature: String, expected: String, actual: String) -> Self {
    Self {
      model,
      feature,
      expected,
      actual,
    }
  }

  /// Which of the three models: `mel`, `encoder` or `decoder`.
  #[inline(always)]
  pub const fn model(&self) -> &'static str {
    self.model
  }
  /// The feature the failed clause is about.
  #[inline(always)]
  pub fn feature(&self) -> &str {
    &self.feature
  }
  /// What the contract states.
  #[inline(always)]
  pub fn expected(&self) -> &str {
    &self.expected
  }
  /// What the model declares.
  #[inline(always)]
  pub fn actual(&self) -> &str {
    &self.actual
  }
}

/// Failure calling into an [`InferenceBackend`] — mel extraction, encoding,
/// or a decode step.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BackendError {
  /// The CoreML runtime failed to run a prediction.
  #[error("backend prediction failed: {0}")]
  Prediction(#[from] crate::PredictionError),
  /// A backend tensor failed to construct or view.
  #[error("backend tensor failed: {0}")]
  Tensor(#[from] crate::TensorError),
  /// A model's output feature dictionary lacks an expected named output.
  #[error("{} model output is missing feature `{}`", .0.model(), .0.name())]
  MissingFeature(MissingFeature),
  /// A loaded model does not satisfy the load contract its door states.
  #[error(
    "{} model contract mismatch on `{}`: expected {}, got {}",
    .0.model(), .0.feature(), .0.expected(), .0.actual()
  )]
  Contract(ContractMismatch),
  /// The audio window's sample count doesn't match what the backend
  /// expects.
  #[error("audio window has {} samples, backend expects {}", .0.got(), .0.expected())]
  AudioLength(AudioLength),
  /// The caller's audio window carried a NaN or an infinity, which would have
  /// entered the mel model unexamined. Carries the flat index of the first
  /// offending sample.
  #[error("audio window has a non-finite sample at index {0}")]
  NonFiniteAudio(usize),
  /// The caller's audio window carried a sample finite in `f32` whose
  /// magnitude exceeds `f16`'s finite range (`|x| > f16::MAX`, i.e. `65504`),
  /// which CoreML's narrowing into the mel model's declared `float16` `audio`
  /// input would round to an f16 infinity — [`Self::NonFiniteAudio`]'s failure
  /// one representability step in. Carries the flat index of the first
  /// offending sample.
  #[error(
    "audio window has a sample at index {0} that is finite in f32 but overflows the mel      model's f16 input domain (|x| > f16::MAX)"
  )]
  F16OverflowAudio(usize),
  /// [`mock::MockBackend`]'s scripted logits ran out before the decode loop
  /// finished — the test forgot to script an explicit end-of-text step.
  /// Carries the step index the script had no entry for.
  #[error("mock script exhausted at step {0}")]
  ScriptExhausted(usize),
  /// A failure scripted by [`mock::MockBackend::fail_on_call`] — lets
  /// hermetic tests drive error paths (e.g. a transiently failing
  /// language probe) that no scripted-logits vocabulary can express.
  /// Carries the 1-based ordinal of the failing `decode_step` call.
  #[error("scripted decode-step failure on call {0}")]
  ScriptedFailure(usize),
}

// ---------------------------------------------------------------------
// InferenceBackend
// ---------------------------------------------------------------------

/// Seam over the three CoreML-shaped inference stages a Whisper pipeline
/// drives per window: mel feature extraction, encoding, and the
/// autoregressive decode step (spec §5.4). A real backend implements this
/// against `crate::Model`s; [`mock::MockBackend`] implements it here
/// with no compiled model at all, for hermetic decode-loop,
/// fallback-ladder, windowing, and early-stop tests (spec §9.1).
pub trait InferenceBackend {
  /// Mel features for one 30 s window.
  type Features;
  /// Encoder output for one window.
  type EncoderOutput;
  /// Pre-allocated, reusable decoder tensors (ports Swift `DecodingInputs`).
  type DecoderState;

  /// Extracts mel-spectrogram features from one window of audio samples.
  ///
  /// # Errors
  /// [`BackendError`] if feature extraction fails.
  fn extract_features(&self, audio: &[f32]) -> Result<Self::Features, BackendError>;

  /// Runs the encoder over previously extracted features.
  ///
  /// # Errors
  /// [`BackendError`] if encoding fails.
  fn encode(&self, features: &Self::Features) -> Result<Self::EncoderOutput, BackendError>;

  /// Allocates a fresh decoder state (Swift `DecodingInputs::init`).
  ///
  /// # Errors
  /// [`BackendError`] if the backend cannot allocate its decoder tensors.
  fn new_decoder_state(&self) -> Result<Self::DecoderState, BackendError>;

  /// Ports `DecodingInputs.reset(maxTokenContext:)` (Models.swift:312-322).
  fn reset_decoder_state(&self, state: &mut Self::DecoderState);

  /// One autoregressive step: consume `token` at `position`, write the full
  /// vocab logits (converted to f32 once) into the reused `logits` buffer,
  /// advance the KV cache/masks inside `state`, and STAGE this step's
  /// alignment row (row `position + 1`) — the row lands in the persistent
  /// accumulator only if the decode loop then calls
  /// [`Self::commit_alignment_row`], never from within this step (Swift
  /// updates alignment weights only on non-completing steps,
  /// `TextDecoder.swift:673-717`).
  ///
  /// `position` is 0-based and must be in `0..dims().max_token_context()`:
  /// it is the KV-cache slot this step fills (the caches are
  /// `[1, kv, 1, max_token_context]`, per the introspected tiny model).
  /// On success the backend leaves `logits` exactly `dims().vocab()` long,
  /// holding only this step's values — the buffer is fully overwritten,
  /// never appended to, so no stale data from prior steps survives.
  ///
  /// # Errors
  /// [`BackendError`] if the step fails.
  fn decode_step(
    &self,
    token: u32,
    position: usize,
    encoder_output: &Self::EncoderOutput,
    state: &mut Self::DecoderState,
    logits: &mut Vec<f32>,
  ) -> Result<(), BackendError>;

  /// Commits the alignment row staged by the immediately preceding
  /// [`Self::decode_step`] into the persistent accumulator, at row
  /// `position + 1`. Ports the placement of `updateAlignmentWeights`
  /// (`TextDecoder.swift:709-717`): the decode loop calls this only after a
  /// step's completion check fails, so a completing step's staged row is
  /// never committed — its slot instead retains the previous window's value
  /// (or the initial zero), exactly like Swift's once-allocated tensor
  /// (`TextDecoder.swift:141`, `Models.swift:312-322`). No-op when the
  /// preceding step staged nothing (model without the alignment head, or a
  /// step whose outputs lacked the feature).
  fn commit_alignment_row(&self, state: &mut Self::DecoderState);

  /// Accumulated per-token alignment weights: the FULL fixed-size
  /// accumulator (`max_token_context + 1` rows, one column per audio-ctx
  /// step), mirroring Swift's once-allocated `[kvCacheMaxSequenceLength,
  /// n_audio_ctx]` tensor. Rows the current window did not commit read back
  /// as an earlier window's bytes or the construction-time zero, exactly
  /// like Swift's tensor across `DecodingInputs.reset` (`Models.swift:312-322`).
  /// `None` unless the current window has committed at least one row via
  /// [`Self::commit_alignment_row`] — the port of Swift's `hasAlignment`
  /// nil-cache gate (`TextDecoder.swift:568,711,764-771`): a window whose
  /// steps produced no alignment slice yields no view, so the caller's whole
  /// word-timestamp block is skipped (`TranscribeTask.swift:197-199`).
  fn alignment_weights<'state>(
    &self,
    state: &'state Self::DecoderState,
  ) -> Option<AlignmentView<'state>>;

  /// Static shape/vocabulary description of the loaded model.
  fn dims(&self) -> ModelDims;
}