speakrs 0.7.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
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
use std::path::{Path, PathBuf};

use crate::inference::ExecutionMode;
#[cfg(feature = "online")]
use hf_hub::api::sync::{Api, ApiBuilder, ApiRepo};
#[cfg(feature = "online")]
use hf_hub::{Repo, RepoType};

const SEGMENTATION_ONNX: &str = "segmentation-3.0.onnx";
const EMBEDDING_ONNX: &str = "wespeaker-voxceleb-resnet34.onnx";
const EMBEDDING_MIN_SAMPLES: &str = "wespeaker-voxceleb-resnet34.min_num_samples.txt";

/// Resolved model paths for the speakrs pipeline
///
/// Captures the three root paths needed by [`SegmentationModel`], [`EmbeddingModel`],
/// and `PldaTransform`. Native CPU, CUDA and CoreML models use the base ONNX paths
/// as family selectors; the ONNX files do not need to exist for those modes. CPU and
/// CUDA load `segmentation-3.0.safetensors` and `wespeaker-multimask-tail.safetensors`
/// from the same directory. MIGraphX loads the ONNX files
///
/// [`SegmentationModel`]: crate::inference::segmentation::SegmentationModel
/// [`EmbeddingModel`]: crate::inference::embedding::EmbeddingModel
#[derive(Debug, Clone)]
pub struct ModelBundle {
    segmentation_onnx: PathBuf,
    embedding_onnx: PathBuf,
    plda_dir: PathBuf,
}

impl ModelBundle {
    /// Resolve and validate paths from a local directory containing all model files
    pub fn from_dir(
        models_dir: impl Into<PathBuf>,
    ) -> Result<Self, crate::inference::ModelLoadError> {
        let dir = models_dir.into();
        crate::inference::embedding::read_min_num_samples(&dir.join(EMBEDDING_MIN_SAMPLES))?;

        Ok(Self {
            segmentation_onnx: dir.join(SEGMENTATION_ONNX),
            embedding_onnx: dir.join(EMBEDDING_ONNX),
            plda_dir: dir,
        })
    }

    /// Download models from HuggingFace and resolve paths
    #[cfg(feature = "online")]
    #[cfg_attr(docsrs, doc(cfg(feature = "online")))]
    pub fn from_pretrained(mode: ExecutionMode) -> Result<Self, crate::inference::ModelLoadError> {
        let manager = ModelManager::new()?;
        let dir = manager
            .ensure(mode)
            .map_err(|source| download_error(mode, source))?;
        Self::from_dir(dir)
    }

    /// Segmentation family selector, or the ONNX model path for MIGraphX
    pub fn segmentation_path(&self) -> &Path {
        &self.segmentation_onnx
    }

    /// Embedding family selector, or the ONNX model path for MIGraphX
    pub fn embedding_path(&self) -> &Path {
        &self.embedding_onnx
    }

    /// Directory containing PLDA parameter files
    pub fn plda_dir(&self) -> &Path {
        &self.plda_dir
    }
}

/// Names the CUDA weights in the error when they cannot be downloaded
#[cfg(feature = "online")]
fn download_error(
    mode: ExecutionMode,
    source: hf_hub::api::sync::ApiError,
) -> crate::inference::ModelLoadError {
    #[cfg(feature = "_cuda")]
    if mode.is_cuda() {
        return crate::inference::ModelLoadError::CudaAssetsUnavailable { mode, source };
    }

    let _ = mode;
    source.into()
}

/// Hugging Face repository that hosts the speakrs models
pub const MODEL_REPOSITORY: &str = "avencera/speakrs-models";
/// Revision of [`MODEL_REPOSITORY`] that this release loads
// CI downloads fixtures from this same revision via SPEAKRS_MODEL_FIXTURE_REV
pub const MODEL_REVISION: &str = "67f963b6a1d94fcd4678948237b3cc8bd69bf1d8";

#[cfg(feature = "online")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ModelRepositoryId(&'static str);

#[cfg(feature = "online")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ModelRevision(&'static str);

#[cfg(feature = "online")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct PinnedModelRepository {
    id: ModelRepositoryId,
    revision: ModelRevision,
}

#[cfg(feature = "online")]
impl PinnedModelRepository {
    const fn speakrs_models() -> Self {
        Self {
            id: ModelRepositoryId(MODEL_REPOSITORY),
            revision: ModelRevision(MODEL_REVISION),
        }
    }

