speakrs 0.6.0

Fast Rust speaker diarization with pyannote-level accuracy and native CPU/CoreML/CUDA inference
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
//! Checked tensor layout used by inference adapters before native or ORT work

use std::fmt;

/// Tensor shape, length, rank, or output-type mismatch found while binding inputs or decoding outputs
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TensorShapeError {
    /// Multiplying dimensions overflowed `usize`
    Overflow {
        /// Which bind or decode step failed
        context: &'static str,
    },
    /// A tensor dimension was negative or could not fit in `usize`
    InvalidDimension {
        /// Which bind or decode step failed
        context: &'static str,
        /// Observed dimension
        dimension: i64,
    },
    /// Flat buffer length did not match the shape product
    LengthMismatch {
        /// Which bind or decode step failed
        context: &'static str,
        /// Product of the declared dimensions
        expected: usize,
        /// Observed buffer length
        actual: usize,
    },
    /// Rank did not match the model contract
    RankMismatch {
        /// Which decode step failed
        context: &'static str,
        /// Required rank
        expected: usize,
        /// Observed rank
        actual: usize,
        /// Observed dimensions
        shape: Vec<usize>,
    },
    /// Tensor dimensions did not match the model contract
    ShapeMismatch {
        /// Which decode step failed
        context: &'static str,
        /// Required dimensions
        expected: Vec<usize>,
        /// Observed dimensions
        actual: Vec<usize>,
    },
    /// One tensor axis did not match the model contract
    AxisMismatch {
        /// Which decode step failed
        context: &'static str,
        /// Zero-based axis index
        axis: usize,
        /// Required axis length
        expected: usize,
        /// Observed axis length
        actual: usize,
    },
    /// CoreML output was not Float16 or Float32
    #[cfg(any(test, feature = "coreml"))]
    #[cfg_attr(docsrs, doc(cfg(feature = "coreml")))]
    UnsupportedDType {
        /// Which decode step failed
        context: &'static str,
        /// Reported CoreML data type
        dtype: &'static str,
    },
}

impl fmt::Display for TensorShapeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Overflow { context } => {
                write!(formatter, "{context}: tensor shape product overflowed")
            }
            Self::InvalidDimension { context, dimension } if *dimension < 0 => write!(
                formatter,
                "{context}: expected non-negative tensor dimensions, got {dimension}"
            ),
            Self::InvalidDimension { context, dimension } => write!(
                formatter,
                "{context}: tensor dimension {dimension} does not fit in usize"
            ),
            Self::LengthMismatch {
                context,
                expected,
                actual,
            } => write!(
                formatter,
                "{context}: expected {expected} values, got {actual}"
            ),
            Self::RankMismatch {
                context,
                expected,
                actual,
                shape,
            } => write!(
                formatter,
                "{context}: expected rank {expected}, got rank {actual} shape {shape:?}"
            ),
            Self::ShapeMismatch {
                context,
                expected,
                actual,
            } => write!(
                formatter,
                "{context}: expected shape {expected:?}, got {actual:?}"
            ),
            Self::AxisMismatch {
                context,
                axis,
                expected,
                actual,
            } => write!(
                formatter,
                "{context}: expected axis {axis} to have length {expected}, got {actual}"
            ),
            #[cfg(any(test, feature = "coreml"))]
            Self::UnsupportedDType { context, dtype } => write!(
                formatter,
                "{context}: CoreML output type {dtype} is not Float16 or Float32"
            ),
        }
    }
}

impl std::error::Error for TensorShapeError {}

/// CoreML output types that adapters may decode
#[cfg(any(test, feature = "coreml"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CoreMlOutputDType {
    /// IEEE Float16 payload
    Float16,
    /// IEEE Float32 payload
    Float32,
}

/// Tags covering CoreML types the decoder must accept or reject
#[cfg(any(test, feature = "coreml"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CoreMlDTypeTag {
    /// IEEE Float16
    Float16,
    /// IEEE Float32
    Float32,
    /// IEEE Float64
    Float64,
    /// Signed 32-bit integer
    Int32,
    /// Signed 8-bit integer
    Int8,
    /// Any other CoreML type
    #[cfg(feature = "coreml")]
    Other,
}

#[cfg(any(test, feature = "coreml"))]
impl CoreMlOutputDType {
    /// Accept Float16 or Float32 and reject every other CoreML type
    pub(crate) fn try_from_tag(
        tag: CoreMlDTypeTag,
        context: &'static str,
    ) -> Result<Self, TensorShapeError> {
        match tag {
            CoreMlDTypeTag::Float16 => Ok(Self::Float16),
            CoreMlDTypeTag::Float32 => Ok(Self::Float32),
            CoreMlDTypeTag::Float64 => Err(TensorShapeError::UnsupportedDType {
                context,
                dtype: "Float64",
            }),
            CoreMlDTypeTag::Int32 => Err(TensorShapeError::UnsupportedDType {
                context,
                dtype: "Int32",
            }),
            CoreMlDTypeTag::Int8 => Err(TensorShapeError::UnsupportedDType {
                context,
                dtype: "Int8",
            }),
            #[cfg(feature = "coreml")]
            CoreMlDTypeTag::Other => Err(TensorShapeError::UnsupportedDType {
                context,
                dtype: "unsupported",
            }),
        }
    }
}

