ferricml 0.1.2

A lean, pure-Rust toolkit for classical machine learning
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
//! Generic fitted preprocessing pipelines.
//!
//! The initial seam composes one fitted transformer with one fitted estimator.
//! Both types remain concrete, so transformation and the callback passed to
//! [`Pipeline::with_transformed`] are statically dispatched. Training-time
//! composition and multi-step pipelines will be added with the first concrete
//! preprocessing estimator rather than guessed in advance.

use crate::api::Classifier;
use crate::api::{Estimator, ModelError, Transformer, validate_transformed_shape};
use crate::artifact::{
    ArtifactError, STANDARD_SCALER_LINEAR_PIPELINE_ARTIFACT_KIND,
    STANDARD_SCALER_LOGISTIC_PIPELINE_ARTIFACT_KIND, STANDARD_SCALER_RIDGE_PIPELINE_ARTIFACT_KIND,
    SchemaRole, decode_component, decode_v2_envelope, encode_component, encode_v2_envelope,
};
use crate::data::{DenseMatrix, MatrixView};
use crate::linear_model::{LinearRegression, LogisticRegression, Ridge};
use crate::preprocessing::StandardScaler;

const PIPELINE_PAYLOAD_VERSION: u16 = 1;
const TRANSFORMER_COMPONENT_KIND: u16 = 1;
const ESTIMATOR_COMPONENT_KIND: u16 = 2;
const COMPONENT_VERSION: u16 = 1;

/// One fitted transformer followed by one fitted estimator.
///
/// Construction validates the feature-width handoff. Allocation-sensitive
/// callers reuse a workspace and call [`Pipeline::with_transformed`]; callers
/// that prefer convenience can use [`Pipeline::transform`].
#[derive(Clone, Debug, PartialEq)]
pub struct Pipeline<T, E> {
    transformer: T,
    estimator: E,
}

impl<T, E> Pipeline<T, E>
where
    T: Transformer,
    E: Estimator,
{
    /// Composes fitted parts after validating their feature-width handoff.
    pub fn new(transformer: T, estimator: E) -> Result<Self, ModelError> {
        let transformed = transformer.n_features_out();
        let expected = estimator.n_features_in();
        if transformed != expected {
            return Err(ModelError::FeatureDimension {
                expected,
                actual: transformed,
            });
        }
        Ok(Self {
            transformer,
            estimator,
        })
    }

    /// Returns the fitted transformer.
    pub const fn transformer(&self) -> &T {
        &self.transformer
    }

    /// Returns the fitted final estimator.
    pub const fn estimator(&self) -> &E {
        &self.estimator
    }

    /// Consumes the pipeline and returns its fitted parts.
    pub fn into_parts(self) -> (T, E) {
        (self.transformer, self.estimator)
    }

    /// Number of `f32` values required for a transformed batch workspace.
    pub fn workspace_len(&self, rows: usize) -> Result<usize, ModelError> {
        rows.checked_mul(self.transformer.n_features_out())
            .ok_or(ModelError::OutputShapeOverflow {
                rows,
                columns: self.transformer.n_features_out(),
            })
    }

    /// Transforms into caller-owned workspace and returns its validated view.
    pub fn transform_into<'output>(
        &self,
        data: &MatrixView<'_>,
        workspace: &'output mut [f32],
    ) -> Result<MatrixView<'output>, ModelError> {
        let transformed = self.transformer.transform_into(data, workspace)?;
        validate_transformed_shape(data.rows(), self.transformer.n_features_out(), &transformed)?;
        Ok(transformed)
    }

    /// Transforms into a newly allocated dense matrix.
    pub fn transform(&self, data: &MatrixView<'_>) -> Result<DenseMatrix, ModelError> {
        self.transformer.transform(data)
    }

    /// Runs an operation on a transformed batch without allocating or erasing
    /// either fitted type.
    ///
    /// This is the extension point for future classifier/regressor convenience
    /// methods: the callback can call an estimator's `_into` method while the
    /// caller reuses `workspace` across batches.
    pub fn with_transformed<R>(
        &self,
        data: &MatrixView<'_>,
        workspace: &mut [f32],
        operation: impl FnOnce(&E, &MatrixView<'_>) -> Result<R, ModelError>,
    ) -> Result<R, ModelError> {
        let transformed = self.transform_into(data, workspace)?;
        operation(&self.estimator, &transformed)
    }
}

impl<T, E> Estimator for Pipeline<T, E>
where
    T: Transformer,
    E: Estimator,
{
    fn n_features_in(&self) -> usize {
        self.transformer.n_features_in()
    }
}