    fn into_hf_repo(self) -> Repo {
        Repo::with_revision(
            self.id.0.to_owned(),
            RepoType::Model,
            self.revision.0.to_owned(),
        )
    }

    fn bind(self, api: &Api) -> ApiRepo {
        api.repo(self.into_hf_repo())
    }
}

#[cfg(feature = "online")]
const PINNED_MODEL_REPOSITORY: PinnedModelRepository = PinnedModelRepository::speakrs_models();

/// Manages downloading and caching speakrs models from HuggingFace
#[cfg(feature = "online")]
#[cfg_attr(docsrs, doc(cfg(feature = "online")))]
pub struct ModelManager {
    repo: ApiRepo,
}

#[cfg(feature = "online")]
impl ModelManager {
    /// Create a manager using the default HuggingFace cache directory
    pub fn new() -> Result<Self, hf_hub::api::sync::ApiError> {
        let api = Api::new()?;
        Ok(Self::from_api(api))
    }

    /// Create a manager with a custom cache directory
    pub fn with_cache_dir(cache_dir: PathBuf) -> Result<Self, hf_hub::api::sync::ApiError> {
        let api = ApiBuilder::from_cache(hf_hub::Cache::new(cache_dir)).build()?;
        Ok(Self::from_api(api))
    }

    fn from_api(api: Api) -> Self {
        let repo = PINNED_MODEL_REPOSITORY.bind(&api);
        Self { repo }
    }

    /// Download a single file, returns path to cached copy
    pub fn get(&self, filename: impl AsRef<str>) -> Result<PathBuf, hf_hub::api::sync::ApiError> {
        self.repo.get(filename.as_ref())
    }

    /// Ensure all files for a mode are downloaded, return base models dir
    pub fn ensure(&self, mode: ExecutionMode) -> Result<PathBuf, hf_hub::api::sync::ApiError> {
        let files = required_model_files(mode);
        for file in &files {
            self.repo.get(file)?;
        }
        // all files land in the same snapshot dir
        let first = self.repo.get(&files[0])?;
        let Some(parent) = first.parent() else {
            return Ok(first);
        };
        Ok(parent.to_path_buf())
    }
}

const PLDA_FILES: &[&str] = &[
    "plda_lda.npy",
    "plda_tr.npy",
    "plda_mu.npy",
    "plda_psi.npy",
    "plda_mean1.npy",
    "plda_mean2.npy",
    EMBEDDING_MIN_SAMPLES,
];

/// The safetensors weights the native CPU and CUDA modes load, exported by
/// `scripts/cuda/export_weights.py --runtime-assets`
const NATIVE_WEIGHT_FILES: &[(&str, ModelFamily)] = &[
    ("segmentation-3.0.safetensors", ModelFamily::Segmentation),
    (
        "wespeaker-multimask-tail.safetensors",
        ModelFamily::MultiMaskTail,
    ),
];

fn mlmodelc_files(name: &str) -> Vec<String> {
    vec![
        format!("{name}/model.mil"),
        format!("{name}/coremldata.bin"),
        format!("{name}/weights/weight.bin"),
        format!("{name}/analytics/coremldata.bin"),
    ]
}

const COREML_COMMON_MODEL_STEMS: &[&str] = &[
    "segmentation-3.0.mlmodelc",
    "segmentation-3.0-b32.mlmodelc",
    "segmentation-3.0-b64.mlmodelc",
    "wespeaker-fbank.mlmodelc",
    "wespeaker-fbank-b32.mlmodelc",
    "wespeaker-fbank-30s.mlmodelc",
    "wespeaker-multimask-tail-b32.mlmodelc",
    "wespeaker-voxceleb-resnet34-tail.mlmodelc",
    "wespeaker-voxceleb-resnet34-tail-b3.mlmodelc",
    "wespeaker-voxceleb-resnet34-tail-b32.mlmodelc",
];

const COREML_CHUNK_MODEL_STEMS: &[&str] = &[
    "wespeaker-chunk-emb-p1s-w21.mlmodelc",
    "wespeaker-chunk-emb-p1s-w36.mlmodelc",
    "wespeaker-chunk-emb-p1s-w51.mlmodelc",
    "wespeaker-chunk-emb-p1s-w81.mlmodelc",
    "wespeaker-chunk-emb-p1s-w111.mlmodelc",
];

