coremlit 0.1.2

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
//! Structured error types for the CoreML layer.

use std::path::PathBuf;

use objc2_foundation::NSError;

use crate::DataType;

/// Structured capture of an `NSError` returned by CoreML.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{domain} (code {code}): {message}")]
pub struct NsErrorInfo {
  domain: String,
  code: isize,
  message: String,
}

impl NsErrorInfo {
  /// Construct from a live `NSError` reference.
  pub(crate) fn from_ns_error(error: &NSError) -> Self {
    // Plain accessor message sends on a live NSError reference.
    let (domain, code, message) = (
      error.domain().to_string(),
      error.code(),
      error.localizedDescription().to_string(),
    );
    Self {
      domain,
      code,
      message,
    }
  }

  /// The `NSError` domain.
  #[inline(always)]
  pub fn domain(&self) -> &str {
    &self.domain
  }

  /// The `NSError` code.
  #[inline(always)]
  pub const fn code(&self) -> isize {
    self.code
  }

  /// The localized description.
  #[inline(always)]
  pub fn message(&self) -> &str {
    &self.message
  }
}

/// Failure loading a compiled model.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum LoadError {
  /// The model path does not exist.
  ///
  /// Carries the path that was checked.
  #[error("model not found at `{}`", .0.display())]
  NotFound(PathBuf),
  /// CoreML rejected the model.
  #[error("core ml failed to load model: {0}")]
  Native(NsErrorInfo),
}

/// Failure compiling an `.mlpackage`/`.mlmodel` into an `.mlmodelc`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CompileError {
  /// The source path does not exist.
  ///
  /// Carries the path that was checked.
  #[error("model source not found at `{}`", .0.display())]
  NotFound(PathBuf),
  /// CoreML rejected the compilation.
  #[error("core ml failed to compile model: {0}")]
  Native(NsErrorInfo),
}

/// Failure running a prediction.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PredictionError {
  /// The output feature dictionary lacks an expected name.
  ///
  /// Carries the feature name that was absent.
  #[error("prediction output is missing feature `{0}`")]
  MissingOutput(String),
  /// An output feature was not a multi-array.
  ///
  /// Carries the feature name with the wrong kind.
  #[error("prediction output `{0}` is not a multi-array")]
  NotMultiArray(String),
  /// CoreML reported a prediction failure.
  #[error("core ml prediction failed: {0}")]
  Native(NsErrorInfo),
  /// Stateful prediction requires macOS 15 (MLState).
  #[error("stateful prediction is unavailable on this OS (requires macOS 15)")]
  StateUnsupported,
  /// De-aliasing an output array that shared its native buffer with
  /// another live array (an input, or another output name) failed.
  #[error("failed to de-alias a prediction output: {0}")]
  AliasCopyFailed(TensorError),
}

/// The array's element type differs from the requested view type.
///
/// Payload of [`TensorError::DataTypeMismatch`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataTypeMismatch {
  /// Requested element type.
  expected: DataType,
  /// The array's actual element type.
  actual: DataType,
}

impl DataTypeMismatch {
  /// Construct from the requested and the actual element type.
  #[inline(always)]
  pub const fn new(expected: DataType, actual: DataType) -> Self {
    Self { expected, actual }
  }

  /// Requested element type.
  #[inline(always)]
  pub const fn expected(&self) -> DataType {
    self.expected
  }

  /// The array's actual element type.
  #[inline(always)]
  pub const fn actual(&self) -> DataType {
    self.actual
  }
}

/// Element count differs from the shape's product.
///
/// Payload of [`TensorError::ShapeMismatch`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShapeMismatch {
  /// Elements implied by the shape.
  expected: usize,
  /// Elements provided.
  actual: usize,
}

impl ShapeMismatch {
  /// Construct from the implied and the provided element count.
  #[inline(always)]
  pub const fn new(expected: usize, actual: usize) -> Self {
    Self { expected, actual }
  }