#[cfg(any(test, feature = "migraphx", feature = "coreml"))]
/// Declared dimensions plus their checked element count
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TensorLayout {
    dims: Vec<usize>,
    element_count: usize,
}

#[cfg(any(test, feature = "migraphx", feature = "coreml"))]
impl TensorLayout {
    /// Build a layout with a checked shape product
    pub(crate) fn from_dims(
        dims: &[usize],
        context: &'static str,
    ) -> Result<Self, TensorShapeError> {
        Ok(Self {
            dims: dims.to_vec(),
            element_count: checked_element_count(dims, context)?,
        })
    }

    /// Build a layout from an ORT shape after checking signed dimensions
    #[cfg(feature = "migraphx")]
    pub(crate) fn from_ort_shape(
        shape: &[i64],
        context: &'static str,
    ) -> Result<Self, TensorShapeError> {
        let dims = shape
            .iter()
            .copied()
            .map(|dimension| {
                usize::try_from(dimension)
                    .map_err(|_| TensorShapeError::InvalidDimension { context, dimension })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Self::from_dims(&dims, context)
    }

    pub(crate) fn element_count(&self) -> usize {
        self.element_count
    }

    #[cfg(feature = "coreml")]
    pub(crate) fn dims(&self) -> &[usize] {
        &self.dims
    }

    /// Require `data` to have exactly this layout's element count
    #[cfg(any(test, feature = "coreml"))]
    pub(crate) fn bind<'a>(&self, data: &'a [f32]) -> Result<&'a [f32], TensorShapeError> {
        require_exact_len(data.len(), self.element_count, "coreml input")?;
        Ok(data)
    }

    pub(crate) fn try_rank(
        &self,
        expected: usize,
        context: &'static str,
    ) -> Result<&[usize], TensorShapeError> {
        if self.dims.len() == expected {
            Ok(&self.dims)
        } else {
            Err(TensorShapeError::RankMismatch {
                context,
                expected,
                actual: self.dims.len(),
                shape: self.dims.clone(),
            })
        }
    }

    pub(crate) fn try_rank3(
        &self,
        context: &'static str,
    ) -> Result<(usize, usize, usize), TensorShapeError> {
        let dims = self.try_rank(3, context)?;
        Ok((dims[0], dims[1], dims[2]))
    }

    /// Require dimensions to match a model's exact output contract
    #[cfg(any(feature = "migraphx", feature = "coreml"))]
    pub(crate) fn try_exact_dims(
        &self,
        expected: &[usize],
        context: &'static str,
    ) -> Result<(), TensorShapeError> {
        if self.dims == expected {
            Ok(())
        } else {
            Err(TensorShapeError::ShapeMismatch {
                context,
                expected: expected.to_vec(),
                actual: self.dims.clone(),
            })
        }
    }
}

/// Decoded CoreML tensor with checked layout
#[cfg(any(test, feature = "coreml"))]
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CoreMlTensor {
    data: Vec<f32>,
    layout: TensorLayout,
}

#[cfg(any(test, feature = "coreml"))]
impl CoreMlTensor {
    /// Bind decoded values to a checked layout
    pub(crate) fn try_from_decoded(
        data: Vec<f32>,
        shape: Vec<usize>,
        context: &'static str,
    ) -> Result<Self, TensorShapeError> {
        let layout = TensorLayout::from_dims(&shape, context)?;
        require_exact_len(data.len(), layout.element_count(), context)?;
        Ok(Self { data, layout })
    }

    #[cfg(feature = "coreml")]
    pub(crate) fn layout(&self) -> &TensorLayout {
        &self.layout
    }

    pub(crate) fn try_rank3(
        &self,
        context: &'static str,
    ) -> Result<(usize, usize, usize), TensorShapeError> {
        self.layout.try_rank3(context)
    }

    #[cfg(feature = "coreml")]
    pub(crate) fn into_data(self) -> Vec<f32> {
        self.data
    }

    #[cfg(any(feature = "coreml", all(test, feature = "migraphx")))]
    pub(crate) fn into_parts(self) -> (TensorLayout, Vec<f32>) {
        (self.layout, self.data)
    }

    #[cfg(feature = "coreml")]
    pub(crate) fn rank3_hw(
        self,
        context: &'static str,
    ) -> Result<(Vec<f32>, usize, usize), TensorShapeError> {
        let (_, frames, classes) = self.try_rank3(context)?;
        Ok((self.data, frames, classes))
    }
}