fn encode_pipeline_artifact(
    kind: u16,
    input_schema: [u8; 32],
    transformed_schema: [u8; 32],
    transformer_artifact: &[u8],
    estimator_artifact: &[u8],
) -> Result<Vec<u8>, ArtifactError> {
    let transformer = encode_component(
        TRANSFORMER_COMPONENT_KIND,
        COMPONENT_VERSION,
        transformer_artifact,
    )?;
    let estimator = encode_component(
        ESTIMATOR_COMPONENT_KIND,
        COMPONENT_VERSION,
        estimator_artifact,
    )?;
    let mut payload = Vec::with_capacity(transformer.len() + estimator.len());
    payload.extend_from_slice(&transformer);
    payload.extend_from_slice(&estimator);
    encode_v2_envelope(
        kind,
        PIPELINE_PAYLOAD_VERSION,
        &[
            (SchemaRole::Input, input_schema),
            (SchemaRole::Transformed, transformed_schema),
        ],
        &payload,
    )
}

fn decode_pipeline_components(
    bytes: &[u8],
    kind: u16,
    input_schema: [u8; 32],
    transformed_schema: [u8; 32],
) -> Result<(&[u8], &[u8]), ArtifactError> {
    let mut envelope = decode_v2_envelope(
        bytes,
        kind,
        PIPELINE_PAYLOAD_VERSION,
        &[
            (SchemaRole::Input, input_schema),
            (SchemaRole::Transformed, transformed_schema),
        ],
    )?;
    let transformer =
        decode_component(&mut envelope, TRANSFORMER_COMPONENT_KIND, COMPONENT_VERSION)?;
    let estimator = decode_component(&mut envelope, ESTIMATOR_COMPONENT_KIND, COMPONENT_VERSION)?;
    if !envelope.is_empty() {
        return Err(ArtifactError::TrailingBytes);
    }
    Ok((transformer.remaining(), estimator.remaining()))
}

impl Pipeline<StandardScaler, LogisticRegression> {
    /// Writes labels using caller-owned transform and output buffers.
    pub fn predict_into(
        &self,
        data: &MatrixView<'_>,
        workspace: &mut [f32],
        output: &mut [u8],
    ) -> Result<(), ModelError> {
        self.with_transformed(data, workspace, |model, transformed| {
            model.predict_into(transformed, output)
        })
    }

    /// Writes probabilities using caller-owned transform and output buffers.
    pub fn predict_proba_into(
        &self,
        data: &MatrixView<'_>,
        workspace: &mut [f32],
        output: &mut [f32],
    ) -> Result<(), ModelError> {
        self.with_transformed(data, workspace, |model, transformed| {
            model.predict_proba_into(transformed, output)
        })
    }

    /// Writes one requested probability column without allocating.
    pub fn predict_class_proba_into(
        &self,
        data: &MatrixView<'_>,
        class: u8,
        workspace: &mut [f32],
        output: &mut [f32],
    ) -> Result<(), ModelError> {
        self.with_transformed(data, workspace, |model, transformed| {
            Classifier::predict_class_proba_into(model, transformed, class, output)
        })
    }

    /// Writes raw decision scores without allocating.
    pub fn decision_function_into(
        &self,
        data: &MatrixView<'_>,
        workspace: &mut [f32],
        output: &mut [f32],
    ) -> Result<(), ModelError> {
        self.with_transformed(data, workspace, |model, transformed| {
            model.decision_function_into(transformed, output)
        })
    }

    /// Encodes this concrete fitted pipeline and both schema identities.
    pub fn to_artifact(
        &self,
        input_schema: [u8; 32],
        transformed_schema: [u8; 32],
    ) -> Result<Vec<u8>, ArtifactError> {
        encode_pipeline_artifact(
            STANDARD_SCALER_LOGISTIC_PIPELINE_ARTIFACT_KIND,
            input_schema,
            transformed_schema,
            &self
                .transformer
                .to_artifact(input_schema, transformed_schema)?,
            &self.estimator.to_artifact(transformed_schema)?,
        )
    }