const COREML_FAST_SEGMENTATION_MODEL_STEMS: &[&str] = &[
    "segmentation-3.0-w8a16.mlmodelc",
    "segmentation-3.0-b32-w8a16.mlmodelc",
    "segmentation-3.0-b64-w8a16.mlmodelc",
];

const COREML_FAST_CHUNK_MODEL_STEMS: &[&str] = &[
    "wespeaker-chunk-emb-s25-w11.mlmodelc",
    "wespeaker-chunk-emb-s25-w16.mlmodelc",
    "wespeaker-chunk-emb-s25-w21.mlmodelc",
    "wespeaker-chunk-emb-s25-w26.mlmodelc",
    "wespeaker-chunk-emb-s25-w36.mlmodelc",
    "wespeaker-chunk-emb-s25-w46.mlmodelc",
    "wespeaker-chunk-emb-s25-w56.mlmodelc",
];

/// Model family owned by the asset catalog
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModelFamily {
    Segmentation,
    Embedding,
    Filterbank,
    EmbeddingTail,
    MultiMaskTail,
    ChunkEmbedding,
    Plda,
    Metadata,
}

/// Backend that consumes a catalog asset
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModelBackend {
    SharedData,
    Cpu,
    Onnx,
    CoreMl,
    Cuda,
}

/// Weight precision recorded for a catalog asset
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModelPrecision {
    Fp32,
    W8A16,
}

/// Whether a catalog asset must be downloaded for a mode
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AssetRequirement {
    Required,
    Optional,
}

/// One remote model file or compiled CoreML bundle stem
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ModelAsset {
    file_name: &'static str,
    family: ModelFamily,
    backend: ModelBackend,
    precision: ModelPrecision,
    batch: Option<u32>,
    requirement: AssetRequirement,
}

impl ModelAsset {
    const fn new(
        file_name: &'static str,
        family: ModelFamily,
        backend: ModelBackend,
        precision: ModelPrecision,
        batch: Option<u32>,
        requirement: AssetRequirement,
    ) -> Self {
        Self {
            file_name,
            family,
            backend,
            precision,
            batch,
            requirement,
        }
    }

    /// Remote file name or compiled-bundle directory
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn file_name(self) -> &'static str {
        self.file_name
    }

    /// Model family this asset belongs to
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn family(self) -> ModelFamily {
        self.family
    }

    /// Backend that loads this asset
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn backend(self) -> ModelBackend {
        self.backend
    }

    /// Recorded weight precision
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn precision(self) -> ModelPrecision {
        self.precision
    }

    /// Batch dimension when the asset is a fixed-shape model
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn batch(self) -> Option<u32> {
        self.batch
    }

    /// Whether this asset must be present for the selected mode
    pub(crate) fn requirement(self) -> AssetRequirement {
        self.requirement
    }

    fn remote_paths(self) -> Vec<String> {
        if self.file_name.ends_with(".mlmodelc") {
            mlmodelc_files(self.file_name)
        } else {
            vec![self.file_name.to_string()]
        }
    }
}

fn family_for_stem(name: &str) -> ModelFamily {
    if name.starts_with("segmentation") {
        ModelFamily::Segmentation
    } else if name.contains("chunk-emb") {
        ModelFamily::ChunkEmbedding
    } else if name.contains("fbank") {
        ModelFamily::Filterbank
    } else if name.contains("multimask") {
        ModelFamily::MultiMaskTail
    } else if name.contains("tail") {
        ModelFamily::EmbeddingTail
    } else {
        ModelFamily::Embedding
    }
}

fn batch_from_name(name: &str) -> Option<u32> {
    let stem = name
        .trim_end_matches(".mlmodelc")
        .trim_end_matches(".onnx")
        .trim_end_matches(".onnx.data");
    stem.rsplit_once("-b")
        .and_then(|(_, batch)| batch.parse().ok())
}

fn onnx_asset(name: &'static str, family: ModelFamily) -> ModelAsset {
    ModelAsset::new(
        name,
        family,
        ModelBackend::Onnx,
        ModelPrecision::Fp32,
        batch_from_name(name),
        AssetRequirement::Required,
    )
}