#[cfg(any(test, feature = "migraphx", feature = "coreml"))]
pub(crate) fn checked_element_count(
    dims: &[usize],
    context: &'static str,
) -> Result<usize, TensorShapeError> {
    let mut count = 1usize;
    for &dim in dims {
        count = count
            .checked_mul(dim)
            .ok_or(TensorShapeError::Overflow { context })?;
    }
    Ok(count)
}

#[cfg(any(test, feature = "migraphx", feature = "coreml"))]
pub(crate) fn require_exact_len(
    actual: usize,
    expected: usize,
    context: &'static str,
) -> Result<(), TensorShapeError> {
    if actual == expected {
        Ok(())
    } else {
        Err(TensorShapeError::LengthMismatch {
            context,
            expected,
            actual,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CoreMlDTypeTag, CoreMlOutputDType, CoreMlTensor, TensorLayout, TensorShapeError,
        checked_element_count,
    };

    #[test]
    fn bind_accepts_exact_input_length() {
        let layout = TensorLayout::from_dims(&[1, 1, 4], "coreml input").unwrap();
        let data = [1.0, 2.0, 3.0, 4.0];
        assert_eq!(layout.bind(&data).unwrap(), &data);
    }

    #[test]
    fn bind_rejects_short_input() {
        let layout = TensorLayout::from_dims(&[1, 1, 4], "coreml input").unwrap();
        let error = layout.bind(&[1.0, 2.0, 3.0]).unwrap_err();
        assert_eq!(
            error,
            TensorShapeError::LengthMismatch {
                context: "coreml input",
                expected: 4,
                actual: 3,
            }
        );
    }

    #[test]
    fn bind_rejects_long_input() {
        let layout = TensorLayout::from_dims(&[2, 2], "coreml input").unwrap();
        let error = layout.bind(&[1.0, 2.0, 3.0, 4.0, 5.0]).unwrap_err();
        assert_eq!(
            error,
            TensorShapeError::LengthMismatch {
                context: "coreml input",
                expected: 4,
                actual: 5,
            }
        );
    }

    #[test]
    fn shape_product_reports_overflow() {
        let error = checked_element_count(&[usize::MAX, 2], "coreml input").unwrap_err();
        assert_eq!(
            error,
            TensorShapeError::Overflow {
                context: "coreml input"
            }
        );
        assert!(TensorLayout::from_dims(&[usize::MAX, 3], "coreml input").is_err());
    }

    #[test]
    fn output_dtype_rejects_float64_int32_and_int8() {
        for (tag, dtype) in [
            (CoreMlDTypeTag::Float64, "Float64"),
            (CoreMlDTypeTag::Int32, "Int32"),
            (CoreMlDTypeTag::Int8, "Int8"),
        ] {
            let error = CoreMlOutputDType::try_from_tag(tag, "coreml output").unwrap_err();
            assert_eq!(
                error,
                TensorShapeError::UnsupportedDType {
                    context: "coreml output",
                    dtype,
                }
            );
        }
        assert_eq!(
            CoreMlOutputDType::try_from_tag(CoreMlDTypeTag::Float16, "coreml output").unwrap(),
            CoreMlOutputDType::Float16
        );
        assert_eq!(
            CoreMlOutputDType::try_from_tag(CoreMlDTypeTag::Float32, "coreml output").unwrap(),
            CoreMlOutputDType::Float32
        );
    }

    #[test]
    fn tensor_rejects_wrong_rank_and_element_count() {
        let rank0 = CoreMlTensor::try_from_decoded(vec![1.0], vec![], "coreml output").unwrap();
        assert!(matches!(
            rank0.try_rank3("coreml output"),
            Err(TensorShapeError::RankMismatch {
                expected: 3,
                actual: 0,
                ..
            })
        ));

        let rank2 =
            CoreMlTensor::try_from_decoded(vec![1.0, 2.0], vec![1, 2], "coreml output").unwrap();
        assert!(matches!(
            rank2.try_rank3("coreml output"),
            Err(TensorShapeError::RankMismatch {
                expected: 3,
                actual: 2,
                ..
            })
        ));

        let rank3 = CoreMlTensor::try_from_decoded(
            vec![1.0, 2.0, 3.0, 4.0],
            vec![1, 2, 2],
            "coreml output",
        )
        .unwrap();
        assert_eq!(rank3.try_rank3("coreml output").unwrap(), (1, 2, 2));

        let error =
            CoreMlTensor::try_from_decoded(vec![1.0], vec![1, 2, 2], "coreml output").unwrap_err();
        assert_eq!(
            error,
            TensorShapeError::LengthMismatch {
                context: "coreml output",
                expected: 4,
                actual: 1,
            }
        );
    }
}