    /// Decodes this concrete pipeline and validates the fitted width handoff.
    pub fn from_artifact(
        bytes: &[u8],
        input_schema: [u8; 32],
        transformed_schema: [u8; 32],
    ) -> Result<Self, ArtifactError> {
        let (transformer, estimator) = decode_pipeline_components(
            bytes,
            STANDARD_SCALER_LOGISTIC_PIPELINE_ARTIFACT_KIND,
            input_schema,
            transformed_schema,
        )?;
        let transformer =
            StandardScaler::from_artifact(transformer, input_schema, transformed_schema)?;
        let estimator = LogisticRegression::from_artifact(estimator, transformed_schema)?;
        Self::new(transformer, estimator).map_err(|_| ArtifactError::InvalidPayload)
    }
}

macro_rules! impl_scaler_regression_pipeline {
    ($estimator:ty, $kind:expr) => {
        impl Pipeline<StandardScaler, $estimator> {
            /// Writes predictions using caller-owned transform and output buffers.
            pub fn predict_into(
                &self,
                data: &MatrixView<'_>,
                workspace: &mut [f32],
                output: &mut [f32],
            ) -> Result<(), ModelError> {
                self.with_transformed(data, workspace, |model, transformed| {
                    model.predict_into(transformed, output)
                })
            }

            /// Encodes this concrete fitted pipeline and both schema identities.
            pub fn to_artifact(
                &self,
                input_schema: [u8; 32],
                transformed_schema: [u8; 32],
            ) -> Result<Vec<u8>, ArtifactError> {
                encode_pipeline_artifact(
                    $kind,
                    input_schema,
                    transformed_schema,
                    &self
                        .transformer
                        .to_artifact(input_schema, transformed_schema)?,
                    &self.estimator.to_artifact(transformed_schema)?,
                )
            }

            /// Decodes this concrete pipeline and validates the fitted width handoff.
            pub fn from_artifact(
                bytes: &[u8],
                input_schema: [u8; 32],
                transformed_schema: [u8; 32],
            ) -> Result<Self, ArtifactError> {
                let (transformer, estimator) =
                    decode_pipeline_components(bytes, $kind, input_schema, transformed_schema)?;
                let transformer =
                    StandardScaler::from_artifact(transformer, input_schema, transformed_schema)?;
                let estimator = <$estimator>::from_artifact(estimator, transformed_schema)?;
                Self::new(transformer, estimator).map_err(|_| ArtifactError::InvalidPayload)
            }
        }
    };
}