fn catalog_assets(mode: ExecutionMode) -> Vec<ModelAsset> {
    let mut assets: Vec<ModelAsset> = PLDA_FILES
        .iter()
        .map(|name| {
            let family = if name.ends_with(".txt") {
                ModelFamily::Metadata
            } else {
                ModelFamily::Plda
            };
            ModelAsset::new(
                name,
                family,
                ModelBackend::SharedData,
                ModelPrecision::Fp32,
                None,
                AssetRequirement::Required,
            )
        })
        .collect();

    match mode {
        // native modes share the deployed FP32 weights and never read ONNX graphs
        ExecutionMode::Cpu | ExecutionMode::Cuda | ExecutionMode::CudaFast => {
            let backend = if matches!(mode, ExecutionMode::Cpu) {
                ModelBackend::Cpu
            } else {
                ModelBackend::Cuda
            };
            assets.extend(NATIVE_WEIGHT_FILES.iter().map(|&(name, family)| {
                ModelAsset::new(
                    name,
                    family,
                    backend,
                    ModelPrecision::Fp32,
                    None,
                    AssetRequirement::Required,
                )
            }));
        }
        ExecutionMode::MiGraphX => {
            assets.push(onnx_asset(
                "segmentation-3.0.onnx",
                ModelFamily::Segmentation,
            ));
            assets.push(onnx_asset(
                "wespeaker-voxceleb-resnet34.onnx",
                ModelFamily::Embedding,
            ));
            assets.push(onnx_asset(
                "wespeaker-voxceleb-resnet34.onnx.data",
                ModelFamily::Embedding,
            ));
            assets.push(onnx_asset("wespeaker-fbank.onnx", ModelFamily::Filterbank));
            assets.push(onnx_asset(
                "wespeaker-fbank-b32.onnx",
                ModelFamily::Filterbank,
            ));
            assets.push(onnx_asset(
                "wespeaker-multimask-tail.onnx",
                ModelFamily::MultiMaskTail,
            ));
            assets.push(onnx_asset(
                "wespeaker-multimask-tail-b32.onnx",
                ModelFamily::MultiMaskTail,
            ));
            assets.push(onnx_asset(
                "segmentation-3.0-b32.onnx",
                ModelFamily::Segmentation,
            ));
            assets.push(onnx_asset(
                "wespeaker-voxceleb-resnet34-b64.onnx",
                ModelFamily::Embedding,
            ));
        }
        // compiled bundles only: CoreML modes never read the ONNX files
        ExecutionMode::CoreMl | ExecutionMode::CoreMlFast => {
            assets.extend(COREML_COMMON_MODEL_STEMS.iter().map(|&name| {
                ModelAsset::new(
                    name,
                    family_for_stem(name),
                    ModelBackend::CoreMl,
                    ModelPrecision::Fp32,
                    batch_from_name(name),
                    AssetRequirement::Required,
                )
            }));
            if matches!(mode, ExecutionMode::CoreMl) {
                assets.extend(COREML_CHUNK_MODEL_STEMS.iter().map(|&name| {
                    ModelAsset::new(
                        name,
                        ModelFamily::ChunkEmbedding,
                        ModelBackend::CoreMl,
                        ModelPrecision::Fp32,
                        batch_from_name(name),
                        AssetRequirement::Required,
                    )
                }));
            }
            if matches!(mode, ExecutionMode::CoreMlFast) {
                assets.extend(COREML_FAST_SEGMENTATION_MODEL_STEMS.iter().map(|&name| {
                    ModelAsset::new(
                        name,
                        ModelFamily::Segmentation,
                        ModelBackend::CoreMl,
                        ModelPrecision::W8A16,
                        batch_from_name(name),
                        AssetRequirement::Required,
                    )
                }));
                assets.extend(COREML_FAST_CHUNK_MODEL_STEMS.iter().map(|&name| {
                    ModelAsset::new(
                        name,
                        ModelFamily::ChunkEmbedding,
                        ModelBackend::CoreMl,
                        ModelPrecision::Fp32,
                        batch_from_name(name),
                        AssetRequirement::Required,
                    )
                }));
            }
            assets.push(ModelAsset::new(
                "wespeaker-voxceleb-resnet34-tail-b64.mlmodelc",
                ModelFamily::EmbeddingTail,
                ModelBackend::CoreMl,
                ModelPrecision::Fp32,
                Some(64),
                AssetRequirement::Optional,
            ));
        }
    }

    assets
}

