trustformers-core 0.2.1

Core traits and utilities for TrustformeRS
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
// Core ML export functionality for iOS deployment
//! # Why no `.mlmodel` is written
//!
//! A Core ML model is an operation graph (`NeuralNetwork` / `MLProgram`) serialised
//! as an Apple protobuf. [`Model`] exposes parameters (via
//! [`Model::named_tensors`]) but not topology, so the layer list cannot be derived.
//!
//! Earlier revisions emitted a fixed 768-wide, 12-block transformer whose every
//! weight was `sin(i * 0.001)`, wrote it under the `.mlmodel` extension and
//! reported success. That artifact described a model that did not exist, so it is
//! no longer produced: [`CoreMLExporter::export`] returns a structured
//! [`ErrorKind::UnsupportedOperation`](crate::errors::ErrorKind::UnsupportedOperation).
//!
//! Use the GGUF or GGML exporters to write the model's real parameters; they are
//! tensor containers and need no topology.

use super::{ExportConfig, ExportFormat, ModelExporter};
use crate::errors::unsupported_operation;
use crate::traits::Model;
use anyhow::{anyhow, Result};
use std::collections::HashMap;

/// Explanation attached to every refusal to write a Core ML model.
pub const COREML_UNSUPPORTED_REASON: &str =
    "a Core ML model is an operation graph serialised as an Apple protobuf; the \
     `Model` trait exposes parameters only (`named_tensors`), so TrustformeRS will \
     not emit a synthesized layer graph under a real model's name. Convert an ONNX \
     export with `coremltools` instead.";

/// Core ML model representation
#[derive(Debug, Clone)]
pub struct CoreMLModel {
    pub specification_version: u32,
    pub description: CoreMLModelDescription,
    pub neural_network: CoreMLNeuralNetwork,
    pub model_type: CoreMLModelType,
}

#[derive(Debug, Clone)]
pub enum CoreMLModelType {
    NeuralNetwork(CoreMLNeuralNetwork),
    Pipeline(CoreMLPipeline),
    MLProgram(CoreMLProgram),
}