  /// Elements implied by the shape.
  #[inline(always)]
  pub const fn expected(&self) -> usize {
    self.expected
  }

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

/// Index tuple rank differs from the array rank.
///
/// Payload of [`TensorError::RankMismatch`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RankMismatch {
  /// The array's rank.
  expected: usize,
  /// Indices provided.
  actual: usize,
}

impl RankMismatch {
  /// Construct from the array's rank and the number of indices provided.
  #[inline(always)]
  pub const fn new(expected: usize, actual: usize) -> Self {
    Self { expected, actual }
  }

  /// The array's rank.
  #[inline(always)]
  pub const fn expected(&self) -> usize {
    self.expected
  }

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

/// A linear or dimensional index is out of bounds.
///
/// Payload of [`TensorError::IndexOutOfBounds`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexOutOfBounds {
  /// Offending index.
  index: usize,
  /// Bound it violated.
  len: usize,
}

// `len` names the BOUND one failed index violated, not a collection length
// this payload owns, so there is nothing for an `is_empty` to mean here.
#[allow(clippy::len_without_is_empty)]
impl IndexOutOfBounds {
  /// Construct from the offending index and the bound it violated.
  #[inline(always)]
  pub const fn new(index: usize, len: usize) -> Self {
    Self { index, len }
  }

  /// Offending index.
  #[inline(always)]
  pub const fn index(&self) -> usize {
    self.index
  }

  /// Bound it violated.
  #[inline(always)]
  pub const fn len(&self) -> usize {
    self.len
  }
}

/// The array's memory layout is not row-major contiguous.
///
/// Payload of [`TensorError::NonContiguous`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NonContiguous {
  /// The array's shape.
  shape: Vec<usize>,
  /// The array's element strides.
  strides: Vec<usize>,
}

impl NonContiguous {
  /// Construct from the array's shape and its element strides.
  #[inline(always)]
  pub const fn new(shape: Vec<usize>, strides: Vec<usize>) -> Self {
    Self { shape, strides }
  }

  /// The array's shape.
  #[inline(always)]
  pub fn shape(&self) -> &[usize] {
    &self.shape
  }

  /// The array's element strides.
  #[inline(always)]
  pub fn strides(&self) -> &[usize] {
    &self.strides
  }
}

/// The shape does not meet an operation's structural requirement.
///
/// Payload of [`TensorError::UnsupportedShape`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsupportedShape {
  /// The offending shape.
  shape: Vec<usize>,
  /// Why the shape was rejected.
  reason: ShapeRequirement,
}

impl UnsupportedShape {
  /// Construct from the offending shape and the requirement it failed.
  #[inline(always)]
  pub const fn new(shape: Vec<usize>, reason: ShapeRequirement) -> Self {
    Self { shape, reason }
  }

  /// The offending shape.
  #[inline(always)]
  pub fn shape(&self) -> &[usize] {
    &self.shape
  }

  /// Why the shape was rejected.
  #[inline(always)]
  pub const fn reason(&self) -> ShapeRequirement {
    self.reason
  }
}

/// A buffer whose element count fits `usize` and whose allocation the Rust
/// allocator refused.
///
/// # Why a refusal and not an abort
///
/// The count is not this crate's to choose. Every buffer this names is sized
/// by [`MultiArray::count`](crate::MultiArray::count) โ€” the product of the axes
/// an `MLMultiArray` declares โ€” and for an array extracted from a prediction
/// those axes are the ARTIFACT's. `checked_element_count` proves the product
/// fits `usize`, and fitting `usize` is strictly weaker than the memory
/// existing: a rank-2 output of `[2^40, 2^15]` counts fine and asks for
/// exabytes. `vec![T::default(); n]` answers that by ABORTING the process,
/// which is not something a caller of a `Result`-returning API can handle, so
/// the buffers sized this way are reserved with `Vec::try_reserve_exact` and
/// this payload is what the refusal carries.
///
/// Named for the same reason [`ShapeOverflow`](TensorError::ShapeOverflow)
/// carries the shape: the element type is half of what was asked for, because
/// the byte size is `elements ยท size_of(data_type)` and the two are not
/// interchangeable across a 2-byte and an 8-byte element.
///
/// Payload of [`TensorError::AllocationFailed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AllocationFailed {
  /// Elements the buffer was asked for.
  elements: usize,
  /// The element type each of them occupies.
  data_type: DataType,
}