/// Files that `mode` loads, relative to the model directory
///
/// The model manager downloads exactly these files from [`MODEL_REPOSITORY`] at
/// [`MODEL_REVISION`]. Compiled CoreML bundles are listed file by file
pub fn required_model_files(mode: ExecutionMode) -> Vec<String> {
    catalog_assets(mode)
        .into_iter()
        .filter(|asset| asset.requirement() == AssetRequirement::Required)
        .flat_map(ModelAsset::remote_paths)
        .collect()
}

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

    use super::{EMBEDDING_MIN_SAMPLES, ModelBundle};

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

    fn scratch_directory(test_name: &str) -> std::path::PathBuf {
        let id = NEXT_DIRECTORY_ID.fetch_add(1, Ordering::Relaxed);
        let directory = std::env::temp_dir().join(format!(
            "speakrs-model-bundle-{}-{test_name}-{id}",
            std::process::id()
        ));
        fs::create_dir_all(&directory).unwrap();
        directory
    }

    #[test]
    fn local_bundle_requires_embedding_metadata() {
        let directory = scratch_directory("missing-metadata");
        let error = ModelBundle::from_dir(&directory).unwrap_err();

        assert!(error.to_string().contains("missing embedding metadata"));
        fs::remove_dir_all(directory).unwrap();
    }

    #[test]
    fn local_bundle_validates_embedding_metadata_before_construction() {
        let directory = scratch_directory("metadata-validation");
        let metadata = directory.join(EMBEDDING_MIN_SAMPLES);
        fs::write(&metadata, "0\n").unwrap();
        let error = ModelBundle::from_dir(&directory).unwrap_err();
        assert!(error.to_string().contains("must be greater than zero"));

        fs::write(metadata, "400\n").unwrap();
        ModelBundle::from_dir(&directory).unwrap();
        fs::remove_dir_all(directory).unwrap();
    }
}