#[derive(Debug, Clone)]
pub struct CoreMLPipeline {
    pub models: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct CoreMLProgram {
    pub functions: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct CoreMLModelDescription {
    pub input: Vec<CoreMLFeatureDescription>,
    pub output: Vec<CoreMLFeatureDescription>,
    pub predicted_feature_name: Option<String>,
    pub predicted_probabilities_name: Option<String>,
    pub training_input: Vec<CoreMLFeatureDescription>,
    pub metadata: HashMap<String, String>,
}

#[derive(Debug, Clone)]
pub struct CoreMLFeatureDescription {
    pub name: String,
    pub short_description: String,
    pub feature_type: CoreMLFeatureType,
}

#[derive(Debug, Clone)]
pub enum CoreMLFeatureType {
    MultiArray(CoreMLArrayFeatureType),
    String(CoreMLStringFeatureType),
    Int64(CoreMLInt64FeatureType),
    Double(CoreMLDoubleFeatureType),
    Dictionary(CoreMLDictionaryFeatureType),
    Sequence(Box<CoreMLFeatureType>),
}

#[derive(Debug, Clone)]
pub struct CoreMLArrayFeatureType {
    pub shape: Vec<i64>,
    pub data_type: CoreMLArrayDataType,
    pub default_optional_value: Option<Vec<f64>>,
}

#[derive(Debug, Clone, Copy)]
pub enum CoreMLArrayDataType {
    Float32 = 65568,
    Float16 = 65552,
    Int32 = 131104,
}

#[derive(Debug, Clone)]
pub struct CoreMLStringFeatureType {
    pub default_value: Option<String>,
}

#[derive(Debug, Clone)]
pub struct CoreMLInt64FeatureType {
    pub default_value: Option<i64>,
}

#[derive(Debug, Clone)]
pub struct CoreMLDoubleFeatureType {
    pub default_value: Option<f64>,
}

#[derive(Debug, Clone)]
pub struct CoreMLDictionaryFeatureType {
    pub key_type: CoreMLDictionaryKeyType,
}

#[derive(Debug, Clone)]
pub enum CoreMLDictionaryKeyType {
    String,
    Int64,
}

/// Core ML Neural Network representation
#[derive(Debug, Clone)]
pub struct CoreMLNeuralNetwork {
    pub layers: Vec<CoreMLNeuralNetworkLayer>,
    pub preprocessing: Vec<CoreMLFeatureDescription>,
    pub array_inputs: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct CoreMLNeuralNetworkLayer {
    pub name: String,
    pub input: Vec<String>,
    pub output: Vec<String>,
    pub layer_type: CoreMLLayerType,
}

#[derive(Debug, Clone)]
pub enum CoreMLLayerType {
    InnerProduct(CoreMLInnerProductLayer),
    Convolution(CoreMLConvolutionLayer),
    Activation(CoreMLActivationLayer),
    Pooling(CoreMLPoolingLayer),
    Normalization(CoreMLNormalizationLayer),
    Softmax(CoreMLSoftmaxLayer),
    LRN(CoreMLLRNLayer),
    Crop(CoreMLCropLayer),
    Padding(CoreMLPaddingLayer),
    Upsample(CoreMLUpsampleLayer),
    Unary(CoreMLUnaryLayer),
    Add(CoreMLAddLayer),
    Multiply(CoreMLMultiplyLayer),
    Average(CoreMLAverageLayer),
    Scale(CoreMLScaleLayer),
    Bias(CoreMLBiasLayer),
    Max(CoreMLMaxLayer),
    Min(CoreMLMinLayer),
    Dot(CoreMLDotLayer),
    Reduce(CoreMLReduceLayer),
    LoadConstant(CoreMLLoadConstantLayer),
    Reshape(CoreMLReshapeLayer),
    Flatten(CoreMLFlattenLayer),
    Permute(CoreMLPermuteLayer),
    Concat(CoreMLConcatLayer),
    Split(CoreMLSplitLayer),
    SequenceRepeat(CoreMLSequenceRepeatLayer),
    Reorganize(CoreMLReorganizeLayer),
    Slice(CoreMLSliceLayer),
    EmbeddingND(CoreMLEmbeddingNDLayer),
    BatchedMatMul(CoreMLBatchedMatMulLayer),
}

// Layer type definitions
#[derive(Debug, Clone)]
pub struct CoreMLInnerProductLayer {
    pub input_channels: u64,
    pub output_channels: u64,
    pub has_bias: bool,
    pub weights: CoreMLWeightParams,
    pub bias: Option<CoreMLWeightParams>,
}

#[derive(Debug, Clone)]
pub struct CoreMLConvolutionLayer {
    pub output_channels: u64,
    pub kernel_channels: u64,
    pub n_groups: u64,
    pub kernel_size: Vec<u64>,
    pub stride: Vec<u64>,
    pub dilation_factor: Vec<u64>,
    pub valid: CoreMLValidPadding,
    pub weights: CoreMLWeightParams,
    pub bias: Option<CoreMLWeightParams>,
    pub output_shape: Vec<u64>,
}

#[derive(Debug, Clone)]
pub struct CoreMLValidPadding {
    pub padding_amounts: CoreMLBorderAmounts,
}

#[derive(Debug, Clone)]
pub struct CoreMLBorderAmounts {
    pub border_amounts: Vec<CoreMLBorderAmount>,
}

#[derive(Debug, Clone)]
pub struct CoreMLBorderAmount {
    pub start_edge_size: u64,
    pub end_edge_size: u64,
}

#[derive(Debug, Clone)]
pub struct CoreMLActivationLayer {
    pub activation_type: CoreMLActivationType,
}

#[derive(Debug, Clone)]
pub enum CoreMLActivationType {
    ReLU,
    LeakyReLU { alpha: f32 },
    Tanh,
    Sigmoid,
    SoftPlus,
    SoftSign,
    ELU { alpha: f32 },
    PReLU { alpha: CoreMLWeightParams },
    ThresholdedReLU { alpha: f32 },
    Linear { alpha: f32, beta: f32 },
}

#[derive(Debug, Clone)]
pub struct CoreMLPoolingLayer {
    pub pooling_type: CoreMLPoolingType,
    pub kernel_size: Vec<u64>,
    pub stride: Vec<u64>,
    pub valid: CoreMLValidPadding,
    pub avg_pool_exclude_padding: bool,
    pub global_pooling: bool,
}

#[derive(Debug, Clone)]
pub enum CoreMLPoolingType {
    Max,
    Average,
    L2,
}

#[derive(Debug, Clone)]
pub struct CoreMLNormalizationLayer {
    pub normalization_type: CoreMLNormalizationType,
}

#[derive(Debug, Clone)]
pub enum CoreMLNormalizationType {
    LRN {
        alpha: f32,
        beta: f32,
        local_size: u64,
        k: f32,
    },
    BatchNorm {
        channels: u64,
        computed_mean: CoreMLWeightParams,
        computed_variance: CoreMLWeightParams,
        epsilon: f32,
    },
    InstanceNorm {
        channels: u64,
        epsilon: f32,
        gamma: Option<CoreMLWeightParams>,
        beta: Option<CoreMLWeightParams>,
    },
    LayerNorm {
        normalized_shape: Vec<u64>,
        eps: f32,
        gamma: Option<CoreMLWeightParams>,
        beta: Option<CoreMLWeightParams>,
    },
}

#[derive(Debug, Clone)]
pub struct CoreMLSoftmaxLayer {
    pub axis: i64,
}

#[derive(Debug, Clone)]
pub struct CoreMLLRNLayer {
    pub alpha: f32,
    pub beta: f32,
    pub local_size: u64,
    pub k: f32,
}

#[derive(Debug, Clone)]
pub struct CoreMLCropLayer {
    pub crop_amounts: CoreMLBorderAmounts,
    pub offset: Vec<i64>,
}

#[derive(Debug, Clone)]
pub struct CoreMLPaddingLayer {
    pub padding_type: CoreMLPaddingType,
}

#[derive(Debug, Clone)]
pub enum CoreMLPaddingType {
    Constant {
        value: f32,
        padding_amounts: CoreMLBorderAmounts,
    },
    Reflection {
        padding_amounts: CoreMLBorderAmounts,
    },
    Replication {
        padding_amounts: CoreMLBorderAmounts,
    },
}

#[derive(Debug, Clone)]
pub struct CoreMLUpsampleLayer {
    pub scaling_factor: Vec<u64>,
    pub mode: CoreMLUpsampleMode,
}

#[derive(Debug, Clone)]
pub enum CoreMLUpsampleMode {
    NN, // Nearest neighbor
    Bilinear,
}

#[derive(Debug, Clone)]
pub struct CoreMLUnaryLayer {
    pub unary_type: CoreMLUnaryType,
}

#[derive(Debug, Clone)]
pub enum CoreMLUnaryType {
    Sqrt,
    Rsqrt,
    Inverse,
    Power { alpha: f32 },
    Exp,
    Log,
    Abs,
    Threshold { alpha: f32 },
}

#[derive(Debug, Clone)]
pub struct CoreMLAddLayer {
    pub alpha: f32,
}

#[derive(Debug, Clone)]
pub struct CoreMLMultiplyLayer {
    pub alpha: f32,
}

#[derive(Debug, Clone)]
pub struct CoreMLAverageLayer;

#[derive(Debug, Clone)]
pub struct CoreMLScaleLayer {
    pub shape_scale: Vec<u64>,
    pub scale: CoreMLWeightParams,
    pub has_bias: bool,
    pub shape_bias: Vec<u64>,
    pub bias: Option<CoreMLWeightParams>,
}

#[derive(Debug, Clone)]
pub struct CoreMLBiasLayer {
    pub shape: Vec<u64>,
    pub bias: CoreMLWeightParams,
}

#[derive(Debug, Clone)]
pub struct CoreMLMaxLayer;

#[derive(Debug, Clone)]
pub struct CoreMLMinLayer;

#[derive(Debug, Clone)]
pub struct CoreMLDotLayer {
    pub cos_distance: bool,
}

#[derive(Debug, Clone)]
pub struct CoreMLReduceLayer {
    pub reduce_type: CoreMLReduceType,
    pub axis: i64,
    pub keep_dims: bool,
}

#[derive(Debug, Clone)]
pub enum CoreMLReduceType {
    Sum,
    Avg,
    Prod,
    LogSum,
    SumSquare,
    L1,
    L2,
    Max,
    Min,
    ArgMax,
}

#[derive(Debug, Clone)]
pub struct CoreMLLoadConstantLayer {
    pub shape: Vec<u64>,
    pub data: CoreMLWeightParams,
}

#[derive(Debug, Clone)]
pub struct CoreMLReshapeLayer {
    pub target_shape: Vec<i64>,
    pub mode: CoreMLReshapeMode,
}

#[derive(Debug, Clone)]
pub enum CoreMLReshapeMode {
    Channel,
    Width,
    Height,
}

#[derive(Debug, Clone)]
pub struct CoreMLFlattenLayer {
    pub mode: CoreMLFlattenMode,
}

#[derive(Debug, Clone)]
pub enum CoreMLFlattenMode {
    Channel,
    Width,
    Height,
}

#[derive(Debug, Clone)]
pub struct CoreMLPermuteLayer {
    pub axis: Vec<u64>,
}

#[derive(Debug, Clone)]
pub struct CoreMLConcatLayer {
    pub sequence_concat: bool,
}

#[derive(Debug, Clone)]
pub struct CoreMLSplitLayer {
    pub n_outputs: u64,
}

#[derive(Debug, Clone)]
pub struct CoreMLSequenceRepeatLayer {
    pub n_repetitions: u64,
}

#[derive(Debug, Clone)]
pub struct CoreMLReorganizeLayer {
    pub block_size: u64,
    pub mode: CoreMLReorganizeMode,
}

#[derive(Debug, Clone)]
pub enum CoreMLReorganizeMode {
    SpaceToDepth,
    DepthToSpace,
    PixelShuffle,
}

#[derive(Debug, Clone)]
pub struct CoreMLSliceLayer {
    pub start_index: i64,
    pub end_index: i64,
    pub stride: u64,
    pub axis: i64,
}

#[derive(Debug, Clone)]
pub struct CoreMLEmbeddingNDLayer {
    pub vocab_size: u64,
    pub embedding_size: u64,
    pub has_bias: bool,
    pub weights: CoreMLWeightParams,
    pub bias: Option<CoreMLWeightParams>,
}

#[derive(Debug, Clone)]
pub struct CoreMLBatchedMatMulLayer {
    pub transpose_a: bool,
    pub transpose_b: bool,
    pub weight_matrix_first_dimension: u64,
    pub weight_matrix_second_dimension: u64,
    pub has_bias: bool,
    pub weights: CoreMLWeightParams,
    pub bias: Option<CoreMLWeightParams>,
}

#[derive(Debug, Clone)]
pub struct CoreMLWeightParams {
    pub quantization: Option<CoreMLQuantizationParams>,
    pub float_value: Vec<f32>,
    pub float16_value: Vec<u16>,
    pub raw_value: Vec<u8>,
}

#[derive(Debug, Clone)]
pub struct CoreMLQuantizationParams {
    pub number_of_bits: u64,
    pub linear_quantization: Option<CoreMLLinearQuantizationParams>,
    pub lookup_table_quantization: Option<CoreMLLookupTableQuantizationParams>,
}

#[derive(Debug, Clone)]
pub struct CoreMLLinearQuantizationParams {
    pub scale: Vec<f32>,
    pub bias: Vec<f32>,
}

#[derive(Debug, Clone)]
pub struct CoreMLLookupTableQuantizationParams {
    pub float_value: Vec<f32>,
}

/// Core ML exporter implementation
#[derive(Clone)]
pub struct CoreMLExporter {
    target_ios_version: String,
    optimization_enabled: bool,
}

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

impl CoreMLExporter {
    pub fn new() -> Self {
        Self {
            target_ios_version: "13.0".to_string(),
            optimization_enabled: true,
        }
    }

    pub fn with_target_ios_version(mut self, version: String) -> Self {
        self.target_ios_version = version;
        self
    }

    pub fn with_optimization(mut self, enabled: bool) -> Self {
        self.optimization_enabled = enabled;
        self
    }
}

impl ModelExporter for CoreMLExporter {
    /// Always fails with a structured `UnsupportedOperation` error.
    ///
    /// See the [module documentation](self) for why no `.mlmodel` is written.
    fn export<M: Model>(&self, model: &M, config: &ExportConfig) -> Result<()> {
        if config.format != ExportFormat::CoreML {
            return Err(anyhow!("CoreMLExporter only supports Core ML format"));
        }

        // Surface the "no weights at all" problem first: it is the caller's bug,
        // whereas the missing topology is a limitation of the `Model` trait.
        let _tensors = crate::export::collect_model_tensors(model)?;
        Err(unsupported_operation("Core ML model export", COREML_UNSUPPORTED_REASON).into())
    }

    fn supported_formats(&self) -> Vec<ExportFormat> {
        vec![ExportFormat::CoreML]
    }

    fn validate_model<M: Model>(&self, _model: &M, format: ExportFormat) -> Result<()> {
        if format != ExportFormat::CoreML {
            return Err(anyhow!("CoreMLExporter only supports Core ML format"));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_coreml_exporter_creation() {
        let exporter = CoreMLExporter::new();
        assert_eq!(exporter.target_ios_version, "13.0");
        assert!(exporter.optimization_enabled);

        let exporter_custom =
            exporter.with_target_ios_version("14.0".to_string()).with_optimization(false);
        assert_eq!(exporter_custom.target_ios_version, "14.0");
        assert!(!exporter_custom.optimization_enabled);
    }

    #[test]
    fn test_coreml_array_data_types() {
        assert_eq!(CoreMLArrayDataType::Float32 as u32, 65568);
        assert_eq!(CoreMLArrayDataType::Float16 as u32, 65552);
        assert_eq!(CoreMLArrayDataType::Int32 as u32, 131104);
    }

    #[test]
    fn test_coreml_feature_types() {
        let array_feature = CoreMLFeatureType::MultiArray(CoreMLArrayFeatureType {
            shape: vec![1, 512],
            data_type: CoreMLArrayDataType::Float32,
            default_optional_value: None,
        });

        let string_feature = CoreMLFeatureType::String(CoreMLStringFeatureType {
            default_value: Some("default".to_string()),
        });

        match array_feature {
            CoreMLFeatureType::MultiArray(_) => {},
            _ => panic!(
                "Expected MultiArray feature type but got {:?}",
                array_feature
            ),
        }

        match string_feature {
            CoreMLFeatureType::String(_) => {},
            _ => panic!("Expected String feature type but got {:?}", string_feature),
        }
    }

    #[test]
    fn test_supported_formats() {
        let exporter = CoreMLExporter::new();
        let formats = exporter.supported_formats();
        assert_eq!(formats.len(), 1);
        assert_eq!(formats[0], ExportFormat::CoreML);
    }

    #[test]
    fn test_coreml_activation_types() {
        let relu = CoreMLActivationType::ReLU;
        let leaky_relu = CoreMLActivationType::LeakyReLU { alpha: 0.1 };
        let sigmoid = CoreMLActivationType::Sigmoid;

        match relu {
            CoreMLActivationType::ReLU => {},
            _ => panic!("Expected ReLU activation but got {:?}", relu),
        }

        match leaky_relu {
            CoreMLActivationType::LeakyReLU { alpha } => assert!((alpha - 0.1).abs() < 1e-6),
            _ => panic!("Expected LeakyReLU activation but got {:?}", leaky_relu),
        }

        match sigmoid {
            CoreMLActivationType::Sigmoid => {},
            _ => panic!("Expected Sigmoid activation but got {:?}", sigmoid),
        }
    }

    /// Regression test for the exporter that used to write a fixed 12-block
    /// transformer whose weights were `sin(i * 0.001)` for any model.
    #[test]
    fn export_refuses_to_write_a_synthesized_mlmodel() {
        let dir = std::env::temp_dir().join("trustformers_coreml_export_test");
        std::fs::create_dir_all(&dir).expect("temp dir");
        let output = dir.join("model");

        let exporter = CoreMLExporter::new();
        let model = crate::export::test_support::TestModel::with_seed(5.0);
        let config = ExportConfig {
            format: ExportFormat::CoreML,
            output_path: output.to_string_lossy().to_string(),
            ..Default::default()
        };

        let err = exporter.export(&model, &config).expect_err("must not fabricate a model");
        assert!(
            err.to_string().contains("Unsupported operation"),
            "expected UnsupportedOperation, got: {err}"
        );
        assert!(
            !output.with_extension("mlmodel").exists(),
            "no .mlmodel may be produced"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn export_reports_missing_weights_before_missing_topology() {
        let exporter = CoreMLExporter::new();
        let model = crate::export::test_support::TestModel::empty();
        let config = ExportConfig {
            format: ExportFormat::CoreML,
            ..Default::default()
        };

        let err = exporter.export(&model, &config).expect_err("no weights, no export");
        assert!(
            err.to_string().contains("named_tensors"),
            "expected the missing-weights diagnostic, got: {err}"
        );
    }
}