impl_scaler_regression_pipeline!(
    LinearRegression,
    STANDARD_SCALER_LINEAR_PIPELINE_ARTIFACT_KIND
);
impl_scaler_regression_pipeline!(Ridge, STANDARD_SCALER_RIDGE_PIPELINE_ARTIFACT_KIND);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::{BinaryTargets, RegressionTargets};
    use crate::linear_model::{LinearRegressionParams, LogisticRegressionParams, RidgeParams};
    use crate::preprocessing::StandardScalerParams;
    use sha2::{Digest, Sha256};

    fn data() -> DenseMatrix {
        DenseMatrix::new(vec![0.0, 1.0, 1.0, 2.0, 2.0, 4.0, 3.0, 8.0], 4, 2).unwrap()
    }

    fn scaler() -> StandardScaler {
        StandardScaler::fit(&data().as_view(), StandardScalerParams::default()).unwrap()
    }

    #[test]
    fn logistic_pipeline_round_trips_and_reuses_workspace() {
        let transformed = scaler().transform(&data().as_view()).unwrap();
        let model = LogisticRegression::fit(
            &transformed.as_view(),
            &BinaryTargets::new(vec![0, 0, 1, 1]).unwrap(),
            LogisticRegressionParams::default(),
        )
        .unwrap();
        let pipeline = Pipeline::new(scaler(), model).unwrap();
        let mut workspace = vec![0.0; pipeline.workspace_len(4).unwrap()];
        let mut expected = [0; 4];
        pipeline
            .predict_into(&data().as_view(), &mut workspace, &mut expected)
            .unwrap();
        let bytes = pipeline.to_artifact([1; 32], [2; 32]).unwrap();
        let decoded =
            Pipeline::<StandardScaler, LogisticRegression>::from_artifact(&bytes, [1; 32], [2; 32])
                .unwrap();
        let mut actual = [0; 4];
        decoded
            .predict_into(&data().as_view(), &mut workspace, &mut actual)
            .unwrap();
        assert_eq!(actual, expected);
        assert_eq!(bytes, pipeline.to_artifact([1; 32], [2; 32]).unwrap());
    }

    #[test]
    fn regression_pipeline_artifacts_keep_estimator_identity() {
        let transformed = scaler().transform(&data().as_view()).unwrap();
        let targets = RegressionTargets::new(vec![0.0, 1.0, 4.0, 9.0]).unwrap();
        let linear = Pipeline::new(
            scaler(),
            LinearRegression::fit(
                &transformed.as_view(),
                &targets,
                LinearRegressionParams::default(),
            )
            .unwrap(),
        )
        .unwrap();
        let bytes = linear.to_artifact([3; 32], [4; 32]).unwrap();
        assert_eq!(
            Pipeline::<StandardScaler, Ridge>::from_artifact(&bytes, [3; 32], [4; 32]).unwrap_err(),
            ArtifactError::UnsupportedModelKind {
                found: STANDARD_SCALER_LINEAR_PIPELINE_ARTIFACT_KIND
            }
        );

        let ridge = Pipeline::new(
            scaler(),
            Ridge::fit(&transformed.as_view(), &targets, RidgeParams::default()).unwrap(),
        )
        .unwrap();
        let encoded = ridge.to_artifact([3; 32], [4; 32]).unwrap();
        let decoded =
            Pipeline::<StandardScaler, Ridge>::from_artifact(&encoded, [3; 32], [4; 32]).unwrap();
        let mut workspace = vec![0.0; decoded.workspace_len(4).unwrap()];
        let mut output = [0.0; 4];
        decoded
            .predict_into(&data().as_view(), &mut workspace, &mut output)
            .unwrap();
        assert!(output.iter().all(|value| value.is_finite()));
    }

    #[test]
    fn pipeline_artifact_rejects_corruption_bad_components_and_width_handoff() {
        let transformed = scaler().transform(&data().as_view()).unwrap();
        let model = LogisticRegression::fit(
            &transformed.as_view(),
            &BinaryTargets::new(vec![0, 0, 1, 1]).unwrap(),
            LogisticRegressionParams::default(),
        )
        .unwrap();
        let pipeline = Pipeline::new(scaler(), model).unwrap();
        let bytes = pipeline.to_artifact([1; 32], [2; 32]).unwrap();

        let mut corrupted = bytes.clone();
        corrupted[110] ^= 1;
        assert_eq!(
            Pipeline::<StandardScaler, LogisticRegression>::from_artifact(
                &corrupted, [1; 32], [2; 32]
            )
            .unwrap_err(),
            ArtifactError::ChecksumMismatch
        );

        let mut bad_component = bytes.clone();
        bad_component[96..98].copy_from_slice(&ESTIMATOR_COMPONENT_KIND.to_le_bytes());
        let checksum_start = bad_component.len() - 32;
        let checksum = Sha256::digest(&bad_component[..checksum_start]);
        bad_component[checksum_start..].copy_from_slice(&checksum);
        assert_eq!(
            Pipeline::<StandardScaler, LogisticRegression>::from_artifact(
                &bad_component,
                [1; 32],
                [2; 32]
            )
            .unwrap_err(),
            ArtifactError::InvalidPayload
        );

        let mut bad_length = bytes.clone();
        let declared = u32::from_le_bytes(bad_length[100..104].try_into().unwrap());
        bad_length[100..104].copy_from_slice(&(declared + 1).to_le_bytes());
        let checksum_start = bad_length.len() - 32;
        let checksum = Sha256::digest(&bad_length[..checksum_start]);
        bad_length[checksum_start..].copy_from_slice(&checksum);
        assert_eq!(
            Pipeline::<StandardScaler, LogisticRegression>::from_artifact(
                &bad_length,
                [1; 32],
                [2; 32]
            )
            .unwrap_err(),
            ArtifactError::InvalidPayload
        );

        let one_column = DenseMatrix::new(vec![0.0, 1.0, 2.0, 3.0], 4, 1).unwrap();
        let narrow_model = LogisticRegression::fit(
            &one_column.as_view(),
            &BinaryTargets::new(vec![0, 0, 1, 1]).unwrap(),
            LogisticRegressionParams::default(),
        )
        .unwrap();
        let mismatched = encode_pipeline_artifact(
            STANDARD_SCALER_LOGISTIC_PIPELINE_ARTIFACT_KIND,
            [1; 32],
            [2; 32],
            &scaler().to_artifact([1; 32], [2; 32]).unwrap(),
            &narrow_model.to_artifact([2; 32]).unwrap(),
        )
        .unwrap();
        assert_eq!(
            Pipeline::<StandardScaler, LogisticRegression>::from_artifact(
                &mismatched,
                [1; 32],
                [2; 32]
            )
            .unwrap_err(),
            ArtifactError::InvalidPayload
        );
    }
}