// the catalog tests also keep its accessors used in builds without `online`
#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "online")]
    const MODEL_FILENAME: &str = "segmentation-3.0.onnx";
    #[cfg(feature = "online")]
    const EXPECTED_MODEL_URL: &str = "https://huggingface.co/avencera/speakrs-models/resolve/67f963b6a1d94fcd4678948237b3cc8bd69bf1d8/segmentation-3.0.onnx";

    #[cfg(feature = "online")]
    #[test]
    fn pinned_repository_selects_model_card_revision() {
        let repo = PINNED_MODEL_REPOSITORY.into_hf_repo();
        assert_eq!(repo.folder_name(), "models--avencera--speakrs-models");
        assert_eq!(repo.revision(), MODEL_REVISION);

        let api = ApiBuilder::new().with_progress(false).build().unwrap();
        let api_repo = api.repo(repo);
        assert_eq!(api_repo.url(MODEL_FILENAME), EXPECTED_MODEL_URL);
    }

    #[cfg(feature = "online")]
    #[test]
    fn default_and_custom_cache_managers_share_pinned_repository() {
        let default_manager = ModelManager::new().unwrap();
        let custom_cache = std::env::temp_dir().join(format!(
            "speakrs-pinned-model-manager-{}",
            std::process::id()
        ));
        let custom_manager = ModelManager::with_cache_dir(custom_cache).unwrap();

        assert_eq!(default_manager.repo.url(MODEL_FILENAME), EXPECTED_MODEL_URL);
        assert_eq!(custom_manager.repo.url(MODEL_FILENAME), EXPECTED_MODEL_URL);
    }

    #[test]
    fn coreml_required_files_include_chunk_fast_path_assets() {
        let files = required_model_files(ExecutionMode::CoreMl);
        assert!(files.contains(&"segmentation-3.0-b64.mlmodelc/model.mil".to_string()));
        assert!(files.contains(&"wespeaker-fbank-30s.mlmodelc/model.mil".to_string()));
        assert!(files.contains(&"wespeaker-multimask-tail-b32.mlmodelc/model.mil".to_string()));
        assert!(files.contains(&"wespeaker-chunk-emb-p1s-w111.mlmodelc/model.mil".to_string()));
    }

    #[test]
    fn coreml_modes_download_no_onnx_files() {
        for mode in [ExecutionMode::CoreMl, ExecutionMode::CoreMlFast] {
            let files = required_model_files(mode);
            assert!(
                files.iter().all(|path| !path.contains(".onnx")),
                "{mode} downloads ONNX files: {files:?}"
            );
            assert!(files.contains(&EMBEDDING_MIN_SAMPLES.to_string()));
            assert!(files.contains(&"wespeaker-fbank.mlmodelc/model.mil".to_string()));
        }
    }

    #[test]
    fn coreml_fast_required_files_include_fast_assets() {
        let files = required_model_files(ExecutionMode::CoreMlFast);
        assert!(files.contains(&"segmentation-3.0-w8a16.mlmodelc/model.mil".to_string()));
        assert!(files.contains(&"segmentation-3.0-b64-w8a16.mlmodelc/model.mil".to_string()));
        assert!(files.contains(&"wespeaker-chunk-emb-s25-w56.mlmodelc/model.mil".to_string()));
    }

    #[test]
    fn catalog_selects_required_batch_32_coreml_tail() {
        let tail = catalog_assets(ExecutionMode::CoreMl)
            .into_iter()
            .find(|asset| asset.family() == ModelFamily::EmbeddingTail && asset.batch() == Some(32))
            .expect("required batch-32 CoreML tail");
        assert_eq!(tail.backend(), ModelBackend::CoreMl);
        assert_eq!(tail.precision(), ModelPrecision::Fp32);
        assert_eq!(tail.requirement(), AssetRequirement::Required);
        assert_eq!(
            tail.file_name(),
            "wespeaker-voxceleb-resnet34-tail-b32.mlmodelc"
        );
        assert_eq!(
            tail.remote_paths()[0],
            "wespeaker-voxceleb-resnet34-tail-b32.mlmodelc/model.mil"
        );
    }

    #[test]
    fn coreml_catalog_records_optional_batch_64_tail() {
        let optional = catalog_assets(ExecutionMode::CoreMl)
            .into_iter()
            .find(|asset| asset.batch() == Some(64) && asset.family() == ModelFamily::EmbeddingTail)
            .expect("optional batch-64 CoreML tail");
        assert_eq!(optional.requirement(), AssetRequirement::Optional);
        let files = required_model_files(ExecutionMode::CoreMl);
        assert!(!files.iter().any(|path| path.contains("tail-b64")));
    }

    #[test]
    fn native_modes_download_weights_plda_and_metadata_without_onnx() {
        let mut expected: Vec<String> = PLDA_FILES
            .iter()
            .map(|name| name.to_string())
            .chain([
                "segmentation-3.0.safetensors".to_owned(),
                "wespeaker-multimask-tail.safetensors".to_owned(),
            ])
            .collect();
        expected.sort();

        for mode in [
            ExecutionMode::Cpu,
            ExecutionMode::Cuda,
            ExecutionMode::CudaFast,
        ] {
            let mut files = required_model_files(mode);
            files.sort();
            assert_eq!(files, expected, "unexpected assets for {mode}");

            let backend = if matches!(mode, ExecutionMode::Cpu) {
                ModelBackend::Cpu
            } else {
                ModelBackend::Cuda
            };
            let assets = catalog_assets(mode);
            assert!(assets.iter().any(|asset| {
                asset.family() == ModelFamily::Segmentation && asset.backend() == backend
            }));
            assert!(assets.iter().any(|asset| {
                asset.family() == ModelFamily::MultiMaskTail && asset.backend() == backend
            }));
        }
    }

    #[test]
    fn migraphx_required_files_include_accelerated_onnx_assets() {
        let files = required_model_files(ExecutionMode::MiGraphX);
        assert!(files.contains(&"segmentation-3.0-b32.onnx".to_string()));
        assert!(files.contains(&"wespeaker-fbank.onnx".to_string()));
        assert!(files.contains(&"wespeaker-fbank-b32.onnx".to_string()));
        assert!(files.contains(&"wespeaker-multimask-tail.onnx".to_string()));
        assert!(files.contains(&"wespeaker-multimask-tail-b32.onnx".to_string()));
        assert!(files.contains(&"wespeaker-voxceleb-resnet34-b64.onnx".to_string()));
    }
}