impl AllocationFailed {
  /// Construct from the element count that was refused and its element type.
  #[inline(always)]
  pub const fn new(elements: usize, data_type: DataType) -> Self {
    Self {
      elements,
      data_type,
    }
  }

  /// Elements the buffer was asked for.
  #[inline(always)]
  pub const fn elements(&self) -> usize {
    self.elements
  }

  /// The element type each of them occupies.
  #[inline(always)]
  pub const fn data_type(&self) -> DataType {
    self.data_type
  }
}

/// Failure constructing or viewing a multi-array.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TensorError {
  /// The array's element type differs from the requested view type.
  #[error("data type mismatch: expected `{}`, got `{}`", .0.expected(), .0.actual())]
  DataTypeMismatch(DataTypeMismatch),
  /// Element count differs from the shape's product.
  #[error("shape mismatch: expected {} elements, got {}", .0.expected(), .0.actual())]
  ShapeMismatch(ShapeMismatch),
  /// Index tuple rank differs from the array rank.
  #[error("rank mismatch: expected {} indices, got {}", .0.expected(), .0.actual())]
  RankMismatch(RankMismatch),
  /// A linear or dimensional index is out of bounds.
  #[error("index {} out of bounds for length {}", .0.index(), .0.len())]
  IndexOutOfBounds(IndexOutOfBounds),
  /// The array's memory layout is not row-major contiguous.
  #[error("array layout is not contiguous (strides {:?} for shape {:?})", .0.strides(), .0.shape())]
  NonContiguous(NonContiguous),
  /// The data type cannot back an array (no known element size).
  ///
  /// Carries the rejected data type.
  #[error("unsupported data type `{0}` for array construction")]
  UnsupportedDataType(DataType),
  /// CoreML rejected the array construction.
  #[error("core ml multi-array failure: {0}")]
  Native(NsErrorInfo),
  /// CVPixelBuffer creation failed.
  ///
  /// Carries the CVReturn code.
  #[error("pixel buffer creation failed with CVReturn {0}")]
  PixelBuffer(i32),
  /// The shape does not meet an operation's structural requirement.
  #[error("shape {:?} is unsupported: {}", .0.shape(), .0.reason())]
  UnsupportedShape(UnsupportedShape),
  /// A shape's element count, or a size/offset derived from it, overflows
  /// `usize`.
  ///
  /// Carries the offending shape.
  #[error("shape {0:?} element count overflows usize")]
  ShapeOverflow(Vec<usize>),
  /// `MLMultiArray`'s pixel-buffer-backed initializer is unavailable on
  /// this OS.
  #[error("pixel-buffer-backed arrays require macOS 12 or newer")]
  SurfaceUnsupported,
  /// A Rust-side buffer sized from an array's own element count could not be
  /// allocated.
  ///
  /// Distinct from [`Self::ShapeOverflow`], which is the count not EXISTING;
  /// this is a count that exists and memory that does not.
  #[error(
    "could not allocate a {} element `{}` buffer for this array",
    .0.elements(), .0.data_type()
  )]
  AllocationFailed(AllocationFailed),
}

/// Why a shape was rejected by [`TensorError::UnsupportedShape`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Display, derive_more::IsVariant)]
#[display("{}", self.as_str())]
#[non_exhaustive]
pub enum ShapeRequirement {
  /// All dimensions before the last must be 1.
  LeadingDimsUnit,
  /// The shape must have at least one dimension.
  NonEmpty,
  /// Every dimension must be nonzero.
  NonZeroDims,
}

impl ShapeRequirement {
  /// Stable name of the requirement.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::LeadingDimsUnit => "all dimensions before the last must be 1",
      Self::NonEmpty => "the shape must have at least one dimension",
      Self::NonZeroDims => "every dimension must be nonzero",
    }
  }
}

#[cfg(test)]
mod tests;