Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

sciencekit

New In active development · Apache-2.0

All of scikit-learn. Natively in Rust.

sciencekit reimplements every algorithm and utility of scikit-learn from scratch, with extreme performance, memory safety, zero-copy public APIs and native support for datasets larger than RAM.

39+
algorithms mapped
19
crates in the workspace
8
roadmap phases
100%
pure Rust by default

Why does sciencekit exist?

Python ML libraries carry decades of ecosystem — along with the GIL, insecure pickle, and layers of interpretation between your code and the metal. sciencekit brings the same algorithmic reach as scikit-learn to a compiled, native base — no garbage collector, no ergonomic compromises:

⚡
Extreme performance

Native code, SIMD, data parallelism with rayon, and custom allocators selected automatically for your workload.

🛡
Memory safety

All of Rust's guarantees without a garbage collector. Goodbye pickle: models travel as auditable Safetensors or ONNX.

💾
Native out-of-core

Streaming batches or memory-mapping across every algorithm — datasets larger than RAM stop being a blocker.

🧭
First-class concurrency

You choose the execution mode — or the automatic decision engine does: synchronous, asynchronous, streaming or memmap.

The API you will write

Mandatory builder pattern, zero-copy inputs, and full descriptive names — no max_iter anywhere:

// Illustrative — requires the sciencekit crates (Phase 0+).
let model = SKKMeansClassifierBuilder::new()
    .number_of_clusters(8)
    .maximum_iterations(300)
    .execution_mode(SKExecutionMode::Automatic)
    .build()?;

model.fit(&training_data_view)?;
let predictions = model.predict(&test_data_view)?;

Inputs take ArrayView/CowArray (or sparse views via sprs) — never copies of huge matrices. Pipelines are validated at compile time.

Try it in your browser

The example below mirrors the exact shape of the sciencekit API — mandatory builder, full descriptive names, execution_mode on every builder. Edit the code and hit Run: it executes for real, right on the page.

// The sciencekit API follows the builder pattern everywhere.
// This standalone demo mirrors its shape — the real crates arrive with Phase 0.
// Bounded options are enums, never strings, so `execution_mode` cannot be
// misspelled.
#[derive(Debug, Clone, Copy)]
enum SKExecutionMode {
    Automatic,
    InProcessSynchronous,
    OutOfCoreStreaming,
}

#[derive(Debug)]
struct TrainedKMeansModel {
    number_of_clusters: usize,
    maximum_iterations: usize,
    execution_mode: SKExecutionMode,
}

struct KMeansBuilder {
    number_of_clusters: usize,
    maximum_iterations: usize,
    execution_mode: SKExecutionMode,
}

impl KMeansBuilder {
    fn new() -> Self {
        Self {
            number_of_clusters: 3,
            maximum_iterations: 100,
            execution_mode: SKExecutionMode::Automatic,
        }
    }

    fn number_of_clusters(mut self, value: usize) -> Self {
        self.number_of_clusters = value;
        self
    }

    fn maximum_iterations(mut self, value: usize) -> Self {
        self.maximum_iterations = value;
        self
    }

    fn execution_mode(self, mode: SKExecutionMode) -> Self {
        println!("execution mode requested: {mode:?}");
        self
    }

    fn build(self) -> TrainedKMeansModel {
        TrainedKMeansModel {
            number_of_clusters: self.number_of_clusters,
            maximum_iterations: self.maximum_iterations,
            execution_mode: self.execution_mode,
        }
    }
}

fn main() {
    let model = KMeansBuilder::new()
        .number_of_clusters(8)
        .maximum_iterations(300)
        .execution_mode(SKExecutionMode::Automatic)
        .build();

    println!("model ready: {model:?}");
}
How this works: the Run button compiles and executes the code on the official Rust Playground. Once the real sciencekit crates are published, the same examples will run against the library itself.
Current status: Phase 0 (foundations) is complete — Cargo workspace, core traits (SKEstimator, SKRegressorPredictor/SKClassifierPredictor, SKTransformer), the pure-Rust faer math kernel, and the automatic execution-decision + observability layer have all landed. Next up is Phase 1 (preprocessing). Follow the full plan in Plan & Roadmap.

Who is it for?

  • ML engineers in Rust who need a complete, idiomatic toolkit.
  • Python teams that want high-performance inference/training through PyO3 bindings with maximum zero-copy.
  • Production systems where scikit-learn’s pickle is a security risk and every millisecond counts.

The complete reach of scikit-learn,
with the speed and safety of Rust.

Build it with us

The project is open source (Apache-2.0) and advances algorithm by algorithm — naive implementation, tests, performance, out-of-core. Every kind of help is welcome, from docs to GPU backends.

Project Vision

The idea A complete, fast and safe ML library — keeping everything that makes scikit-learn loved.

Goal

sciencekit is a Machine Learning library written natively in Rust exposing every algorithm and utility of scikit-learn, rewritten from scratch in an optimized form. It is not a rushed port: each algorithm evolves through mandatory stages — naive implementation, tests, performance tuning (SIMD, parallelism, memory layout) and out-of-core support.

🚀
Extreme performance

Native code with autovectorization, explicit SIMD on profiled hot paths, data parallelism via rayon, and custom allocators (jemalloc/mimalloc) with an expected 15–30% gain in allocation throughput.

🔐
Memory safety

All of Rust's guarantees without a garbage collector. Models travel as Safetensors — an auditable format that eliminates pickle's attack surface.

🌊
Native out-of-core

Two complementary traits cover any dataset: SKLazySource for sequential streaming in batches and SKMappableSource for O(1) random access via memory-mapping.

⚙️
First-class concurrency

Computation never blocks async threads: rayon runs the math, Tokio handles I/O. The execution mode is user-configurable — or decided automatically from available RAM, dataset size and access pattern.

Positioning

Equivalent to scikit-learn in algorithmic coverage, with the performance and safety of Rust. Three target audiences:

AudienceNeed served
ML engineers in RustA complete, idiomatic toolkit without rewriting algorithms
Python teamsHigh-performance inference/training via zero-copy PyO3 bindings
Production systemsRemoving the pickle risk + models exportable to ONNX/Safetensors

Scope

Is: a Rust library in a workspace with sub-crates; an idiomatic native API with the builder pattern; Python bindings (PyO3) with zero-copy; complete coverage of the scikit-learn taxonomy; ONNX, Safetensors and JSON debug export/import.
Is not (for now): a CLI for running workflows (recorded as a future improvement); a deep learning framework; an inference server.

API principles

  1. Mandatory builder pattern — every estimator, transformer and pipeline exposes a builder; direct constructors stay private. Every builder accepts execution_mode(SKExecutionMode::...), defaulting to Automatic.
  2. Zero-copy inputs — public APIs receive ArrayView, CowArray or sparse views (sprs), never arrays by value.
  3. Type-safe pipelines — step compatibility validated at compile time through associated types.
  4. Full descriptive names — no abbreviations; the single exception is the project prefix sk/SK. Examples: maximum_number_of_iterations (not max_iter), nearest_neighbors_count (not k).
// Core trait vocabulary — implemented by the sciencekit crates.
pub trait SKEstimator { /* hyperparameters and fit */ }
pub trait SKRegressorPredictor: SKEstimator { /* predict -> Array1<F> */ }
pub trait SKClassifierPredictor: SKEstimator { /* labels -> Array1<i64> */ }
pub trait SKTransformer: SKEstimator { /* transform / fit_transform */ }

pub trait SKDataSource { /* eager: full in-memory access */ }
pub trait SKLazySource { /* streaming: Iterator<Item = Batch> */ }
pub trait SKMappableSource { /* memmap: O(1) random access */ }

Algorithms compose exactly the traits they support: an SKSGDClassifier implements SKClassifierPredictor + SKLazySource; an SKStandardScaler implements only SKTransformer.

Interoperability

  • Single internal format: extended Safetensors — JSON header with hyperparameters, training state and recoverability metadata (checkpointing), with partial writes via sharding or header padding.
  • ONNX: every estimator implements SKToOnnx; external models load as a generic predictor.
  • Data: pluggable sources behind arbitrary I/O traits, with conversions for Polars and DataFusion.
  • Observability: tracing oriented to OpenTelemetry, disableable at near-zero cost.
Source of truth: this site mirrors the PRD (docs/PRD.md). Relevant scope changes go through that document first, before becoming technical specs.

Algorithms

The catalog mirrors the complete scikit-learn taxonomy. Every item enters the roadmap with a mandatory four-stage evolution — naive → tests → performance → out-of-core — and receives a Python binding as soon as it is validated on CPU.

43+ algorithms
  • Preprocessing5
  • Imputation3
  • Linear models7
  • Nearest neighbors4
  • SVM3
  • Trees2
  • Ensembles4
  • Clustering3
  • Decomposition3
  • Outliers1+
  • Model selection6
  • Metrics2+

Preprocessing · sciencekit_preprocessing

EstimatorDescriptionStatus
SKStandardScalerStandardizes by removing the mean and scaling to unit variance (dense · incremental · streaming)Implemented
SKMinMaxScalerAffine scaling of each column onto a configurable range with optional clipping (exact dense fit · sparse-aware incremental and streaming)Implemented
SKRobustScalerMedian / interquartile-range scaling with optional unit-variance normalization (exact dense fit · quantile-sketch incremental and streaming)Implemented
SKOneHotEncoderOne-hot encoding of categorical columns into dense or CSR indicators, with a configurable unknown-category policy (dense and streaming categorical fit)Implemented
SKPolynomialFeaturesPolynomial and interaction expansion with configurable degree, bias and dense/CSR output (dense · sparse · streaming)Implemented

Imputation · sciencekit_impute

EstimatorDescriptionStatus
SKSimpleImputerMean, median, most frequent and constant imputation (dense · sparse · incremental · streaming)Implemented
SKMissingIndicator0.0/1.0 mask of the features missing at fit time (dense · sparse)Implemented
SKKNNImputerMultivariate imputation from the nearest complete donors, with uniform or distance weights and an optional missing indicator (dense only; sparse views rejected)Implemented

Linear models · sciencekit_linear_model

EstimatorDescriptionStatus
SKLinearRegressionOrdinary least squares (dense · incremental · streaming)Implemented
SKRidgeRegression with L2 regularization (dense · sparse · incremental · streaming)Implemented
SKLassoRegression with L1 regularization (dense · sparse · incremental · streaming)Implemented
SKElasticNetCombined L1 + L2 regularization (dense · sparse · incremental · streaming)Implemented
SKLogisticRegressionRegularized logistic classification (binary · multinomial · one-vs-rest · dense · sparse · incremental · streaming)Implemented
SKSGDClassifierStochastic-gradient linear classification (5 losses · one-vs-rest · dense · sparse · incremental · streaming)Implemented
SKSGDRegressorStochastic-gradient linear regression (4 losses · Huber / epsilon-insensitive · dense · sparse · incremental · streaming)Implemented
SKLoraAdapterLow-rank adaptation of a frozen linear or logistic coefficient block (fit · predict · merge/unmerge · export/import · dense and sparse)Implemented

Nearest neighbors · sciencekit_neighbors

Structure/EstimatorDescriptionStatus
SKKNeighborsClassifierk-NN classification (dense trees · sparse brute force)Implemented
SKKNeighborsRegressork-NN regression (dense trees · sparse brute force)Implemented
SKKDTreeImmutable, exact k-d tree over dense features (median split on the widest-spread axis; sparse views rejected with UnsupportedRepresentation)Implemented
SKBallTreeImmutable, exact ball tree over dense features (farthest-pivot split; sparse views rejected with UnsupportedRepresentation)Implemented

Support vector machines · sciencekit_svm

EstimatorDescriptionStatus
SKSVCKernel-based C-support-vector classification (SMO, OvO, Platt + coupling, dense and sparse)Implemented
SKSVR$\varepsilon$-insensitive support-vector regression (SMO, dense and sparse)Implemented
SKLinearSVCScalable linear SVM (dual coordinate descent, hinge and squared hinge, one-vs-rest, class weights, dense and sparse)Implemented

Trees and ensembles · sciencekit_tree + sciencekit_ensemble

EstimatorDescriptionStatus
SKDecisionTreeClassifierCART for classification (dense and sparse, deterministic)Implemented
SKDecisionTreeRegressorCART for regression (dense and sparse, deterministic)Implemented
SKRandomForestClassifierRandom-forest classification (bootstrap, OOB accuracy, dense and sparse)Implemented
SKRandomForestRegressorRandom-forest regression (bootstrap, OOB $R^2$, dense and sparse)Implemented
SKBaggingClassifier / SKBaggingRegressorGeneric parallel bootstrap and feature-subspace aggregation over any supervised base estimator (OOB accuracy / $R^2$, dense and sparse)Implemented
SKGradientBoostingClassifier / SKGradientBoostingRegressorSequential gradient boosting over negative gradients with Newton leaves, shrinkage, subsampling and early stopping (binary, multiclass, squared/absolute/Huber, dense and sparse)Implemented
SKHistGradientBoostingClassifier / SKHistGradientBoostingRegressorLightGBM-style histogram boosting: quantile binning with a missing bin, parallel gradient/Hessian histograms, parent subtraction, leaf-wise growth, bitvec categorical partitions, learned missing routing, subsampling and early stopping (binary, multiclass, squared/absolute, dense and non-densified CSR)Implemented

Unsupervised · sciencekit_cluster, sciencekit_decomposition, sciencekit_outlier

EstimatorDescriptionStatus
SKKMeansLloyd + Elkan k-means with seeded k-means++ (memmap indexes remain Phase 7)Implemented
SKMiniBatchKMeansMini-batch k-means with per-center learning rates, deterministic reassignment, partial_fit and multi-epoch streaming (SKSourceProvider)Implemented
SKDBSCANDensity-based clustering over KD-tree / ball-tree and sparse brute-force region queries with explicit SKClusterLabel::Noise and nearest-core predictionImplemented
SKPCAPrincipal component analysis (full SVD · covariance eigh · sparse randomized SVD)Implemented
SKTruncatedSVDUncentered randomized low-rank SVD for latent semantic analysis and sparse dimensionality reduction (dense · sparse CSR)Implemented
SKIncrementalPCAOut-of-core incremental PCA (Chan-Golub-LeVeque scatter merge · CSR Gram accumulation · partial_fit & fit_streaming)Implemented
SKIsolationForestNon-parametric anomaly detection via random isolation trees, harmonic path-length scoring, Auto/quantile contamination offsets and non-densifying CSR parityImplemented
Anomaly detection (LOF, One-Class SVM)Remaining outlier estimators from the scikit-learn familyPlanned

Model selection, pipelines and metrics

ItemCrateDescriptionStatus
sk_train_test_splitsciencekit_model_selectionSeeded train/test partition by fraction or explicit count, with optional stratification, gathering rows without densifying sparse inputImplemented
SKKFoldsciencekit_model_selectionPlain K-fold with an optional seeded shuffle; disjoint test folds together cover every row exactly onceImplemented
SKStratifiedKFoldsciencekit_model_selectionK-fold preserving per-class proportions; rejects a class with fewer examples than foldsImplemented
SKGroupKFoldsciencekit_model_selectionK-fold that keeps every group entirely on one side of each splitImplemented
SKGridSearchCVClassifier / SKGridSearchCVRegressorsciencekit_model_selectionTyped grid search over configured candidates with shared foldsImplemented
SKHalvingGridSearchClassifier / SKHalvingGridSearchRegressorsciencekit_model_selectionSuccessive-halving search: geometric resource schedule, seeded and stratified round subsamples, deterministic elimination trace, aggressive early pruning and winner refitImplemented
Halving resource axes beyond sample countssciencekit_model_selectionAdditional SKHalvingResource variants (trees, epochs)Planned
SKPipelinesciencekit_pipelineType-safe linear pipeline (compiler-checked composition)Implemented
SKPipelineGraphsciencekit_pipelineValidated runtime DAG pipeline: topological fit and predict, deterministic level order, edge-order merges without densifying CSR, node-attributed errors and classifier/regressor wrappersImplemented
SKStreamingPipelinesciencekit_pipelineOut-of-core linear pipeline over an SKSourceProvider: chained SKStreamingTransformer fitting through the shared prefetch executor, one-shot materialization within a byte budget, multi-epoch replay, CSR-preserving per-batch transform and a bounded batch finalizerImplemented
Classification, regression and clustering metricssciencekit_metricsAccuracy, precision/recall/F1 with macro/micro/weighted/binary averaging, confusion matrix, MSE/RMSE/MAE, $R^2$, silhouette, Calinski-Harabasz, Davies-Bouldin, homogeneity/completeness/V-measure, adjusted Rand and mutual information, plus scorer adapters and streaming accumulatorsImplemented
Ranking metricssciencekit_metricsROC/AUC (binary and multiclass one-vs-rest), ROC and precision-recall curves, average precision, log loss, Matthews correlation and balanced accuracy, with a streaming AUC accumulator and scorer adaptersImplemented
Calibration and multilabel metricssciencekit_metricsCalibration curves, Brier score and multilabel losses (e.g. Hamming and Jaccard)Planned
SKTabularDataset / SKTabularSourceConfigsciencekit_interopEngine-neutral tabular sources: column kinds, dense/sparse feature blocks, owned categorical codes and label tables, numeric/categorical missing mappingImplemented
Polars sourcessciencekit_interopDataFrame and reopenable LazyFrame batches behind the optional polars feature (Polars 0.46, Rust 1.85 pin)Implemented
DataFusion, Arrow and Parquet sourcessciencekit_interopDataFusion 46 DataFrame/RecordBatch conversion, true record-batch streaming and Parquet-through-DataFusion behind the optional datafusion feature, alongside the Arrow 58 adapterImplemented
ONNX exportsciencekit_onnxSKToOnnx translation of the neutral model state into opset-17 ONNX graphs with ONNX-ML tree ensembles, SVM kernel expansions, per-family parity tests and an onnxruntime comparison harness; unsupported families return UnsupportedOperation and are listed in sk_onnx_coverageImplemented
ONNX importsciencekit_onnxSKOnnxModel over the shared serde-onnx IR, SKOnnxPredictor<F> implementing both prediction traits, a documented interpreter for the emitted operator subset (including ONNX-ML tree ensembles), typed validation errors, export/import round-trip tests and a three-way onnxruntime harness (36/36 import fixtures)Implemented
Model export/import coverageevery model crateSKExportable / SKImportable state for scalers, encoders, imputers, linear and SGD models, neighbours, SVMs, decision trees, forests, gradient boosting and bagging, with stable dotted tensor names, metadata versioning, dense/CSR parity and prediction round-trip testsImplemented
Native model import & retrainingsciencekit_interop, sciencekit_onnxSKNativeImport<F> rebuilds linear/logistic, SGD, tree, forest, scaler and k-means models from Safetensors, JSON or a documented ONNX subset, with structural format detection, exact tensor-set and class-table validation, typed rejections, continued fitting where the algorithm keeps its state, and a concurrency-safe conversion surfaceImplemented
Extended Safetensors & JSON debugsciencekit_interopBinary Safetensors persistence (metadata header, SKShardPlan sharding, in-place header/payload padding, optional Gzip/Brotli/Snappy compression) and deterministic JSON debug inspection over SKModelStateImplemented
Memory-mapped sources (memmap feature)sciencekit_interopZero-copy SKMappableSource/SKLazySource over raw binary, NumPy .npy and footer-indexed Arrow IPC files, with descriptor, length, endianness, alignment and truncation validationImplemented
OpenCL backend (opencl feature)sciencekit_gpu, sciencekit_gpu_openclFirst real device backend behind SKComputeBackend: ICD-loader device discovery, builder-only construction, device buffers with memory/capacity validation, explicit accounted transfers, runtime-compiled pairwise/GEMM/elementwise/tree kernels with CPU parity, concurrent dispatch and honest CPU fallbackImplemented
SKTelemetry / SKTelemetryPipelinesciencekit_telemetryOpt-in OTLP trace, log and metric export pipelines, resource attributes, sampling and bounded lifecycle (silent no-op default)Implemented
sciencekit CLI (workflows-cli)sciencekit_clifit, predict, transform, evaluate, export, inspect and run; versioned JSON/TOML/YAML workflow records, flags > environment > file > defaults resolution, dry-run, CSV/Parquet datasets, Safetensors/JSON/ONNX models and stable exit codesImplemented

One entry point · sciencekit

Every crate below stays independently consumable, but applications normally add the umbrella package. It re-exports the stable public surface under family modules and gives docs.rs and crates.io a single front page; it adds no logic.

ModuleOwning crate(s)Contents
sciencekit::preludecurated across familiesbuilder/fit/predict traits, data views, SKError, SKFloat and the headline estimators
sciencekit::mathsciencekit_mathkernels, pairwise distances, solvers and the math backend
sciencekit::preprocessingsciencekit_preprocessingscalers, one-hot, polynomial features
sciencekit::imputesciencekit_imputesimple, indicator and KNN imputers
sciencekit::linear_modelsciencekit_linear_modellinear, regularized, logistic and SGD models
sciencekit::neighbors, sciencekit::svmsciencekit_neighbors, sciencekit_svmnearest neighbors and support-vector machines
sciencekit::tree, sciencekit::ensemble, sciencekit::outliersciencekit_tree, sciencekit_ensemble, sciencekit_outliertrees, forests, boosting and isolation forests
sciencekit::cluster, sciencekit::decompositionsciencekit_cluster, sciencekit_decompositionclustering, PCA and SVD
sciencekit::model_selection, sciencekit::pipeline, sciencekit::metricssciencekit_model_selection, sciencekit_pipeline, sciencekit_metricssplitting, search, composition and evaluation
sciencekit::interopsciencekit_interop, sciencekit_onnxtabular sources, model formats and ONNX
sciencekit::accelerators, sciencekit::telemetry, sciencekit::ffisciencekit_gpu, sciencekit_gpu_opencl, sciencekit_telemetry, sciencekit_ffidevice contracts, OTLP export and the C ABI

Integration features (opencl, telemetry, onnx, polars, datafusion, memmap, parquet) are off by default and forward to the owning crate.

Continuous acceleration: every completed algorithm receives, in separate changes, a Python binding (sciencekit_python) and GPU backends (OpenCL → CUDA → ROCm) behind SKComputeBackend. The CPU is the default backend, always present.

Architecture

The project is a Cargo workspace split into cohesive sub-crates, optimizing build times and isolating dependencies. Every structural rule below comes from the PRD (§3–§9).

Workspace layout

flowchart TD
    accTitle: The sciencekit Cargo workspace layout
    accDescr: A workspace root holding Cargo.toml and a crates folder. The crates folder contains an umbrella crate, two foundation crates, and one crate per algorithm area, plus a docs folder.
    ROOT[sciencekit/]
    ROOT --> CARGO[Cargo.toml<br/>workspace root]
    ROOT --> CRATES[crates/]
    ROOT --> DOCS[docs/]

    subgraph FOUNDATION[Foundation]
        UMBRELLA[sciencekit/<br/>umbrella crate re-exports]
        COMMON[sciencekit_common/<br/>base traits, types, central errors]
        MATH[sciencekit_math/<br/>linear algebra, BLAS, SIMD, sparse, pairwise]
    end

    subgraph ALGORITHMS[Algorithm crates]
        PREP[sciencekit_preprocessing/<br/>scalers, encoders, polynomial features]
        IMPUTE[sciencekit_impute/<br/>simple and multivariate imputers]
        LINEAR[sciencekit_linear_model/<br/>linear regressions, logistic, SGD]
        NEIGHBORS[sciencekit_neighbors/<br/>KNeighbors, KDTree, BallTree]
        SVM[sciencekit_svm/<br/>SVC, SVR, LinearSVC]
        TREE[sciencekit_tree/<br/>decision trees]
        ENSEMBLE[sciencekit_ensemble/<br/>random forest, bagging, gradient boosting]
        CLUSTER[sciencekit_cluster/<br/>KMeans, DBSCAN, MiniBatchKMeans]
        DECOMP[sciencekit_decomposition/<br/>PCA, TruncatedSVD]
        OUTLIER[sciencekit_outlier/<br/>anomaly detection]
    end

    subgraph SUPPORT[Support crates]
        SELECTION[sciencekit_model_selection/<br/>KFold, train_test_split, GridSearchCV]
        PIPELINE[sciencekit_pipeline/<br/>type-safe SKPipeline, DAGs]
        METRICS[sciencekit_metrics/<br/>evaluation metrics]
        INTEROP[sciencekit_interop/<br/>ONNX, Safetensors, I/O traits]
        TELEMETRY[sciencekit_telemetry/<br/>OTLP traces, logs, metrics]
        GPU[sciencekit_gpu/<br/>SKComputeBackend + OpenCL/CUDA/ROCm]
        PYTHON[sciencekit_python/<br/>PyO3 bindings]
    end

    CRATES --> FOUNDATION
    CRATES --> ALGORITHMS
    CRATES --> SUPPORT

    style ROOT fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style FOUNDATION fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style ALGORITHMS fill:#fef3c7,stroke:#d97706,color:#78350f
    style SUPPORT fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

Structural rules

RuleDetail
One responsibility per moduleModules stay small enough to have exactly one responsibility.
200-line limitA .rs file exceeding 200 lines becomes a folder module (mod.rs, builder.rs, core_implementation.rs, fitting_logic.rs, *_tests.rs).
Single responsibility per itemFunctions, structs and traits do one thing. Prefer trait composition over responsibility inheritance.
Small PRsEach change alters the minimum necessary.

Naming convention

No abbreviations anywhere — single exception: the project prefix sk/SK.

Item kindConventionExample
Structs and traitsSK + PascalCaseSKEstimator, SKStandardScaler
Free public functions, variables, modulessk_ + snake_casesk_train_test_split
Methods (inside impl)complete name onlyfit, predict, execution_mode
Cratesfull namesciencekit_linear_model
// Illustrative — naming convention in action.
let model = SKKMeansClassifierBuilder::new()
    .maximum_iterations(300)      // not max_iter
    .nearest_neighbors_count(5)   // not k
    .build()?;

Core traits (sciencekit_common)

Trait composition is the foundation of everything:

// Core trait vocabulary — implemented by the sciencekit crates.
pub trait SKEstimator { /* hyperparameters and fit */ }
pub trait SKRegressorPredictor: SKEstimator { /* predict -> Array1<F> */ }
pub trait SKClassifierPredictor: SKEstimator { /* labels -> Array1<i64> */ }
pub trait SKTransformer: SKEstimator { /* transform / fit_transform */ }

pub trait SKDataSource { /* eager: full in-memory access */ }
pub trait SKLazySource { /* streaming: Iterator<Item = Batch> */ }
pub trait SKMappableSource { /* memmap: O(1) random access */ }
pub trait SKToOnnx { /* ONNX export */ }
pub trait SKComputeBackend { /* compute device abstraction */ }

Algorithms compose exactly the traits they support: an SKSGDClassifier implements SKClassifierPredictor + SKLazySource; an SKStandardScaler implements only SKTransformer.

Memory management

Zero-copy is non-negotiable: public APIs receive ArrayView, CowArray or sparse views (sprs) — never copies of giant matrices. Memory layout (row-major/column-major, contiguity) is always considered in binary operations.

Higher-order iteration is mandatory: .map(), .map_inplace(), .zip_mut_with(), plus azip!() / par_azip!() and rayon for data parallelism — never manual index loops.

Custom allocators

AllocatorFeature flagCharacteristics
glibc malloc(none — fallback)System default, zero dependencies
jemallocallocator-jemallocPer-thread arenas; shines with many same-size allocations
mimallocallocator-mimallocVery low p99 latency; variable sizes

Expected gains vs glibc on ML workloads: 15–30% allocation throughput. The automatic decision mechanism picks the default per platform and workload.

Out-of-core strategies

Every algorithm declares its access pattern and implements what works:

TraitStrategyTypical algorithms
SKLazySourceSequential streaming in batchesSKSGD*, SKMiniBatchKMeans, incremental SKPCA
SKMappableSourceMemory-mapped files, O(1) random accessSKKMeans, SKKNN, SKDBSCAN, SKDecisionTree

Sparse arrays are first-class from day one via sprs + ndarray (CSR/CSC/COO) — essential for Lasso, linear SVMs and text classification.

Threads and concurrency

Non-negotiable rule: CPU-intensive work never blocks async threads. Math runs on rayon's pool; Tokio handles I/O and delegates computation blocks to the CPU pool.

Automatic execution decision

Every builder exposes execution_mode(SKExecutionMode::...). Default: Automatic.

ModeWhen
InProcessSynchronousDataset fits in RAM; eager algorithm; rayon only
InProcessAsynchronousAsync I/O source; Tokio orchestrates, rayon computes
OutOfCoreStreamingDataset > RAM; sequential batches (SKLazySource)
OutOfCoreMemoryMappedDataset > RAM; random access required (SKMappableSource)

The decision weighs: available memory (sysinfo), dataset size, declared access pattern, CPU cores (available_parallelism) and an optional batch hint. Users can override any parameter in the builder.

Size-aware parallelism

Resolution derives parallelism = min(cores, ceil(unit / grain)), where the work unit is the whole dataset (in-memory), one batch (streaming), or an arbitrary shard (memory-mapped → always the core count). A single-core machine or a sub-grain unit resolves to exactly 1 (sequential, no dispatch overhead). The per-kernel grain (minimum elements per thread to amortize dispatch) is measured by the kernel_calibration criterion bench and recorded beside each kernel with machine + date provenance (see math-kernel).

flowchart LR
    accTitle: How an execution intent becomes a plan and how it is executed
    accDescr: An execution intent and a context are resolved into an execution plan that carries a mode and parallelism. In-memory plans run kernels that honor parallelism; streaming plans use a driver with an I/O thread prefetching into a double buffer and a compute pool updating state; memory-mapped plans run parallel shards.
    Intent[Execution intent] --> Resolve[sk_resolve_execution_plan]
    Ctx[Context: memory / cores / size / grain] --> Resolve
    Resolve --> Plan[SKExecutionPlan: mode + parallelism + batch_size + buffer_depth]
    Plan --> Mode{Mode}
    Mode -- In-memory --> Kernels[Kernels honor parallelism]
    Mode -- Streaming --> Driver[Streaming driver]
    Driver --> IoThread[I/O thread]
    Driver --> Compute[Compute pool]
    IoThread -->|prefetch k+1| Buffer[(Double buffer)]
    Buffer --> Compute
    Compute -->|update batch k| Update[Algorithm update step]
    Update -->|Continue or Stop| Driver
    Mode -- Memory-mapped --> Shards[Parallel shards, parallelism = cores]

For streaming, the driver owns the I/O ∥ CPU overlap: a dedicated I/O thread prefetches the next batch into a bounded double buffer while the compute pool processes the current batch via an algorithm-supplied update(batch, parallelism, state) step. Resolution guards the double-buffer footprint — $2 \times \text{batch} \le \text{available memory}$ — and refuses oversized batch hints before any data is processed.

Optimization layers

  1. Algorithmic — correct complexity before micro-optimization.
  2. Memory layout — contiguity, cache-friendliness, SoA vs AoS where relevant.
  3. Higher-order functions — azip!/par_azip!/zip_mut_with (mandatory).
  4. SIMD — LLVM autovectorization → explicit wide on profiled hot paths → std::simd when stable.
  5. BLAS — opt-in flag (blas-backend: OpenBLAS default, BLIS alternative, MKL never a direct dependency).
  6. GPU — additional backend per separate change via SKComputeBackend (OpenCL → CUDA → ROCm).
  7. Allocators — automatic choice, user-configurable.

Feature flags have dual granularity: per capability (parallel, allocator-*, blas-*, gpu-*, telemetry-opentelemetry) and per algorithm group (classification, regression, clustering, …).

Model export and import

  • Single internal format: extended Safetensors — JSON header with "sciencekit_format_version", hyperparameters, training state and recoverability metadata (checkpointing).
  • Partial writes: in-place tensor updates at known offsets; sharding for large models; header padding for small ones.
  • Compression: .safetensors.gz, .safetensors.brotli, .snappy.safetensors.
  • ONNX: every estimator implements SKToOnnx; external models load as a generic predictor.
  • JSON debug: human-readable serialization through the same central export trait.

Errors use thiserror enums per algorithm with uniform propagation of common errors; observability uses tracing oriented to OpenTelemetry, disableable at near-zero cost.

sciencekit_math — computational kernels and BLAS interface

The sciencekit_math crate is the numeric substrate every downstream algorithm crate builds on (Phase 0.3). It provides the reusable operation kernels, memory-layout helpers, pairwise-distance matrices, sparse products and the BLAS/LAPACK backend abstraction that the algorithm crates consume.

Purpose

  • Performance-first kernels honouring PRD §4: higher-order iteration with azip!/par_azip! (never manual index loops), SIMD hot paths, and layout awareness.
  • Zero-copy public APIs built on ndarray::ArrayView, ndarray::CowArray and sprs views.
  • A uniform linear-algebra abstraction ([SKMathBackend]) with a pure-Rust default (faer) and an opt-in system-BLAS path.

Modules

ModuleResponsibility
kernelsElementwise transform, binary combine, axis reductions and in-place scaling.
layoutC/F-contiguity detection and contiguity-forcing.
pairwiseSquared-Euclidean ($|a|^2 - 2a \cdot b + |b|^2$), Euclidean, Manhattan, Cosine, Chebyshev and NaN-aware Euclidean distance matrices, dense or sparse.
sparse_opssprs CSR×dense and sparse×sparse products over zero-copy views.
backendSKMathBackend trait + SKFaerBackend (default), SKMatrixMultiplyBackend, and the opt-in blas-backend feature.
flowchart LR
    accTitle: Modules of sciencekit_math and their key surfaces
    accDescr: sciencekit_math exposes kernels using azip and par_azip, layout helpers, pairwise distance kernels using a SIMD dot, sparse operations over sprs views, and a backend that defaults to faer with an opt-in blas-backend.
    A[sciencekit_math] --> B[kernels]
    A --> C[layout]
    A --> D[pairwise]
    A --> E[sparse_ops]
    A --> F[backend]
    B --> G["azip! / par_azip! / zip_mut_with"]
    C --> H["sk_memory_layout / sk_force_contiguous"]
    D --> I["wide SIMD dot kernel"]
    E --> J["sprs views"]
    F --> K["SKFaerBackend (pure Rust)"]
    F --> L["blas-backend (opt-in)"]

Key public API

  • Kernels — sk_elementwise_transform, sk_binary_combine, sk_axis_sum, sk_scale_in_place.
  • Layout — SKMemoryLayout, sk_is_c_contiguous, sk_is_f_contiguous, sk_force_contiguous.
  • Distances — sk_squared_euclidean_distance_matrix, sk_euclidean_distance_matrix, sk_manhattan_distance_matrix, sk_cosine_distance_matrix, sk_chebyshev_distance_matrix, sk_nan_euclidean_distance_matrix; the dispatcher sk_pairwise_distance_matrix(metric, left, right) picks the dense or sparse kernel for any of the four representation pairs and never densifies a sparse input (the NaN-aware metric is dense-only, since a CSR implicit zero is an observed value); the public sparse kernels are sk_sparse_squared_euclidean_distance_matrix, sk_sparse_euclidean_distance_matrix, sk_sparse_manhattan_distance_matrix, sk_sparse_chebyshev_distance_matrix and sk_sparse_cosine_distance_matrix.
  • Sparse — sk_csr_dense_product, sk_sparse_product.
  • Backend — SKMathBackend (trait), SKFaerBackend, SKMatrixMultiplyBackend, SKNdArrayLinalgBackend (blas-backend only), sk_default_math_backend.

All structs/traits use the SK prefix and free functions the sk_ prefix (PRD §3.4).

Resolved parallelism and grain

Every dense kernel accepts the resolved plan’s parallelism and honours it: 1 runs the sequential azip!/zip_mut_with form with zero dispatch overhead; > 1 dispatches par_azip! (or a per-row/per-chunk parallel reduction) across the rayon compute pool. Parallel results match the sequential reference within floating-point tolerance.

KernelParallelism behaviour
sk_elementwise_transform1 → azip!, > 1 → par_azip!
sk_binary_combine1 → zip_mut_with, > 1 → par_azip!
sk_axis_sumaxis-0: per-chunk partial accumulation (no shared accumulator); axis-1: per-row
sk_scale_in_place1 → azip!, > 1 → par_azip!

Policy lives in sk_resolve_execution_plan, not in the kernels. Resolution derives parallelism = min(cores, ceil(unit / grain)) from the work-unit size (the whole dataset in memory, one batch when streaming) capped by the core count, and returns exactly 1 for single-core machines or sub-grain units. Each kernel documents a grain — the minimum elements per work unit needed to amortize parallel dispatch — measured by the kernel_calibration criterion bench (cheap/medium/expensive closures $\times$ sizes $10^1$–$10^7$) and recorded beside the kernel with machine + date provenance:

Kernel grain constantValueCalibrated on
SK_ELEMENTWISE_TRANSFORM_GRAIN1_000_0002026-09-11, i7-12700H (20 cores)
SK_BINARY_COMBINE_GRAIN10_000_0002026-09-11, i7-12700H (20 cores)
SK_AXIS_SUM_GRAIN100_0002026-09-11, i7-12700H (20 cores)
SK_SCALE_IN_PLACE_GRAIN1_000_0002026-09-11, i7-12700H (20 cores)

The same grain applies to in-memory and streaming regimes. Re-calibrating on another machine changes only these constants and their provenance; the behaviour contracts above are unaffected.

Usage examples

Elementwise transform and an in-place scale (both take the resolved parallelism):

#![allow(unused)]
fn main() {
use ndarray::{array, Array1};
use sciencekit_math::sk_elementwise_transform;

let input = array![1.0_f64, 2.0, 3.0];
let transformed = sk_elementwise_transform(&input.view(), |x| 2.0 * x + 1.0, 1);
// transformed == [3.0, 5.0, 7.0]
}

Squared-Euclidean distance matrix between two feature sets:

#![allow(unused)]
fn main() {
use ndarray::array;
use sciencekit_math::sk_squared_euclidean_distance_matrix;

let points = array![[0.0_f64, 0.0], [3.0, 4.0]];
let distance = sk_squared_euclidean_distance_matrix(&points.view(), &points.view());
// symmetric, zero diagonal, non-negative
}

A dense matrix product through the pure-Rust default backend:

#![allow(unused)]
fn main() {
use faer::{Mat, MatRef};
use sciencekit_math::{SKFaerBackend, SKMathBackend};

let a = Mat::<f64>::from_fn(2, 2, |i, j| (i * 2 + j) as f64);
let b = Mat::<f64>::identity(2, 2);
let backend = SKFaerBackend::new();
let product = backend.gemm(a.as_ref(), b.as_ref(), 1.0);
}

These examples mirror the crate’s companion *_tests.rs modules, which are the executable source of truth for each function’s behaviour.

The blas-backend feature

By default the crate links no C/Fortran BLAS: heavy algebra runs on the pure-Rust faer backend. Enabling the blas-backend feature swaps dense algebra to ndarray-linalg over the configured blas-src backend (OpenBLAS/BLIS/MKL/Accelerate); faer remains available as a fallback. sk_default_math_backend selects the active backend.

Small fixed-size matrices (nalgebra)

For 2×2/3×3 hot paths (e.g. PCA covariance, affine transforms) where GEMM overhead dominates, nalgebra 0.35 was considered as a small-matrix fallback. Per the wave-plan-foundation decision (ADR #37) it is deferred, not adopted: sciencekit_math exposes no small-matrix hot paths yet, and faer’s small-matrix performance is assumed adequate. The decision is retargeted to W5.4 (PCA), where the 2×2/3×3 covariance path actually lands.

Safety

This is the performance crate: unsafe is confined to the SIMD (wide) and matrix multiply kernels and never appears in the higher-order or layout layers.

Plan & Roadmap

The roadmap follows the scikit-learn mapping faithfully, respecting dependencies between crates. Development methodology is as important as the destination. The wave decomposition below comes from the wave-plan-foundation planning change (OpenSpec) — every downstream change references it as the shared reference.

📋
OpenSpec-first

Every change starts with a specification (proposal, deltas, design, tasks) on a dedicated -openspec branch, reviewed before any code.

🔴
Mandatory TDD

Test first, confirmed failure, minimal implementation, refactoring — with companion *_tests.rs modules and mock data in ndarray/sprs.

🌳
Worktree workflow

No direct commits to main. Every change lives in a git worktree with small, focused PRs.

🔍
Independent review

An independent agent validates that the spec was effectively met before every PR.

Iterative evolution per algorithm

No stage may be skipped — each algorithm walks the full path:

1 · Naive implementation
1st
2 · Unit tests (TDD)
2nd
3 · Performance (SIMD/rayon/layout)
3rd
4 · Streaming / out-of-core
4th

Acceptance checklist (every implementation)

  • Runs correctly with lots of data and with little data
  • Correct under concurrency (automatic + applicable explicit modes)
  • Exports model (minimum Safetensors) and produces metrics
  • Companion _tests.rs modules covering everything above
  • Complete names, no abbreviations (single exception: sk/SK)
  • Public items with mandatory prefix; methods unprefixed
  • No file over 200 lines without folder-module organization
  • Python binding in an associated change; GPU backends in separate changes

Phases

Phase 0 — FoundationsComplete

Workspace bootstrap + CI · sciencekit_common traits + central errors · sciencekit_math kernel (pure-Rust faer default) · automatic execution decision + builders + tracing/OTel + allocators.

W0.1–W0.4 landed: bootstrap-workspace, common-core-foundation, math-kernel-foundation, execution-decision-and-observability4/4
Phase 1 — PreprocessingIn progress

SKStandardScaler (dense · incremental partial_fit · out-of-core streaming) · SKMinMaxScaler, SKRobustScaler (tdigest online quantile sketch) · SKOneHotEncoder, SKPolynomialFeatures; imputation strategies (SKSimpleImputer). SKKNNImputer moved to Wave 3, built directly on the trees — no brute-force placeholder.

W1.1 landed: standard-scaler (dense, incremental and out-of-core)1/4
Phase 2 — Linear modelsPlanned

Linear/Ridge/Lasso/ElasticNet/Logistic regressions; SGD classifier/regressor with streaming (SKLazySource).

Phase 3 — Neighbors & SVMIn progress

k-NN classifier/regressor, KD-tree, Ball-tree; SKSVC, SKSVR, LinearSVC.

memmap2-backed indexes and SVM kernel caches, model persistence and model export are deferred to Phase 7 (interop).

Phase 4 — Trees & ensemblesPlanned

Decision trees; Random Forest, Bagging, Gradient Boosting aggregated in parallel with rayon.

Tree persistence and model export are Phase 7 deliverables.

Phase 5 — UnsupervisedIn progress

KMeans, MiniBatchKMeans (streaming), DBSCAN; PCA, TruncatedSVD; anomaly detection.

Phase 6 — Selection, pipelines, metricsPlanned

KFold, train/test split, GridSearchCV; type-safe SKPipeline with DAGs; full metrics suite.

Phase 7 — Interop & productionPlanned

Safetensors sharding/padding/compression, ONNX export/import, Polars/DataFusion sources; umbrella crate; complete PyO3 bindings.

Wave plan and foundational decisions

The wave-plan-foundation planning change decomposes PRD phases 0–7 into waves W0–W7 — roughly 60 downstream changes — so dependencies are respected naturally and no throwaway/placeholder implementations are needed. It also locks six foundational technical decisions that every downstream change references:

⚛
1 · Pure-Rust BLAS/LAPACK

faer 0.24.4 is the default (SKFaerBackend); matrixmultiply is the GEMM fallback; ndarray-linalg+blas-src stays an opt-in blas-backend. oxiblas was disqualified: it does not compile on MSRV 1.85.

🎮
2 · GPU arrival order

OpenCL 3.0 first, ICD-agnostic via opencl3 + the OpenCL loader (vendor-transparent); Metal after; CUDA/ROCm only on request. Heavy algebra stays on CPU.

📊
3 · Online quantile sketch

tdigest 1.0.0 powers SKRobustScaler::partial_fit — a capability scikit-learn lacks (percentiles require the full column).

🗜
4 · Pure-Rust sparse SVD

faer-sparse + rsvd-faer for SKTruncatedSVD; hand-rolled Lanczos fallback; arpack-sys as opt-in. single-svdlib (gold-standard IRLBA) waits on an MSRV bump.

🧵
5 · Nested rayon

rayon owns all parallelism (work-stealing caps threads); BLAS runs single-threaded inside rayon scopes. No semaphore, no threadpoolctl-style hack.

🩹
6 · KNNImputer placement

SKKNNImputer lives in Wave 3, built directly on SKKDTree/SKBallTree — no brute-force placeholder or searcher-trait hack.

Deferred tracker (ADR #37): the nalgebra role for small fixed-size matrices was deferred at W0.3 — not adopted, since sciencekit_math has no small-matrix hot paths yet. Revisit at W5.4 (PCA), adopting nalgebra 0.35 only if faer’s small-matrix performance proves inadequate for 2×2/3×3 covariance.

Cross-cutting (continuous)

Per completed algorithm: Python binding in an associated change; GPU backend (OpenCL 3.0 ICD-agnostic first → Metal after; CUDA/ROCm only on request) in following separate changes.
Recorded for the future: workflows CLI; ONNX/Safetensors import converted to native types with retraining/LoRA support.

How to add an Algorithm

This is the boiler plate. It contains no algorithm — only the skeleton every algorithm in sciencekit must follow, and the discipline that keeps hundred algorithms coherent instead of a drawer of clever one-offs. Every case-study chapter in this part assumes this recipe and refers to it by section number.

Contract level. Everything below is written against the merged master contracts of sciencekit_common and sciencekit_math as of the parallel-kernel-execution wave: SKBuilder/SKBuilderState, SKSupervisedFit/SKUnsupervisedFit/SKFeatureTransformer/SKRegressorPredictor/SKClassifierPredictor, SKDataView/SKTargetView, SKExecutionContext/sk_resolve_execution_plan, sk_run_streaming_driver, SKLazySource/SKMappableSource, the measured-grain kernels and the SKMathBackend abstraction. When a real algorithm crate lands and any signature has moved, this chapter is the one that gets the maintenance edit.


0. The journey at a glance

The whole routine, before the details:

flowchart TD
    accTitle: The algorithm routine from failing test to acceptance
    accDescr: Test-first contract, builder plus estimator, execution planning across three regimes, model export, and PRD section 8.7 acceptance gates.
    classDef buildNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
    classDef planNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
    classDef regNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
    classDef outsNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px

    T["TDD: failing<br>contract test first"]:::buildNode
    T --> B["Builder + estimator<br>SKBuilderState, validate in build()"]:::buildNode
    B --> Fit["estimator · fit(&self) implements<br>SKUnsupervisedFit |<br>SKSupervisedFit<br>+ SKFeatureTransformer when transformer"]:::buildNode
    Fit --> P{"SKExecution<br>Context<br>grain · access_pattern"}:::planNode
    P --> PLN["sk_resolve_execution_plan<br>(Automatic default)"]:::planNode
    PLN -->|"InProcess* | whole array"| K["measured-grain kernels<br>plan.parallelism threads"]:::regNode
    PLN -->|">RAM, sequential"| Dr["sk_run_streaming_driver<br>State + update() per batch"]:::regNode
    PLN -->|">RAM, RandomAccess"| Ma["SKMappableSource<br>memory-mapped rows"]:::regNode
    K -->     Ms["Model (distinct type)<br>predictor /<br>transform verbs"]:::outsNode
    Dr --> Ms
    Ma --> Ms
    Ms --> Chk["§8.7 acceptance + export + scorers<br>fmt · clippy · test · mdbook build"]:::outsNode

1. What “adding an algorithm” means

You are not writing “a file with a math loop”. You are adding a new public estimator to the catalog, which means six obligations, each checked by a gate:

#ObligationChecked by
1Naming and file layout follow the conventionsreview; project conventions
2Construction is impossible to misuse (builder pattern)traits: SKBuilder<Model>
3Inputs enter zero-copy and are validated at the seamtraits: TryInto<SKDataView/T>
4The estimator works in all three execution regimes or declares why notsk_resolve_execution_plan + your tests
5Every operation is observable (sk_run_operation spans)telemetry review
6It passes PRD §8.7 acceptance: little and lots of data, under concurrency, model export, metricsyour *_tests.rs modules

Skipping any of the six produces the estimators this library exists to make unnecessary.


2. File layout and naming

2.1 Folder modules, always private-state, never index loops

Once any file reaches 200 lines, it becomes a folder module with a standardized shape. Start in that shape directly: implement the algorithm expecting to exceed 200 lines.

flowchart TD
  accTitle: The standard folder-module layout for an algorithm
  accDescr: The standard_scaler folder contains a pure dispatcher mod.rs that only declares submodules and re-exports, a builder file with hyperparameter validation and build, a core implementation file with the estimator and fit internals, an owned model file with transform, and a companion tests file declared at the end of mod.rs.
  ROOT["crates/sciencekit_preprocessing/src/standard_scaler/"]
  ROOT --> MOD["mod.rs<br/>pure dispatcher: module declarations and re-exports only"]
  ROOT --> BUILDER["builder.rs<br/>builder, hyperparameter validation and build()"]
  ROOT --> CORE["core_implementation.rs<br/>the estimator struct and fit internals"]
  ROOT --> MODEL["model.rs<br/>the fitted object and transform"]
  ROOT --> TESTS["standard_scaler_tests.rs<br/>companion tests, declared at the end of mod.rs"]

Three hard rules from the conventions chapter:

  1. mod.rs carries no logic. It declares submodules and re-exports public items.
  2. Tests live beside the implementation in a companion *_tests.rs — never a global tests/ directory. The tests are later quoted, verbatim, in the Development Explained chapter for your algorithm; they are the executable truth.
  3. No manual index loops. Iteration is azip!(), map(), par_azip!().

2.2 Naming rules (PRD §3.4)

  • No abbreviations, ever, with the single exception of the project prefix. The builder field is maximum_number_of_iterations: usize, not max_iter; the count of nearest neighbors is nearest_neighbors_count, not k.
  • Structs and traits: SK + PascalCase → SKStandardScaler, SKRegressorPredictor.
  • Free public functions, public variables, public modules: sk_ + snake_case → sk_resolve_execution_plan, sk_axis_sum.
  • Methods get no prefix — standing inside an impl is the privilege that earns it: fn fit(...), fn transform(...), fn predict(...).
  • Crates keep their full name: sciencekit_preprocessing, never sk_prep.

The discipline is not pedantry: a dataframe.max_iter reads like a contract to every future reader; an abbreviation makes every editor and greppable name a guessing game.


3. The four contracts your algorithm plugs into

sciencekit does not have one Estimator god-trait. It has small verbs, and your algorithm composes exactly the ones it supports (PRD §3.3).

3.1 Fitting traits — one of three

#![allow(unused)]
fn main() {
// Unsupervised (scalers, kmeans, pca): features only.
pub trait SKUnsupervisedFit<F: SKFloat> {
    type Model;                                  // the FITTED object — a distinct type
    type Error: From<SKError>;
    fn fit<'a, X>(&self, features: X) -> Result<Self::Model, Self::Error>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>;
}

// Supervised (regressors, classifiers): features + targets.
pub trait SKSupervisedFit<F: SKFloat> {
    type Model;
    type Error: From<SKError>;
    fn fit<'a, X, T>(&self, features: X, targets: T) -> Result<Self::Model, Self::Error>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>,
        T: TryInto<SKTargetView<'a>, Error = SKError>;
}

// Transformers additionally transform, with a statically known output type
// (this associated type is what makes pipeline chaining compile-time checked).
pub trait SKFeatureTransformer<F: SKFloat> {
    type Output;
    type Error: From<SKError>;
    fn transform<'a, X>(&self, features: X) -> Result<Self::Output, Self::Error>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>;
}
}

Three details carry the design and are easy to miss in a skim:

  • fit(&self, ...) — not &mut self. An estimator is immutable configuration; you may hand the same SKStandardScaler to two threads fitting two datasets concurrently. All mutation lifetime lives in the returned Model.
  • Self::Model is a distinct type. Do not reuse the estimator struct as its own model. The model holds fitted values (mean, variance, coefficients…), implements the operation traits, and is what gets serialized for export.
  • Everything enters through TryInto<SKDataView> / TryInto<SKTargetView>. The caller passes zero-copy inputs; the fallible conversion seam (Error = SKError, the central taxonomy: ShapeMismatch, UnsupportedRepresentation, …) is where validation lives. Never accept raw Array2 by value.

3.2 The model’s predictive side

#![allow(unused)]
fn main() {
// Implemented on the MODEL, never on the estimator.
pub trait SKRegressorPredictor<F: SKFloat> {
    type Error: From<SKError>;
    fn predict<'a, X>(&self, features: X) -> Result<ndarray::Array1<F>, Self::Error>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>;
}

pub trait SKClassifierPredictor<F: SKFloat> {
    type Error: From<SKError>;
    fn predict_labels<'a, X>(&self, features: X) -> Result<ndarray::Array1<i64>, Self::Error>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>;
    fn predict_probabilities<'a, X>(&self, features: X) -> Result<ndarray::Array2<F>, Self::Error>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>;
}
}

Note predict returns Array1<F> in the model scalar — an f32 model predicts f32 with no f64 detour — while classifier labels are scalar-independent i64 indices (SKTargetView::Continuous is likewise generic over F).


4. The builder

The builder is the only public constructor path. Direct constructors are private; a new estimator validates every hyperparameter exactly once, in build().

#![allow(unused)]
fn main() {
use sciencekit_common::builders::{SKBuilder, SKBuilderState};
use sciencekit_common::builders::sk_validate_hyperparameter;
use sciencekit_common::SKExecutionMode;

pub struct SKStandardScaler {
    plan: SKBuilderState,
    with_mean: bool,
    with_std: bool,
}

impl SKStandardScaler {
    pub fn new() -> SKStandardScalerBuilder {
        SKStandardScalerBuilder::new()
    }
    // ... the estimator also exposes:
    pub fn execution_intent(&self) -> SKExecutionMode { self.plan.execution_intent() }
    pub fn resolve_plan(
        &self, context: &SKExecutionContext,
    ) -> Result<SKExecutionPlan, SKError> { self.plan.resolve_plan(context) }
}

pub struct SKStandardScalerBuilder {
    state: SKBuilderState,     // holds execution_intent, defaults to Automatic
    with_mean: bool,
    with_std: bool,
}

impl SKStandardScalerBuilder {
    pub(crate) fn new() -> Self {
        Self { state: SKBuilderState::new(), with_mean: true, with_std: true }
    }

    pub fn with_mean(mut self, value: bool) -> Self { self.with_mean = value; self }
    pub fn with_std(mut self, value: bool) -> Self { self.with_std = value; self }

    pub fn execution_mode<E>(mut self, mode: E) -> Self
    where E: TryInto<SKExecutionMode> {
        self.state.execution_mode(mode);
        self
    }
}

impl SKBuilder<SKStandardScaler> for SKStandardScalerBuilder {
    fn execution_mode<E>(&mut self, mode: E) -> &mut Self
    where E: TryInto<SKExecutionMode> {
        self.state.execution_mode(mode);
        self
    }
    fn build(self) -> Result<SKStandardScaler, SKError> {
        // validation here — e.g. with_mean=false && with_std=false leaves identity.
        Ok(SKStandardScaler { plan: self.state, with_mean: self.with_mean, with_std: self.with_std })
    }
}
}

The obligations encoded:

  • execution_mode(SKExecutionMode::Automatic) is the default resolved intent; the user may override, and the trait’s &mut self form coexists with the by-value chaining form — both funnel into the same SKBuilderState.
  • build() never panics; invalid states return SKError::InvalidHyperparameter via sk_validate_hyperparameter(name, valid, reason).

4.1 Why the intent is resolved at operation time, not at build time

A constant that tempts every newcomer: resolve the plan eagerly in build() and store it. Do not. The estimator is reusable: the same fitted model may be asked to transform a 100-row slice in the morning and drive the usual 50 GB job in the afternoon — and available_memory_bytes, the dominant variable of the resolution rule, is free memory right now. Resolution happens per-operation, inside fit/transform/predict, from a fresh SKExecutionContext.


5. Planning: from intent to executable plan

Inside every operation you do the same four lines, and then parametrize everything by plan.parallelism and guard everything by plan.mode:

#![allow(unused)]
fn main() {
use sciencekit_common::execution::{SKExecutionContext, sk_resolve_execution_plan};
use sciencekit_common::observability::{SKOperationAttributes, SKOperationKind};
use sciencekit_math::kernels::SK_AXIS_SUM_GRAIN; // your dominant kernel's grain

fn standardize<F: SKFloat>(
    estimator: &SKStandardScaler,
    features: &ndarray::ArrayView2<F>,
) -> Result<ndarray::Array2<F>, SKError> {
    sk_run_operation(
        SKOperationAttributes {
            operation: SKOperationKind::Fit,
            rows: features.nrows(),
            columns: features.ncols(),
            execution_mode: estimator.execution_intent(),
            backend: SKBackendKind::Faer, // or the actual backend's kind()
        },
        || {
            let mut context = SKExecutionContext::real();
            context.dataset_size_bytes = features.len() as u64 * size_of::<F>() as u64;
            context.scalar_size_bytes = size_of::<F>() as u64;   // defaults are f64-sized; set it for f32 batches
            context.dataset_elements = Some(features.len() as u64);
            context.access_pattern = SKAccessPattern::Sequential;
            context.grain = SK_AXIS_SUM_GRAIN;          // the algorithm declares its grain
            let plan = sk_resolve_execution_plan(estimator.execution_intent(), &context)?;

            // dispatch on plan.mode / use plan.parallelism (see §6, §7)
            // ...
            unimplemented!()
        },
    )
}
}

What sk_resolve_execution_plan does with that (pure, deterministic — so your tests can assert it exactly):

$$\begin{aligned} \text{intent} = \text{Automatic}:&\ \ &\text{dataset_size_bytes} \le \text{available_memory_bytes} &&\to \text{InProcessSynchronous} \ &\text{else access_pattern RandomAccess} &&\to \text{OutOfCoreMemoryMapped} \ &\text{else Sequential} \mid \text{Iterative} &&\to \text{OutOfCoreStreaming} \[4pt] \text{parallelism} &= \min(\text{cores}, \lceil \text{unit_elements} / \text{grain} \rceil) \ \text{unit} &= \text{whole dataset (in-memory)} \mid \text{one batch (streaming, batch_size_hint)} \mid \infty \text{ (mapped)} \end{aligned}$$

Two compile-time facts your tests should lock in:

  • Automatic is a policy, not a prophecy: it never returns ExecutionModeIncompatible, and small data always lands in-memory (parallelism collapses to 1 when the unit is below one grain — the resolver will not hand out threads for a 5-element array). One caveat: when Automatic resolves to a streaming plan, the buffer guard still applies — an oversized batch_size_hint raises BatchBufferOversize, which is a data-shape error, not an intent error.
  • Declaring OutOfCoreStreaming with access_pattern = RandomAccess is a programming error caught before any data moves: SKError::ExecutionModeIncompatible.

5.1 Which access pattern should your algorithm declare?

PatternMeansChoose when
Sequentialone pass (or the state is order-independent) — most fit operationsyour state is a combiner updated once per element/batch
RandomAccessany element in O(1), possibly many timesnearest-neighbor bases, memory-mapped training sets
Iterativemultiple passes over the same datak-means, SGD over epochs, iterative solvers

The pattern is a property of the algorithm math, not a preference. SKStandardScaler is Sequential. SKSGDClassifier is Sequential per pass (it never needs a random row). SKKNeighborsClassifier is the textbook RandomAccess: its “training” is storing and its prediction needs any stored row at any time.


6. Regime 1 — in-memory, parallel kernels

InProcessSynchronous is the regime every algorithm supports: the whole array is resident, and the job is to throw plan.parallelism threads at it. You do not create threads and you do not write rayon code in the algorithm — the kernels do, taking a single parallelism: usize and branching internally:

#![allow(unused)]
fn main() {
use sciencekit_math::kernels::sk_axis_sum;

// axis 0 => per-column sums; parallel path uses per-chunk PARTIAL accumulators
// combined at the end (no thread ever writes to another thread's accumulator).
let per_column_sums = sk_axis_sum(&features.view(), 0, plan.parallelism);
}

The rules to internalize before writing your first kernel call:

  • Parallelism is paid for by the grain. Each kernel family carries a measured grain (SK_AXIS_SUM_GRAIN = 100_000 elements for reductions, 1M for elementwise transforms…) — the crossover point where splitting work pays for its own dispatch overhead. You inject your dominant kernel’s grain into the context; the resolver computes parallelism = min(cores, ceil(unit / grain)). The same number governs in-memory and streaming: the grain is a property of the kernel, not of the regime.
  • Partials, never shared accumulators. When you compute anything in parallel, each worker accumulates into its own partial vector; partials are combined once at the end. This is why the parallel column sum is deterministic-order-tolerant and race-free — and in the transformer chapter it is why $\Sigma$ and $\Sigma x^2$ partials compose into Welford cleanly.
  • Layout is a contract, not an accident. Pass &features.view() into kernels; when a copy may be needed for a blocked/backend path, sk_force_contiguous gives back a CowArray — borrow if already contiguous, own only if strided.

7. Regime 2 — out-of-core streaming, the generic driver

The mental model first. Streaming is not “a smaller fit called repeatedly by the user”. It is the same fit, running over an SKLazySource that yields owned SKDataBatches, with your algorithm’s state updated per batch inside the driver’s prefetch pipeline. You write one closure; the driver owns buffering, an I/O producer thread, ordering, errors and the final-batch flag.

#![allow(unused)]
fn main() {

struct StreamingMomentsState {
    count: u64,
    count_f: f64,          // Welford accumulators — see the transformer chapter
    mean: ndarray::Array1<f64>,
    m2: ndarray::Array1<f64>,
}

fn fit_streaming<F: SKFloat>(
    source: &mut impl SKLazySource<F>,
    plan: &SKExecutionPlan,
) -> Result<StreamingMomentsState, SKError> {
    let mut state = StreamingMomentsState { count: 0, count_f: 0.0,
        mean: ndarray::Array1::zeros(0), m2: ndarray::Array1::zeros(0) };

    sk_run_streaming_driver(source, &mut state, |batch, parallelism, state| {
        // ← THE "partial fit": one batch, one update of the combinable state.
        update_moments(batch.view().as_dense().expect("dense batch"), parallelism, state);
        SKStreamDecision::Continue
    }, plan)?;

    Ok(state)
}
}

Mechanics you inherit for free by using the driver (and must never re-implement by hand — that is a whole second book of subtle concurrency):

  • a dedicated I/O producer thread reads ahead through a bounded buffer sized by plan.buffer_depth (double buffering = 1), so disk and CPU overlap;
  • batches arrive in source order, owned (SKDataBatch owns its Array2<F> precisely so it can be handed across the producer/consumer boundary);
  • SKDataBatch::is_final() marks the last batch; position() gives zero-based order;
  • a read error mid-stream surfaces as SKError with all earlier batches’ effects preserved in your state — error handling is monotonic: never a partial model without an error, and never an error that discards the caller’s ability to see it;
  • SKStreamDecision::Stop halts the pipeline early while keeping the current batch’s effect.

The same state produced by the stream must be the same kind of state the in-memory path produces. For a scaler that is trivial; for LinearRegression it is exactly why Chapter 4 accumulates a Gram matrix per batch; for SGD Chapter 3 of this part never had to re-formulate anything — its update is already the only formulation it has.

Batch sizing. The plan carries plan.batch_size (streaming only) and checks a buffer guard: $2 \times \text{batch_elements} \times \text{scalar_size} \le \text{available_memory_bytes}$, else SKError::BatchBufferOversize. Pass batch_size_hint in the context if your format has a natural batch (e.g. rows of a parquet row-group, cache-line multiples of a .npy memmap).


8. Regime 3 — memory-mapped random access (SKMappableSource)

The third regime exists because not all algorithms read data in order. k-NN needs “row arbitrary”; so do k-means over the same dataset used twice, and decision-tree splits over a base too big for RAM.

#![allow(unused)]
fn main() {
pub trait SKMappableSource<F> {
    type Error: From<SKError>;
    fn number_of_rows(&self) -> usize;
    fn row(&self, index: usize) -> Result<ndarray::ArrayView1<'_, F>, Self::Error>;
}
}

Design rule: implement SKMappableSource when the algorithm declares SKAccessPattern::RandomAccess and the data backing it lives on disk in a layout that gives O(1) rows (contiguous row-major, no header tricks). Then sk_resolve_execution_plan(Automatic)’s resolution sends huge datasets to OutOfCoreMemoryMapped where the union of memory and page cache serves the algorithm — no SKDataBatch copying, no prefetch pipeline, just rows handed out from where they already are.

The transform chapter will not need it; the neighbors chapter is built on it.


9. Observability: every public operation under one span

#![allow(unused)]
fn main() {
use sciencekit_common::observability::{sk_run_operation, SKOperationAttributes, SKOperationKind};

pub fn fit<F>(...) -> Result<Model, MyError> {
    sk_run_operation(
        SKOperationAttributes {
            operation: SKOperationKind::Fit,          // Fit · FitTransform · FitPredict · PartialFit · Transform · Predict · Score
            rows, columns,
            execution_mode, backend,
        },
        || { /* the real work */ },
    )
}
}

sk_run_operation opens a span carrying operation/rows/columns/mode/backend, times the closure and, if it errors, records the error — bounded enums only, never free-form strings. The streaming tip: each per-batch update is instrumented with SKOperationKind::PartialFit (k-means over $10^2$ batches, an SGD classifier with 100 → a streaming job becomes a legible sequence of partial steps rather than one opaque fit).


10. The routine, end to end

Assemble everything above into the routine you will now repeat. It is the same routine no matter the algorithm — only the math body changes:

TDD guarantee (mandatory, never skipped):
  1. Failing contract test FIRST         (cargo test → compile-error/fail; commit on the red)
  2. Smallest naive implementation        (passes; commit)
  3. Performance pass                     (grain, layout, partials; same tests still green;
                                           commit)
  4. Streaming/out-of-core pass           (same state, driver wiring; SAME tests, plus batch
                                           tests; commit)

Gates, before any push:
  cargo fmt --all --check && cargo clippy --workspace --all-targets && cargo test --workspace
  mdbook build docs   (documentation change accompanies every code change)

Acceptance, per PRD §8.7 — the four scenarios each estimator must survive:
  ✔ large and small datasets        (the same tests ask both shapes of data from the contract)
  ✔ under concurrency               (Send/Sync by design; parallel kernels; &self fit)
  ✔ model export & reload           (fit→serialize→deserialize→predict must equal)
  ✔ metrics computed                (scorer traits give you score() for free)

Numbers to keep in mind when you pick the second pass (the ones teams constantly trip on):

  • Do not skip the performance stage. The naive version exists to make the next test meaningful: the parallel/Welford/laid-out version must produce the same answers to 1e-15 (see the transformer chapter’s cancellation walk-through), and the grain constants in sciencekit_math::kernels::grain are measured, not folklore — reuse them.
  • Automatic is the golden default because resolution is pure and total — the plan is a function of (intent, context) with no world effects, which means every algorithm’s dispatch itself is unit-testable without disks or clusters. Keep it that way: never read the clock, the file system, or the thread pool inside a decision path.
  • The model type is the export boundary. PRD §8.7 acceptance includes export; design the model as a plain, default-repr struct of fitted values + the metadata needed to rebuild, and serialization is nearly a recording note rather than a new design.

11. Checklist — before you open the PR

  • Folder module; mod.rs is semantics-free; tests are companions, not in tests/
  • Naming: no abbreviations; SK/sk_ prefixes applied per §3.4; crate name intact
  • Builder-only construction; execution_mode default Automatic; validation in build()
  • Zero-copy inputs via TryInto<SKDataView>; errors from the central taxonomy
  • Estimator is immutable (&self methods), model is distinct type + implements its verbs
  • Execution context declares grain and access_pattern; plan resolved per operation
  • In-memory path goes through measured-grain kernels with plan.parallelism
  • Streaming path (when the algorithm afford sequential batches): same state + driver; memory-mapped path (if RandomAccess): SKMappableSource
  • Every entry point wrapped in sk_run_operation with bounded attributes
  • Red→green→refactor committed per task; OpenSpec tasks.md - [x] kept in lockstep
  • fmt/clippy/test/mdbook build all green locally
  • Documentation branch: Development Explained chapter (new) + tutorials walk-through
  • Independent review: spec met, then the PR references the ADR issue with closing keywords

You now know everything that is the same across algorithms. The next four chapters are what is different — the math, the numerics, and the traps of each family.

Tutorials

This part is the hands-on textbook for the library. Where Development Explained walks through what was already built and why, this part teaches you how to build the next thing — by hand, with no agent, using only the book as your companion.

Who this is for

You already know Rust (ownership, generics, traits, iterators — where a Rust language concept appears, we reference the Development Explained book instead of re-teaching it). You do not need to know:

  • how sciencekit wires its internals (we show every wire),
  • the numerical-computing theory behind the algorithms (we teach each one from zero),
  • how parallel machines think about work (we teach grain, partials and prefetch pipelines in context, the first time an algorithm needs them).

The one idea to hold

Every estimator in sciencekit follows the same skeleton:

flowchart TD
  accTitle: The estimator lifecycle taught by the tutorials
  accDescr: A builder creates a stateless estimator, whose fit produces a fitted model. One resolved plan selects in-memory kernels, a streaming driver or a memory-mapped source. All regimes feed the transform and predict operations.
    classDef buildNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
    classDef fitNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
    classDef regNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
    classDef outNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px

    B["Builder::new()<br>hyperparameters · execution_mode(…)<br>(default: Automatic)"]:::buildNode
    B -->|"build()"| E["Estimator<br>(stateless config, &self everywhere)"]:::buildNode
    E -->|"fit(features[, targets])"| M["Model<br>(fitted, shareable, exportable object)"]:::fitNode
    M --> P{"one resolved plan<br>decides the regime"}:::regNode
    P -->|"InProcessSynchronous"| A["parallel kernels, whole array,<br>plan.parallelism threads"]:::regNode
    P -->|"OutOfCoreStreaming"| S["sk_run_streaming_driver:<br>owned SKDataBatch,<br>update(batch, parallelism, &mut State)"]:::regNode
    P -->|"OutOfCoreMemoryMapped"| Mm["SKMappableSource:<br>O(1) random rows,<br>no materialization"]:::regNode
    A --> O["transform / predict verbs"]:::outNode
    S --> O
    Mm --> O

The key that makes all of this cohere: the algorithm is first designed as a function of a combinable state ($\Sigma$ sums, Welford moments, a gradient accumulator, a set of stored neighbor vectors). Once the state exists, the in-memory path is “the streaming path with one batch that happens to hold everything” — the two regimes share the same math, and the user never picks a code path, only a SKExecutionMode — usually the default Automatic, which resolves it from dataset size, free memory and access pattern.

Chapter map

ChapterWhat you buildThe lesson it carries
How to add an Algorithm(no algorithm — the boiler plate)file layout, naming, builder, contracts, planning, three regimes, TDD, gates, acceptance
Adding a TransformerSKStandardScaler, SKRobustScalerreductions and partials; Welford; quantiles are hard in a stream
Adding a Linear ModelSKLinearRegressiondense linear algebra through the backend; SVD vs normal equations; Gram accumulation when streaming
Adding a Streaming ModelSKSGDClassifier, SKSGDRegressorgradient descent from zero; the driver’s update; PartialFit spans; in-memory = degenerate batch
Adding a Neighbors ModelSKKNeighborsClassifier, SKKNeighborsRegressorthe honest exception: random access, memory-mapped bases, why no sequential stream

Each case-study chapter follows the same internal contract:

  1. Story & decisions — what problem, which roads taken and not taken.
  2. Theory from zero — numerics with sources; pros/cons; where the obvious solution quietly fails.
  3. A state that combines — the mathematical core both regimes share.
  4. Full reference code — real, final-form files (folder module, builder, estimator, model, tests).
  5. Both regimes side by side — Mermaid data flow and when to prefer each.
  6. Acceptance walk-through — PRD §8.7 mapped to the tests you just wrote.
  7. Study sources.

Prerequisites check

Before starting, make sure you can run the CI gates locally — they are part of every task:

$ cargo fmt --all --check
$ cargo clippy --workspace --all-targets
$ cargo test --workspace

and build the book you are reading:

$ mdbook build docs

Everything else — grain constants, error taxonomy, planning rules, backend selection — is introduced where the algorithms first need it.

Adding a Transformer — SKStandardScaler and SKRobustScaler

Pre-read: How to add an Algorithm — this chapter quotes its skeleton (folder layout §2, builder §4, planning §5, streaming driver §7) without repeating it.

A transformer is the smallest complete algorithm: it has fit, it has transform, it has no targets, and it has a numerical half-life — one where the naive solution is still the answer printed in most textbooks and, precisely for that reason, is the wrong answer to ship first.

Everything in one place: after this chapter you can write a transformer end-to-end by hand.

flowchart LR
  accTitle: The standard-scaler tutorial pipeline
  accDescr: The builder produces an immutable estimator. Fit resolves a plan that selects in-memory parallel reductions or streaming Welford updates. Both feed the fitted standard-scaler model, whose transform emits scaled features.
    classDef planNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
    classDef computeNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
    classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
    classDef modelNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px

    B["SKStandardScalerBuilder<br>.execution_mode(...)"]:::planNode --> E["SKStandardScaler<br>(immutable estimator)"]:::planNode
    E -->|fit x| R{"sk_resolve_execution_plan<br>(Automatic)"}:::planNode
    R -->|fits in RAM| M["in-memory regime<br>sk_axis_sum partials<br>parallelism threads"]:::computeNode
    R -->|larger than RAM| S["streaming regime<br>sk_run_streaming_driver<br>Welford update per batch"]:::streamNode
    M --> St["SKStandardScalerModel<br>μ, σ² (fitted)"]:::modelNode
    S --> St
    St -->|transform| T["sk_scaled features"]:::modelNode

1. Story & decisions

The problem. Your features live on different scales — income in the tens of thousands, age in tens. Any distance- or gradient-based model becomes a physics experiment where one feature’s magnitude is the whole of gravity. Standardization removes feature scale as a variable: subtract the mean, divide by the standard deviation. Robust standardization does the same with order statistics (median, inter-quartile range) instead of moments, because a single bad sensor reading can drag a mean half a column away.

DecisionChosenRoads not taken, and why
Population (÷N) variance, like eager scikit-learn’s default?Yes for the fit statisticDegrees-of-freedom correction (÷N−1) is a sampling choice, not a preprocessing one; it is requested at scoring time, not baked into the transformer.
One parallel reduction for $\Sigma$ and $\Sigma x^2$?No — Welford both regimes$\Sigma x^2$ has ~half the significant digits of $x$; subtracting means from it amplifies rounding — the catastrophic cancellation walk-through is §3. The naive two-array reduction is exactly the “obvious solution that fails”, §2.
Compute variance in the same pass as mean when streaming?Yes — Welford carries (count, mean, M2)A second pass (means first, then squares) requires re-reading the data — worthless when the raison d’être of the streaming path is not having the data twice.
transform after streaming fit must be exact?Bit-near-identical to in-memoryGuaranteed by testing both regimes against the same fixtures (walk-through §6).
RobustScaler’s medians under streamingTwo-pass honest approach: streaming moments for with_centering=False choice, exact quantiles via a resumable, batch-buffered exact pass (P² approximation discussed, not shipped)Exact online quantiles require nontrivial estimator structures (P² algorithm, Jain & Chlamtac 1985); approximating with simpler checkpoints silently violates the transformer’s deterministic contract. See §5.
Support with_mean=False/with_std=False?Yes, validation prevents both-false identity transformersSilently letting the estimator degrade to identity gives a UX cliff: a pipeline that stopped transforming for no surfaced reason.

The contract shapes the math

SKFeatureTransformer::Output must be statically known — that is the compile-time pipeline hook. For both scalers the output is a materialized owned Array2<F> on transform (zero-copy input goes in, owned result comes out; in-place variants are an explicit future addition, see §5).


2. Theory from zero — moments, and why the obvious solution fails

2.1 The mean, and what “sum” quietly means

The mean of column $j$ is $\mu_j = \frac{1}{N}\sum_i x_{ij}$. The variance is $\sigma_j^2 = \frac{1}{N}\sum_i (x_{ij} - \mu_j)^2$. Both look like one-liners. They are one-liners in exact arithmetic — and the whole content of this chapter lives in what floating-point arithmetic does to the naive forms.

Parallelism. Sums are associatively commutative in exact math and not quite in floating point — which is why column sums are computed as per-chunk partials and combined once (sk_axis_sum, axis 0). Every parallel worker owns a partial; the combine step happens once. Mutating a shared accumulator from several threads is a data race — and, even if you patched the race with an atomic, you would get a non-deterministic summation order that changes run to run (deviating between small and large data, the exact thing the acceptance §8.7 “little and lots” tests want to distinguish: with little data, the deployment-time parallelism is 1; with lots, the parallel path must agree to machine precision).

2.2 Catastrophic cancellation — the three-line formula that lies

The naive algebraic identity for variance is:

$$\sigma^2 = \frac{\Sigma x^2}{N} - \mu^2$$

Pro: one accumulation, reads the array once, easy to parallelize ($\Sigma$ and $\Sigma x^2$ partials in the same pass). Con: for data whose mean is huge compared to its spread — a very common shape in financial data, sensor data, any data conditioned by adding a constant — you subtract two numbers that are nearly equal, each with ~16 significant decimal digits of a 64-bit float, and the difference carries only the digits the two big numbers did not have in common.

A classic reminder (need to show scale, not precision):

$$\begin{aligned} \sigma^2 &= \frac{\Sigma x^2}{N} - \mu^2 && \text{where each summand carries 53 bits} \ \left\lvert \frac{\Sigma x^2}{N} - \mu^2 \right\rvert &\ll \frac{\Sigma x^2}{N} && \text{the information destroyed has exactly the parts you needed} \end{aligned}$$

with a proviso: when the spread is ~1e-8 or less of the mean, the naive identity is not “slightly imprecise” — it returns negative numbers that square to imaginary standard deviations (a real bug class reported repeatedly in scikit-learn; see the “welford-negative-variance” folklore and the RunningStats discussions).

2.3 Welford’s online algorithm — the combining trick

The fix (Welford 1962; the multi-participant combiner is Chan, Golub & LeVeque 1983, “Algorithms for computing the sample variance: analysis and recommendations”, The American Statistician) re-represents the state as (count, mean, M2) rather than $(n, \Sigma x, \Sigma x^2)$:

$$\begin{aligned} W(x;\ \text{count}, \text{mean}, M_2):& \ \text{count} &= \text{count} + 1 \ \text{delta} &= x - \text{mean} \ \text{mean} &= \text{mean} + \frac{\text{delta}}{\text{count}} && \text{new mean} = \text{old mean} + \frac{x - \text{old mean}}{n} \ M_2 &= M_2 + \text{delta} \cdot (x - \text{mean}) && M_2 = \sum_i (x_i - \text{current_mean})^2 \ \text{output: variance} &= \frac{M_2}{\text{count}} \end{aligned}$$

Every intermediate is a small residual — the possibly-conditioned subtraction is (x − mean), not (big − big); the cancellation is structured, not pathological.

And when the participants are batches (streaming), the form composes: two partial states (count_a, mean_a, M2_a), (count_b, mean_b, M2_b) combine with

$$\begin{aligned} \text{delta} &= \text{mean}_b - \text{mean}_a \ \text{count}_c &= \text{count}_a + \text{count}_b \ \text{mean}_c &= \text{mean}a + \text{delta} \cdot \frac{\text{count}b}{\text{count}c} \ M{2,c} &= M{2,a} + M{2,b} + \text{delta}^2 \cdot \frac{\text{count}_a \cdot \text{count}_b}{\text{count}_c} \end{aligned}$$

That is the whole algorithm: for the streaming path the “update per batch” is exactly the above with batch=(count_b, mean_b, M2_b) — each batch collapsed to its OWN Welford state (using the parallel-partials trick within the batch), then combined with the running state. One formulation, two regimes; that is the design point the anchor chapter promised.

Sources to learn this properly:

  • Donald Knuth, TAOCP vol. 2, §4.2.2 — where most people first meet Welford (as exercise: hardly the bibliographic patient)
  • Chan, Golub, LeVeque (1983), Am. Stat. — the analysis that says why it is stable
  • Welford’s original note: Technometrics 4:3 (1962), “A note on a method for calculating corrected sums of squares and products”

3. The combinable state

#![allow(unused)]
fn main() {
// crates/sciencekit_preprocessing/src/standard_scaler/core_implementation.rs
use sciencekit_common::SKFloat;
use sciencekit_math::kernels::sk_axis_sum;

/// A combinatorial object: in-memory partials and streaming batches
/// both arrive as these, and both reduce by the same merge.
#[derive(Debug, Clone, Default)]
pub struct SKMoments {
    pub count: u64,
    pub mean: ndarray::Array1<f64>,
    pub m2: ndarray::Array1<f64>,   // Σ (x − μ)² accumulated around the current mean
}

impl SKMoments {
    /// Pull one *chunk of rows* into the state. `parallelism` comes from the plan:
    /// the chunk's column sums are the parallel partials of `sk_axis_sum`.
    pub fn absorb_chunks<F: SKFloat>(
        &mut self,
        chunks: &ndarray::Array2<F>,
        parallelism: usize,
    ) {
        // ONE pass, no Σx² anywhere
        let chunk_rows = chunks.nrows();
        for row in chunks.rows() {
            let row_f64: ndarray::Array1<f64> = row
                .iter()
                .map(|v| v.to_f64().unwrap_or(0.0))
                .collect();
            // Welford single-element update against the CURRENT mean
            self.count += 1;
            // (Chosen for the parallel column-mean first — the streaming variant below
            //  does the whole-batch combine.)
        }
        // In practice, this inner piece merges the batch-level Welford done by
        // `absorb_batch` (below) so both regimes collapse to one combiner.
    }
}
}

The point of showing the will-not-compile version first is pedagogical: the naive habit is to reach for “two parallel sums”. Do not design the first version that way. The one combinable object you write in practice is:

#![allow(unused)]
fn main() {
impl SKMoments {
    /// parallel-friendly: absorb a whole batch by aggregating the batch's own Welford state
    /// first (so parallel partials cannot race), then COMBINING into the running state.
    pub fn absorb_batch<F: SKFloat>(
        &mut self,
        batch: &ndarray::ArrayView2<F>,
        parallelism: usize,
    ) {
        let batch_size = batch.nrows() as u64;
        if batch_size == 0 { return; }
        let per_batch = SKMoments::welford_of_batch(batch, parallelism);
        self.combine(per_batch);
    }

    fn combine(&mut self, other: SKMoments) {
        // The running state starts empty (`SKMoments::default()` carries
        // zero-length vectors): adopting the first partial outright avoids
        // subtracting mismatched shapes on the very first merge.
        if self.count == 0 { *self = other; return; }
        if other.count == 0 { return; }
        let total = self.count + other.count;
        let delta_w: ndarray::Array1<f64> = &other.mean - &self.mean;
        let running_weight = self.count as f64;
        let borrowed_weight = other.count as f64;
        let total_f = total as f64;
        self.mean = &self.mean + &delta_w.mapv(|d| d * borrowed_weight / total_f);
        let other_m2_delta: ndarray::Array1<f64> = delta_w.mapv(|d| d * d);
        self.m2 = &self.m2 + &other.m2
            + other_m2_delta.mapv(|d| d * (running_weight * borrowed_weight / total_f));
        self.count = total;
    }

    fn welford_of_batch<F: SKFloat>(
        batch: &ndarray::ArrayView2<F>,
        parallelism: usize,
    ) -> SKMoments {
        // The batch itself is reduced via per-chunk partial Welford states
        // (sk_axis_sum-shaped: chunk -> own state -> combine), so parallelism
        // never writes the same accumulator twice.
        let (rows, cols) = batch.dim();
        if rows == 0 { return SKMoments::default(); }
        let chunk = rows.div_ceil(parallelism.max(1));
        let partials: Vec<SKMoments> = batch
            .axis_chunks_iter(ndarray::Axis(0), chunk)
            .into_par_iter()
            .map(|piece| {
                let mut state = SKMoments {
                    count: 0,
                    mean: ndarray::Array1::zeros(cols),
                    m2: ndarray::Array1::zeros(cols),
                };
                for row in piece.rows() {
                    // Single-element Welford update, one row at a time: each
                    // row is ONE observation, so the shared observation counter
                    // advances once per row while every column updates its own
                    // (mean, m2) pair with that same counter value.
                    state.count += 1;
                    let count_as_float = state.count as f64;
                    for (mean, m2, value) in itertools::izip!(&mut state.mean, &mut state.m2, row.iter()) {
                        let next = value.to_f64().unwrap_or(0.0);
                        let delta = next - *mean;
                        *mean += delta / count_as_float;
                        *m2 += delta * (next - *mean);
                    }
                    // Parallel safety comes from the outer split: each rayon
                    // worker owns its private `state`; partials merge once via
                    // `combine` below, so no two threads share an accumulator.
                }
                state
            })
            .collect();
        let mut whole = SKMoments::default();
        for partial in partials { whole.combine(partial); }
        whole
    }
}
}

One caveat that keeps this honest: the exact Welford row-deceleration must be generic over both fact layouts, f32 and f64; state carries f64 internally always — variance accumulated in f32 $\Sigma x^2$-adjacent forms collapses exactly in the case Welford exists to prevent. This is a deliberate micro-decision: mean/variance at f32 costs you the 1e-7 precision the rest of the pipeline relies on. The features stay F; the statistics are f64 unconditionally.


4. Both regimes — the rest of the crown code

#![allow(unused)]
fn main() {
// in-memory path: one batch is the whole array; the driver is unnecessary.
impl SKUnsupervisedFit<F> for SKStandardScaler {
    type Model = SKStandardScalerModel;
    type Error = SKError;

    fn fit<'a, X>(&self, features: X) -> Result<Self::Model, Self::Error>
    where X: TryInto<SKDataView<'a, F>, Error = SKError> {
        let view = features.try_into()?.as_dense()?; // reject sparse up front
        sk_run_operation(
            SKOperationAttributes {
                operation: SKOperationKind::Fit,
                rows: view.nrows(),
                columns: view.ncols(),
                execution_mode: self.execution_intent(),
                backend: SKBackendKind::Faer,
            },
            || {
                let mut context = SKExecutionContext::real();
                context.dataset_size_bytes = view.len() as u64 * size_of::<F>() as u64;
                context.dataset_elements = Some(view.len() as u64);
                context.access_pattern = SKAccessPattern::Sequential;
                context.grain = SK_AXIS_SUM_GRAIN;
                let plan = sk_resolve_execution_plan(self.execution_intent(), &context)?;

                let mut state = SKMoments::default();
                state.absorb_batch(&view, plan.parallelism);
                Ok(SKStandardScalerModel::from_moments(state, self))
            },
        )
    }
}
}

and the streaming twin — note that only the plumbing changes:

#![allow(unused)]
fn main() {
impl SKStandardScaler {
    pub fn fit_streaming_source<S: SKLazySource<F> + Send>(
        &self,
        source: &mut S,
        plan: &SKExecutionPlan,
    ) -> Result<SKStandardScalerModel, SKError> {
        let mut state = SKMoments::default();
        sk_run_streaming_driver(source, &mut state, |batch, parallelism, state| {
            sk_run_operation(
                SKOperationAttributes {
                    operation: SKOperationKind::PartialFit,
                    rows: batch.number_of_rows(), columns: batch.number_of_columns(),
                    execution_mode: self.execution_intent(),
                    backend: SKBackendKind::Faer,
                },
                || { state.absorb_batch(&batch.view().as_dense().expect("dense batch"), parallelism); }
            ).map_err(|_| SKError::Io(std::io::Error::new(std::io::ErrorKind::Other, "batch update failed")))?;
            SKStreamDecision::Continue
        }, plan)?;
        Ok(SKStandardScalerModel::from_moments(state, self))
    }
}
}

The model — spelled out once, because it is the object the “smallest complete algorithm” must finish with (per-column fitted statistics as f64, plus the construction flags, which transform needs to know what the caller asked for):

#![allow(unused)]
fn main() {
pub struct SKStandardScalerModel {
    means: ndarray::Array1<f64>,         // per column; 0.0 where with_mean == false
    scales: ndarray::Array1<f64>,        // 1/σ per column; 1.0 where with_std is false
}

impl SKStandardScalerModel {
    pub(crate) fn from_moments(
        moments: SKMoments,
        options: &SKStandardScaler,      // with_mean / with_std flags
    ) -> Self {
        // Population variance (÷N), matching scikit-learn's default.
        assert!(moments.count > 0, "cannot fit on zero rows — reject empty input in fit()");
        let variance = &moments.m2 / moments.count as f64;
        // `scales` stores the MULTIPLICATIVE factor 1/σ: transform centers
        // then multiplies by it (never divides — division by a tiny σ
        // amplifies rounding; multiplication by a precomputed reciprocal is
        // both faster and the convention `sk_scale_in_place` expects).
        // Columns the caller disabled resolve to identities here, so
        // `columns()` below can hand `transform` ready-to-use triples.
        let scales = variance.mapv(|v| if options.with_std { 1.0 / v.sqrt() } else { 1.0 });
        let means = if options.with_mean { moments.mean } else {
            ndarray::Array1::zeros(moments.mean.len())
        };
        Self { means, scales }
    }
    /// (mean, scale) per column; the flags the caller disabled resolve to identities
    pub fn columns(&self) -> Vec<(usize, f64, f64)> {
        /* zip columns with (0.0, 1.0) wherever the construction flags disabled the step */
    }
}
}

transform (§ below) is a pure flat map — in the model, not the estimator:

#![allow(unused)]
fn main() {
impl<F: SKFloat> SKFeatureTransformer<F> for SKStandardScalerModel {
    type Output = ndarray::Array2<F>;
    type Error = SKError;

    fn transform<'a, X>(&self, features: X) -> Result<Self::Output, Self::Error>
    where X: TryInto<SKDataView<'a, F>, Error = SKError> {
        let view = features.try_into()?.as_dense()?;
        let mut out = view.to_owned();
        for (column_index, mean, scale) in self.columns().into_iter() {
            // `scale` is the precomputed reciprocal 1/σ (or 1.0 where the
            // flags disable scaling): center, then MULTIPLY — never divide.
            let mut column = out.column_mut(column_index);
            for value in column.iter_mut() {
                let centered = value.to_f64().unwrap_or(0.0) - mean;
                *value = F::from_f64(centered * scale).unwrap_or(F::zero());
            }
        }
        Ok(out)
    }
}
}

(prose in real code would use sciencekit_math::kernels::sk_scale_in_place per column with the plan parallelism for the design; here it is condensed to fit prose format — the chapter’s walk-through in the tests applies the actual kernel.)


5. SKRobustScaler — what breaks when “mean” becomes “median”

The same skeleton with one state change and one honest confession.

The same. The estimator/model split, the builder, the zero-copy entry, the plan wiring, SKFeatureTransformer on the model, the streaming driver. Nothing changes structurally.

The change. The state is not moments; it is three quantiles per column — median (50%) and the first/third quartile edges bounding the IQR:

$$\text{scaled} = \frac{x - \text{median}}{\mathrm{IQR}}$$

The honest conversation. An exact quantile is an order statistic: it needs all the values sorted. Streaming resistant numbers to a floating-point pipeline in one pass is a research-grade set of algorithms:

ApproachWhat it buysWhat you payShipped as?
Exact — read the batch window, sort the window (cached), then transformExact answers, deterministic, trivial to testRequires holding the entire distinct window (this is how scikit-learn does its RobustScaler.quantile_range) — a sorted copy of the full columnYes (in-memory, and “streaming” via a bounded-column windowed exact layer)
P² algorithm (Jain & Chlamtac 1985)$O(1)$ memory exact-for-many distributionsThis is a heuristic estimator with documented accuracy drift on adversarial/heavy-tail data; silently changing an exact transformer to an estimator breaks the “little and lots tests agree” acceptanceNot in ship — referenced as the extension
Greenwald-Khanna sketch$\varepsilon$-approximate quantiles with proof$\varepsilon$ is a choice; the transformer guarantee “deterministic for identical inputs” survives, but the exactness test would need a toleranceNot in ship

So the practical rule this chapter hands you: a robust transformer either fits its data or it says so. SKRobustScaler keeps the exact-window implementation and, in streaming mode, requires declaring a maximum window size as a hyperparameter (quantile_window_rows), rejecting construction otherwise — rather than degrading quietly to P². That is the streaming trade-off stated, not hidden: you must either touch the data twice (exact) or pick an estimator and document its error.

Sources for quantiles in a stream:

  • Jain & Chlamtac, “The P² algorithm for dynamic calculation of quantiles and histograms without storing observations”, CACM 28(10), 1985 — the famous O(1)-memory one-pass quantile estimator
  • Greenwald & Khanna, “Space-efficient online computation of quantile summaries”, SIGMOD 2001 — the $\varepsilon$-accurate predecessor of modern sketches
  • scikit-learn, sklearn.preprocessing.RobustScaler documentation — the behavior contract this chapter mirrors (quantile range default, centering/scaling flags)

6. The tests — your executable source of truth

The chapter pattern from the anchor: pick the tests that document the numerics, then the contract ones. Real fixtures as ndarray arrays:

#![allow(unused)]
fn main() {
// standard_scaler_tests.rs (companion; lives beside core_implementation.rs)
#[test]
fn sk_mean_variance_matches_closed_form() {
    // little dataset, f64 — in-memory parallel ps=1 
    let x = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
    let scaler = SKStandardScaler::new().build().unwrap();
    let model = scaler.fit(x.view()).unwrap();
    let (mu0, mu1) = (model.mean()[0], model.mean()[1]);
    assert!((mu0 - 3.0).abs() < 1e-12);
    // population variance ε N=3 form, 1 ULP tolerance against the textbook values
    assert!((model.variance()[0] - 8.0 / 3.0).abs() < 1e-14);
    assert!((model.variance()[1] - 8.0 / 3.0).abs() < 1e-14);
}

#[test]
fn welford_matches_two_pass_within_machine_epsilon() {
    // adversarial shape: huge mean, tiny spread — the naive Σx² identity FAILS here
    let base = 1.0e9_f64;
    let x: Vec<f64> = (0..1000).map(|i| base + (i as f64) * 1e-3).collect();
    let mu = x.iter().sum::<f64>() / x.len() as f64;
    let naive = x.iter().map(|v| v * v).sum::<f64>() / x.len() as f64 - mu * mu;
    // naive VIOLATES this assertion (negative variance): document it, never rely on it
    assert!(naive < 0.0);                          // the fixed trap, asserted on purpose 
    let scaler = SKStandardScaler::new().build().unwrap();
    let m = scaler.fit(ndarray::ArrayView2::from_shape((x.len(), 1), &x).unwrap()).unwrap();
    let two_pass_var = x.iter().map(|v| (v - mu) * (v - mu)).sum::<f64>() / 1000.0;
    assert!((m.variance()[0] - two_pass_var).abs() < two_pass_var * 1e-13);
    assert!(m.variance()[0] > 0.0, "welford never returns negative variance");
}

#[test]
fn streaming_matches_in_memory_on_thin_batches() { /* identical fixtures through
    fit_streaming, batched 3-rows-at-a-time; answers agree to 1e-14; the "is_final"
    flag tested by construction (driver guarantees terminal batch delivery) */ }

#[test]
fn concurrency_several_thread_model_transform_output_safe() { /* model is Sync: cloned references
    transformed on rayon, states all agree; represents acceptance "under concurrency" */ }
}

The tests are labeled with their pedagogical role: the first makes sure the math is right once, the second documents why naive variance is not correct here (the genuinely non-obvious transformation decision of this chapter), the third locks the dual-regime promise the PRD asks of every algorithm, and the fourth the concurrency acceptance.


7. Acceptance walk-through & study sources

The PRD §8.7 four-item acceptance, mapped:

Acceptance criterionTest (§6)
Lots and little datathe three-row fixture and the 1000-row adversarial fixture both show up across §6 tests
Under concurrency§6 fourth test — model is Sync, transform under rayon
Model exportmodel structs of fitted moments + flags (export chapter holds the convention)
Metricstransform quality shows up in the downstream chapters scoring (transformer is upstream of scorers)

Study sources for this chapter:

  • Chan, Golub, LeVeque (1983) — the combinating variance analysis (see §2.3’s cites)
  • Knuth, The Art of Computer Programming II, §4.2.2 — where $\Sigma x^2$ collapse is discussed
  • practical style blogs: John D. Cook, “Accurately computing running variance” (the modern favorite walk-through of the algorithm written for engineers)
  • scikit-learn: sklearn.preprocessing.StandardScaler and RobustScaler docs and their fit source — the semantics you are reimplementing and the exactness conventions you inherit
  • Press et al, Numerical Recipes §14.1 — moments and their pitfalls, the “interview answer” reference

Next chapter turns to the first supervised estimator — one where the whole question changes from “moment of a column” to “which vector of coefficients explains a target”.


Source providers (current API). The shipped fit_streaming takes a SKSourceProvider<F> (transformers) or SKSupervisedSourceProvider<F> (supervised models). Passing &mut source still compiles and takes one pass; wrap a factory in SKReopenableSource::new(|| ...) to let an iterative estimator run several epochs. See chapter 18.

Adding a Linear Model — SKLinearRegression

Pre-read: How to add an Algorithm (§5 planning, §7 streaming) and Adding a Transformer (the moments state that combines — keep it in mind; the state here is its first supervised cousin).

Linear regression looks like the easiest algorithm in the catalog and is the best teacher of the two most important numerical-preserving decisions in the whole library: which decomposition carries the solve, and what a streaming formulation of a dense linear system means — including the trade-off that makes it not just a “divided fit”.

1. Story & decisions

DecisionChosenRoads not taken — and the reason they are traps
SolverSVD least squares through the backend (lstsq = pseudoinverse path)Normal equations ($\operatorname{solve}(A^{\mathsf T}A, A^{\mathsf T}y)$) — the textbook one-liner — squares the condition number: $\kappa(A^{\mathsf T}A) = \kappa(A)^2$. For even moderately ill-conditioned real data this is the difference between 13 and 7 significant digits, and it silently produces wrong answers exactly where practitioners most need trust (correlated features). §2 walks the numbers.
Rank deficiencyKeep rank and singular_values from SKLeastSquaresSolution; thin support surfaced todaySilently computing with a rank-deficient matrix and returning a solution that claims “the” answer is a subtraction bug hidden in plain sight — SVD hands rank and singular values for free, so we surface them.
Intercept handlingDesign-matrix augmentation (prepend a column of ones) unless include_intercept is false — the PRD forbids
scikit-learn abbreviations, so include_intercept is the name that carries this chapterSolving for intercept separately via two means collapses rank prematurely on rank-deficient designs.
StreamingGram accumulation per batch: carry $A^{\mathsf T}A$ and $A^{\mathsf T}y$ (and row_count) in the stream state, and solve at the end — the same form the in-memory path never had to use — and the honest precision trade-off is stated.Two-pass streaming (means then squares) re-reads the data — the streaming mode exists precisely because we cannot.
DtypeF: SKFloat on features; targets arrive as f64 (SKTargetView::Continuous)Type application binds feature dtype; the model’s coefficients rise to the solve’s precision policy (f64 state, see §3).

Mermaid, both regimes at a glance:

flowchart TB
  accTitle: Linear-regression execution regimes in the tutorial
  accDescr: The execution plan chooses an in-memory SVD pseudoinverse solve or a streaming path that accumulates the normal-equation terms per batch and solves at stream end. Both paths produce the fitted linear-regression model used for prediction.
    classDef planNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
    classDef jacNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
    classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
    classDef modelNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px

    Q{"sk_resolve_execution_plan(Automatic)"}:::planNode
    Q -->|"fits in RAM"| X["A = [1‖X]<br>SVD → pinv(A)·y<br>lstsq via faer backend<br>rank + singular_values surfaced"]:::jacNode
    Q -->|"larger than RAM"| GR["per batch:<br>G := G + BᵀB<br>c := c + Bᵀyᵦ<br>row_count := row_count + batch.nrows()"]:::streamNode
    GR --> END["solve(G, c) at stream end<br>⚠ doubles condition number — stated trade-off"]:::jacNode
    X -->|predict| St["SKLinearRegressionModel<br>coefficients, intercept, rank"]:::modelNode

2. Theory from zero — least squares, and why one line hides a lie

The problem. We have rows $x_i \in \mathbb{R}^p$ and targets $y_i \in \mathbb{R}$. We want a vector of coefficients $\beta$ and a scalar intercept $b_0$ so that $x_i \cdot \beta + b_0 \approx y_i$. “Best” is least-squares: minimize $\sum_i (y_i - x_i \cdot \beta - b_0)^2$. With the augmented design matrix $A = [1 \mid X]$ (ones in the first column), that is one matrix equation: minimize $\lVert A\beta - y \rVert_2$.

Three roads to $\beta$, and the difference between them is not style — it is numerics:

Road 1 — Normal equations. Set the gradient of $\lVert A\beta - y \rVert_2^2$ to zero: $A^{\mathsf T}A\beta = A^{\mathsf T}y$. One triangular solve afterwards. The seductive part: $A^{\mathsf T}A$ is smaller than $A$ when rows $\gg$ columns (a $p \times p$ object instead of $n \times p$), which made it the pedagogical favorite for decades. The catch is measurable and unforgiving:

$\kappa(A^{\mathsf T}A) = \kappa(A)^2$ — the condition number squares.

Condition number is the ratio by which a linear solve can amplify input rounding; counting doubles means doubling the exponent of the loss: if $A$ has condition $10^7$, $A^{\mathsf T}A$ has $10^{14}$, and a 64-bit float has 16 digits — with $A^{\mathsf T}A$ the solve is allowed about two digits of trust at exactly the kind of gritty, correlated-feature datasets scikit-learn gets asked to process daily. And near-multicollinearity is not exotic: it is any pair of features that happen to co-move (age and years-of-experience; two sensors reading the same room).

Road 2 — QR. Orthogonalize $A$ ($A = QR$), then $\beta = R^{-1}Q^{\mathsf T}y$. $\kappa(QR) = \kappa(A)$ — the condition number is not squared, because the orthogonal factor is perfectly conditioned by construction. Stable, $O(np^2)$, the classic library workhorse.

Road 3 — SVD (the mvp of the “if it is important enough to be in the catalog, it must be stable enough to be in the intro” school). $A = U\Sigma V^{\mathsf T}$, so $\beta = \sum_{\sigma_i \neq 0} (u_i \cdot y / \sigma_i), v_i$ — the pseudoinverse solution. It costs more than QR and does something QR does not: it shows you the rank. Singular values near zero declare the exact features that make the problem degenerate, and the pseudoinverse path (pinv, $\text{rcond} = \varepsilon \cdot \max(m,n)$ in our backend) is exactly how a least-squares solve degrades gracefully when A is not full-rank, returning (i) the minimum-norm solution and (ii) the information that it did so.

The library’s decision: go through SVD — exposed as the backend’s lstsq, which returns solution, rank, singular_values and residual sums — with QR available for the day a profile demands a cheaper decomposition. One product line (feature blas-backend) selects ndarray-linalg vs faer; the algorithm never sees either (§5 anchor — backends are injectable, dispatch-level truths).

Sources to learn the numerics:

  • Golub & Van Loan, Matrix Computations — chapters on least squares, condition numbers, and pseudoinverse: the canonical reference
  • Trefethen & Bau, Numerical Linear Algebra — lectures 4–5 and 11–19 build SVD and least squares in a way a working engineer reads in an afternoon
  • Higham, Accuracy and Stability of Numerical Algorithms — if you want to prove the claims about normal equations; the chapter’s warnings are his §20

2.1 The streaming road

Streaming sits on the same skeleton — but the naive intuition here doubles down on the same hole. The tempting “solve least squares per batch and average the $\beta$” is almost never right: a weighted average hides how the covered rows distributed, and per-batch ranks do not compose.

What composes is the raw material of the normal equations — and that is the honest finding: the streaming regions re-shape the choice to Gram:

$$G := A^{\mathsf T}A \quad (p \times p,\ \text{symmetric}), \qquad c := A^{\mathsf T}y \quad (p,\ \text{right-hand side})$$

Each update adds a rank-$\lvert B \rvert$ contribution: for each batch $B$ ($\text{rows} \times p$),

$$G := G + B^{\mathsf T}B, \qquad c := c + B^{\mathsf T}y_{\text{batch}}$$

At the end, one solve of $G\beta = c$ obtains the coefficients. Exactly one extra fact dumps the price tag on the table: we computed $A^{\mathsf T}A$, so we are square-conditioning again. Thus the streaming trade-off reads, honestly:

in-memory SVDstreaming Gram
Significant digits at $\kappa(A)=10^7$~9 ($16 - \log_{10}\kappa$)~3–5 (the squared condition eats double)
Memory per stream step$O(np)$$O(p^2)$ — the entire point
Rank detection at stream endnativeonly via $G$’s own singular values ($\approx \sigma_i^2$ of $A$)

This is also why the streaming chapter of the optimizer family (next chapter) prefers SGD on day one: SGD never forms $A^{\mathsf T}A$, and its engine turns streaming from a constraint into the algorithm’s natural home.


3. The state — Gram, and what to carry besides

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/linear_regression/core_implementation.rs
#[derive(Debug, Clone, Default)]
pub struct SKGramState<const WITH_INTERCEPT: bool> {
    row_count: u64,
    gram: ndarray::Array2<f64>,  // AᵀA, (p + intercept) × (p + intercept)
    rhs: ndarray::Array1<f64>,   // Aᵀy,  (p + intercept)
}
}

Notes that carry design weight:

  • statistics once again accumulate in f64 unconditionally, like the moments state — when you accumulate $B^{\mathsf T}B$ products, $f32 \times f32 \to f32$ products cross 3 magnitudes of drift per row in adversarial inputs, and the covariates’ first digits are exactly what matters;
  • const WITH_INTERCEPT: bool carries through; a 1 turns into a prepended column that the gram absorb adds by chain rule, no separate pass needs reading the data;
  • row_count is needed for the residual computation only, not the solve.

4. The crown code, both regimes

#![allow(unused)]
fn main() {
impl<F: SKFloat> SKSupervisedFit<F> for SKLinearRegression {
    type Model = SKLinearRegressionModel;
    type Error = SKError;

    fn fit<'a, X, T>(&self, features: X, targets: T) -> Result<Self::Model, SKError>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>,
        T: TryInto<SKTargetView<'a>, Error = SKError>,
    {
        let view = features.try_into()?.as_dense()?;
        let target = targets.try_into()?.as_continuous()?.into_owned();

        sk_run_operation(
            SKOperationAttributes {
                operation: SKOperationKind::Fit,
                rows: view.nrows(),
                columns: view.ncols(),
                execution_mode: self.execution_intent(),
                backend: SKBackendKind::Faer,
            },
            || {
                // 1 · PLAN — same four lines as every algorithm
                let mut context = SKExecutionContext::real();
                context.dataset_size_bytes = view.len() as u64 * size_of::<F>() as u64;
                context.dataset_elements = Some(view.len() as u64);
                context.access_pattern = SKAccessPattern::Sequential;
                context.grain = SK_BINARY_COMBINE_GRAIN; // closeness-of-fit of the batch
                                                          // kernel; the GEMM grain is not yet
                                                          // calibrated — see the note below
                let plan = sk_resolve_execution_plan(self.execution_intent(), &context)?;

                // 2 · SOLVE — through the backend; vanilla-f64 design matrix
                let backend: Box<dyn SKMathBackend<F>> = Box::new(SKFaerBackend::new());
                let (design, target_f) = self.build_design(view, target);
                let least_squares = backend.lstsq(
                    design.view(),              // A, n × p (+1)
target.view().insert_axis(Axis(1)),  // y as n × 1
                )?;

                // 3 · SURFACE — rank and singulars are information, not noise
                SKLinearRegressionModel::from_least_squares(least_squares, self)
            },
        )
    }
}
}

and the streaming twin, which really is “the same data pages, a different sink”:

#![allow(unused)]
fn main() {
impl SKLinearRegression {
    pub fn fit_streaming_source<S, F>(&self, source: &mut S, plan: &SKExecutionPlan)
    -> Result<SKLinearRegressionModel, SKError>
    where
        F: SKFloat + Send,
        S: SKLazySource<F> + Send,
    {
        let mut state = SKGram::zeros(design_width);   // AᵀA & Aᵀy carry the regression
        sk_run_streaming_driver(source, &mut state, |batch, parallelism, state| {
            sk_run_operation(
                SKOperationAttributes {
                    operation: SKOperationKind::PartialFit,
                    rows: batch.number_of_rows(), columns: batch.number_of_columns(),
                    execution_mode: self.execution_intent(),
                    backend: SKBackendKind::Faer,
                },
                || state.absorb_batch(&batch.view().as_dense().expect("dense batch"), parallelism),
            )?;
            SKStreamDecision::Continue
        }, plan)?;

        // solve at stream end — rank checks ride on G's singular values (≈ σᵢ² of A)
        SKLinearRegressionModel::from_gram(state.solve_with_backend(...)?)
    }
}
}

predict on the model, honest minimum:

#![allow(unused)]
fn main() {
impl<F: SKFloat> SKRegressorPredictor<F> for SKLinearRegressionModel {
    type Error = SKError;
    fn predict<'a, X>(&self, features: X) -> Result<ndarray::Array1<F>, Self::Error>
    where X: TryInto<SKDataView<'a, F>, Error = SKError> {
        let view = features.try_into()?.as_dense()?;
        let (rows, _cols) = view.dim();
        let mut out = ndarray::Array1::zeros(rows);
        azip!((row in view.rows(), value in &mut out) {
            let mut acc = self.intercept_expectation();
            for (coefficient, feature) in self.coefficients.iter().zip(row) {
                acc += coefficient * (*x).get();
            }
            *value = acc;
        });
        Ok(out)
    }
}
}

5. Tests — the numerics-labeled set

#![allow(unused)]
fn main() {
// linear_regression_tests.rs
#[test]
fn recovers_exact_coefficients_to_epsilon() {
    // let x = array![[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [2.0, 1.0]];
    let true_coefficients = [3.0, -2.0];
    let y: Array1<f64> = x.map(|row| row.dot(&true_coefficients) + 0.5);
    let model = SKLinearRegression::new().build().unwrap().fit(x.view(), y.view()).unwrap();
    assert!((model.coefficients()[0] - 3.0).abs() < 1e-12);
    assert!((model.coefficients()[1] - (-2.0)).abs() < 1e-12);
    assert!((model.intercept() - 0.5).abs() < 1e-12);
}

#[test]
fn rank_deficiency_is_surfaced_not_hidden() {
    // feature columns linearly dependent — rank < p known ahead
    let x = array![[1.0, 2.0], [2.0, 4.0], [3.0, 6.0]];   // second column = 2 · first
    // SVD path: solution & rank reported; NOT silently mis-answered
    let sol = ...fit(x, y) — asserts `rank() == 1` and the minimum-norm answer is returned
}

#[test]
fn streaming_gram_matches_full_array() { /* the streaming state carries exactly
    gram + rhs + row_count; absorb_batch vs full-array G agree to 1e-13 (f64) */
}
}

(walk-through note to keep in the shipped pages: the third test exists to show how the streaming path’s accuracy gate — same fixtures in memory vs streaming — is how normal equations got kept streaming but with the §2 caveat printed as a test contract.)


6. Acceptance walk-through & sources

Acceptance criterion (PRD §8.7)Landing on the tests (§5)
Lots and little datafour-row exact fixture and the rank-deficient one — two shapes, one solver
Under concurrencymodel is Sync + Copy-safe; scoring under rayon exercised in the scorers chapter
Model exportcoefficients + intercept + design options serialize (export conventions live in the model chapter of the anchor)
MetricsSKSupervisedScorer (regressor) / SKLabelScorer (classifier) give score() free — the $R^2$ chapter exercises it against these models

Chapter sources:

  • Golub & Van Loan — §5.3–5.6 (least squares), §12 (SVD applications)
  • Trefethen & Bau — lectures 11–12 (SVD), 18–19 (conditioning)
  • Higham (2002) — §20 (the condition-number evidence for the normal-equations trap)
  • scikit-learn sklearn.linear_model.LinearRegression — the semantics you are matching, and one honest sanity-check: its least-squares dispatch is the SVD-based LAPACK gelsd family — exactly the pseudoinverse path this chapter’s backend code takes

Next: the family where streaming is not an adaptation but the home — gradient descent, state-as-accumulator, and why in-memory training is just “the batch of everything”.


Source providers (current API). The shipped fit_streaming takes a SKSourceProvider<F> (transformers) or SKSupervisedSourceProvider<F> (supervised models). Passing &mut source still compiles and takes one pass; wrap a factory in SKReopenableSource::new(|| ...) to let an iterative estimator run several epochs. See chapter 18.

Adding a Streaming Model — SKSGDClassifier and SKSGDRegressor

Pre-read: How to add an Algorithm (§5 planning, §7 streaming driver) and Adding a Linear Model (§2’s condition-number warning — this chapter is the escape route it promised).

This is the chapter where the library’s architecture stops being a compromise. Gradient descent is streaming-native: it consumes one sample (or one batch) at a time, updates an accumulator, and never asks “give me everything”. So the reference code here does not add streaming to a batch algorithm — it presents the estimator as a state machine whose in-memory fit is simply the degenerate case of one batch carrying everything, exactly the “one formulation, two regimes” principle from the Tutorials index.

Note (Wave 2.5). This tutorial was written as a design narrative before the implementation landed. The shipped code uses one update per sample, all four schedules, the full loss catalogue and a class table frozen at fit time; the code blocks below are illustrative of the architecture, not verbatim API. The authoritative, code-grounded account is chapter 17.

1. Story & decisions

DecisionChosenRoads not taken — and why they are wrong here specifically
Update granularity per stepone sample per update, wrapped in an epoch loopMini-batch updates would vectorize better, but they change the convergence theory and the schedule semantics; scikit-learn’s SGD is per-sample and the library keeps parity.
In-memory pathThe same per-sample update over the whole matrix, one epoch at a timeA separate closed-form/batch route would fork the semantics: two “fits” with answers that drift apart on ill-conditioned inputs — the exact problem the dual-regime principle exists to prevent.
Learning-rate schedulesall four shipped: constant, inverse_scaling, optimal (with $t_0$ estimated from the first batch) and adaptiveDropping optimal would break parity; shipping it with a fixed constant would hard-code a dataset-dependent number, so the constant is estimated and documented.
Lossesthe full catalogue: 5 classifier (hinge, log-loss, modified huber, squared hinge, perceptron) and 4 regressor (squared error, huber, epsilon-insensitive, squared epsilon-insensitive); penalties L2/L1/ElasticNet/NoneA reduced catalogue would not be scikit-learn-compatible; the substrate pays for the catalogue once and both estimators reuse it.
PartialFit spansEvery batch’s update wrapped in one SKOperationKind::PartialFit spanOne fit-wide span for a 10⁵-batch job reports nothing; per-batch spans form the legible trace that makes streaming jobs debuggable.
Classifier labelsa SKLabelTable frozen at fit time, first-occurrence orderRe-indexing per batch would silently move earlier classes; a class unseen at fit is rejected instead of growing the table, because a new column invalidates the trained coefficients.
flowchart TB
  accTitle: The stochastic-gradient-descent tutorial pipeline
  accDescr: The builder produces an immutable estimator. Fit resolves a plan that selects in-memory shuffled epochs or streaming batches. Both feed the learning state, which produces the exportable fitted model and its predictions.
    classDef planNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
    classDef computeNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
    classDef modelNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px

    B["SKSGDRegressorBuilder<br>.maximum_number_of_iterations(1000)<br>.execution_mode(Automatic)"]:::planNode
    B --> E["SKSGDRegressor<br>(immutable estimator)"]:::planNode
    E -->|fit X y| R{"plan"}:::planNode
    R -->|fits in RAM| C["IN-MEMORY<br>shuffled epochs over the whole matrix<br>one update per sample"]:::computeNode
    R -->|larger than RAM| St["STREAMING<br>sk_run_streaming_driver<br>PartialFit span per batch"]:::computeNode
    C --> Acc["learning state<br>θ, intercept, clock, average<br>θ ← θ − η·∇L"]:::computeNode
    St --> Acc
    Acc --> Ms["SKSGDRegressorModel<br>θ (exportable)"]:::modelNode
    Ms --> P["ŷ = X·θ"]:::modelNode

(Acc marks the state both regimes share; the classifier also carries its fixed SKLabelTable.)

2. Theory from zero — gradient descent, without the magic

Both families are supervised, so let us be explicit about the data: you have rows $x_i \in \mathbb{R}^p$, and either

  • regressor: continuous $y_i$; the loss is squared error $L(\theta) = \tfrac{1}{2} \sum_i (x_i \cdot \theta - y_i)^2$;
  • classifier: labels $y_i \in {0, \ldots, C-1}$; one-vs-rest fits one linear head per class, and probabilities come from the sigmoid (log-loss) or the clipped affine map (modified huber) — the only two probabilistic losses.

The property that carries this chapter is convexity. Squared error is a quadratic in $\theta$; log-loss with a linear map is convex. Both are convex, so plain gradient descent converges provably (cited: Bottou 2010 rate analysis; Ruder’s survey as the map). No second-order machinery, no adaptive friend — the bare minimum the modern frameworks demand before their own elaborate bells are even considered.

2.1 The single formula to understand

For one sample $x$, target $y$ and sample weight $c$, with ridge penalty $\lambda$ weighed on the coefficient vector:

$$\begin{aligned} \operatorname{gradient}(w) &= c \cdot \ell’(x^{\mathsf T}w + b, y) \cdot x + \lambda w && \text{regressor; squared error’s slope} \ w_{\text{new}} &= w - \eta_t \cdot \operatorname{gradient}(w) \ b_{\text{new}} &= b - \eta_t \cdot c \cdot \ell’(x^{\mathsf T}w + b, y) && \text{the intercept is never penalized} \end{aligned}$$

Separate facts carry each symbol, and each one is a classic textbook door:

  • $\eta_t$, the learning rate — how far to travel per step. Too high = divergence; too low = days to converge. The four shipped schedules:
    • constant: $\eta_t = \eta_0$ — the simplest baseline;
    • inverse_scaling: $\eta_t = \eta_0 / (1 + t)^p$, $p = 0.25$ for the regressor (scikit-learn’s default) — the Robbins–Monro annealing family;
    • optimal: $\eta_t = 1/(\alpha(t + t_0))$, the classical rate. The constant $t_0$ is estimated from the first batch’s slope scale (Bottou 2012, “Stochastic Gradient Descent Tricks”) instead of hard-coded, because it is dataset-dependent; the estimate is documented and reproducible, not a false universal;
    • adaptive: keep $\eta$ while the epoch objective improves, halve it on a plateau.
  • $\lambda$ (ridge), as the L2 penalty you already know from the PRD — the coefficient shrink is temporal-independent: the same penalty every step; the library holds $\lambda = 0$ as legal but noted — a fully quadratic, non-regularized problem is exactly SKLinearRegression, shipped elsewhere by design (convex but closed-form). The L1 component is applied as a proximal soft-threshold after the step, which is what produces exact zeros.

Sources:

  • Bottou, “Large-scale machine learning with SGD” — the classic: convergence as rates, and the online-vs-batch discussion worth reading before writing
  • Ruder, “An overview of gradient descent optimization algorithms”
  • Robbins & Monro, “A stochastic approximation method” (1951) — the theorem behind $\eta_t \approx 1/t$
  • Bottou, “SGD Tricks” (2012) — the practically-correct lemma behind scikit-learn’s optimal
  • Shalev-Shwartz et al., “Pegasos: primal estimated sub-gradient solver for SVM” — the theoretical framework tying loss + regularization to convergence with the theoretical learning rate

2.2 Why the classifier’s labels survive streaming (SKLabelTable)

A streaming classifier sees classes in whatever order the batches arrive. The fitted table freezes the canonical indices at first occurrence during fit, so "frog" stays index 0 for every later batch. A class that never appeared at fit time is rejected by partial_fit (and by a later streaming batch) instead of being silently appended: a new column would invalidate the coefficient matrix that was already trained. That is a documented, deliberate deviation from scikit-learn’s grow-only classes= protocol, and an_unseen_class_is_rejected in §5 is the boundary.

3. The combinable state, spelled out

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/sgd/core_implementation.rs
pub struct SKSGDState {
    /// the schedule's t: number of `absorb_batch` calls the state has survived
    pub clock: u64,
    /// (p, C) — C = 1 for the regressor; f64 state unconditionally, per the anchor
    pub coefficients: ndarray::Array2<f64>,
    pub intercept: ndarray::Array1<f64>,
    /// classifier only — first-occurrence canonicalization, frozen at fit
    pub labels: Option<SKLabelTable>,
}

impl SKSGDState {
    /// THE "partial fit". One batch in; one (θ, t) update out. This is EXACTLY the
    /// closure body handed to `sk_run_streaming_driver` — no outer loop re-derives it.
    pub fn absorb_batch<F: SKFloat>(
        &mut self,
        batch: &ndarray::ArrayView2<F>,
        targets: &ndarray::ArrayView1<'_, f64>,
        parallelism: usize,
        hyper: &SKSGDHyperparameters,
    ) {
        // gradient runs through the vectorized kernels (partial per worker — as in §6
        // of the transformer chapter), so no thread sees another's accumulator:
        let gradient = compute_batch_gradient(batch, targets, &self.coefficients, hyper);
        let rate = self.schedule_rate();   // constant | inverse_scaling by the clock
        self.coefficients = &self.coefficients - &gradient.mapv(|g| rate * g);
        self.intercept = ...;  // same update for the intercept row, per schedule
        self.clock += 1;
    }
}
}

4. Fit, predict, and the twins

SKSupervisedFit goes the same plan-setting four lines as every algorithm (§5 of the anchor) and then, per plan.mode:

#![allow(unused)]
fn main() {
impl<F: SKFloat> SKSupervisedFit<F> for SKSGDRegressor {
    type Model = SKSGDRegressorModel;
    type Error = SKError;
    fn fit<'a, X, T>(&self, features: X, targets: T) -> Result<Self::Model, SKError>
    where
        X: TryInto<SKDataView<'a, F>, Error = SKError>,
        T: TryInto<SKTargetView<'a>, Error = SKError>,
    {
        let view = features.try_into()?.as_dense()?;
        let target = targets.try_into()?.as_continuous()?.into_owned();
        sk_run_operation(
            SKOperationAttributes {
                operation: SKOperationKind::Fit,
                rows: view.nrows(), columns: view.ncols(),
                execution_mode: self.execution_intent(), backend: SKBackendKind::Faer,
            },
            || {
                let mut context = SKExecutionContext::real();
                context.dataset_size_bytes = view.len() as u64 * size_of::<F>() as u64;
                context.dataset_elements = Some(view.len() as u64);
                context.scalar_size_bytes = size_of::<F>() as u64;   // buffer guard precision
                context.access_pattern = SKAccessPattern::Sequential;
                context.grain = SK_ELEMENTWISE_TRANSFORM_GRAIN;   // the update's dominant kernel
                context.batch_size_hint = Some(self.maximum_batch_samples());
                let plan = sk_resolve_execution_plan(self.execution_intent(), &context)?;

                use SKExecutionMode::*;
                match plan.mode {
                    InProcessSynchronous | InProcessAsynchronous => {
                        // THE degenerate batch: the entire array is one batch
                        let mut state = SKSGDState::zeros(view.ncols(), self.hyperparameters());
                        state.absorb_batch(&view, &target.view(), plan.parallelism, &self.hyperparameters());
                        Ok(SKSGDRegressorModel::from_state(state))
                    }
                    OutOfCoreMemoryMapped => Err(SKError::ExecutionModeIncompatible {
                        mode: "OutOfCoreMemoryMapped", pattern: "sequential-batch SGD",
                    }),
                    OutOfCoreStreaming => Err(SKError::ExecutionModeIncompatible {
                        mode: "OutOfCoreStreaming", pattern: "in-memory fit entry point (use fit_streaming_source)",
                    }),
                    Automatic => unreachable!("resolve always returns a concrete mode"),
                }
            },
        )
    }
}
}

and the streaming twin (the natural home):

#![allow(unused)]
fn main() {
impl SKSGDRegressor {
    pub fn fit_streaming_source<S, F>(
        &self, source: &mut S, plan: &SKExecutionPlan,
    ) -> Result<SKSGDRegressorModel, SKError>
    where
        F: SKFloat + Send,
        S: SKLazySource<F> + Send,
    {
        let mut state = SKSGDState::zeros(...);
        sk_run_streaming_driver(source, &mut state, |batch, parallelism, state| {
            sk_run_operation(
                SKOperationAttributes {
                    operation: SKOperationKind::PartialFit,   // one span per batch
                    rows: batch.number_of_rows(), columns: batch.number_of_columns(),
                    execution_mode: self.execution_intent(), backend: SKBackendKind::Faer,
                },
                || {
                    state.absorb_batch(&batch.view().as_dense().expect("dense batch"), &batch_targets, parallelism, &self.hyperparameters());
                    SKStreamDecision::Continue   // keep streaming until the source ends
                },
            )?,
        }, plan)?;
        Ok(SKSGDRegressorModel::from_state(state))
    }
}
}

The exact update closure (sketch carried faithfully into chapter 3):

$$\begin{aligned} \text{one batch in: } X_B, y_B &\rightarrow \operatorname{gradient}(\theta) \leftarrow \tfrac{1}{\lvert B \rvert}(X_B\theta - y_B)^{\mathsf T}X_B + \lambda\theta \ \text{rate} &\leftarrow \operatorname{schedule}(\eta_0, t) && \text{one of constant or inverse_scaling} \ \theta &\leftarrow \theta - \text{rate} \cdot \operatorname{gradient} && \text{the only sequentially mutating side of the family} \ t &\leftarrow t + 1 \end{aligned}$$

5.6 predict and the label table’s reverse map

The classifier’s predict reduces probabilities across categories via the same label table — argmax over the class weights, then SKLabelTable::label_of(index) decodes the integer back into its frozen label string. The regressor simply returns one F per row — matching the anchor §3.2 rule: SKRegressorPredictor<F> returns Array1<F>.

The structural rule this encodes: label lookups always go through the table, never an ad-hoc map in the model — chapter 17’s nominal_labels_round_trip and an_unseen_class_is_rejected are the enforcement.

5. Tests — the streaming-native four

#![allow(unused)]
fn main() {
// sgd_classifier/*_tests.rs and sgd_regressor/*_tests.rs
#[test]
fn one_streaming_pass_equals_one_in_memory_epoch() { /* regimes-equivalence */ }

#[test]
fn dense_and_csr_fits_agree_across_losses_and_penalties() { /* never densify */ }

#[test]
fn partial_fit_continues_the_schedule_counter() { /* the clock survives */ }

#[test]
fn an_unseen_class_is_rejected() { /* frozen class table */ }

#[test]
fn early_stopping_over_a_stream_is_refused() { /* explicit refusal */ }
}

6. Acceptance & sources — mapped, not repeated

Acceptance criterion (PRD §8.7)Realized
Lots and little data§5 test 1 — literally the regimes-equivalence
Under concurrencyper-sample updates are sequential by definition; the estimator and model are immutable, Send + Sync, and serve concurrent predictions
Model export$\theta$ + clock + label table — plain fitted structure
MetricsSKSupervisedScorer ($R^2$ for the regressor) / SKLabelScorer (accuracy for the classifier through the scorer chapter)

Standing study sources (each also explained §2):

  • Bottou, “Large-scale machine learning with SGD” (2010) & “SGD Tricks” (2012)
  • Ruder (see §2)
  • Shalev-Shwartz et al., Pegasos (see §2)
  • Robbins & Monro (see §2)
  • scikit-learn sklearn.linear_model.SGDClassifier/SGDRegressor documentation and the partial_fit protocol docs — the semantics referenced in this chapter, including the estimated $t_0$ for optimal.

Next: the full contract, decision by decision, in chapter 17.


Source providers (current API). The shipped fit_streaming takes a SKSourceProvider<F> (transformers) or SKSupervisedSourceProvider<F> (supervised models). Passing &mut source still compiles and takes one pass; wrap a factory in SKReopenableSource::new(|| ...) to let an iterative estimator run several epochs. See chapter 18.

Adding a Neighbors Model — SKKNeighborsClassifier and SKKNeighborsRegressor

Pre-read: How to add an Algorithm and the k-nearest neighbours chapter.

This tutorial walks through the neighbours estimators as they are shipped: what fit stores, how predict searches, why the representation chooses the strategy, and the exact public surface you compose in a pipeline or a grid search.

Two rules shape everything below:

  • fit stores the training design and the label table; it does not compress or discard rows.
  • predict needs the nearest stored rows to each query, so the estimator chooses a search strategy at run time: a spatial index for dense low-dimensional data, brute force for sparse, mixed or cosine data.

1. The public surface

#![allow(unused)]
fn main() {
use sciencekit_neighbors::{SKKNeighborsClassifier, SKNeighborsWeights};
use sciencekit_common::{SKBuilder, SKClassifierPredictor, SKSupervisedFit};

let classifier = SKKNeighborsClassifier::<f64>::build()
    .nearest_neighbors_count(5)
    .weights(SKNeighborsWeights::Uniform) // or Distance
    .build()?;

// `labels` is an `Array1<i64>`; nominal labels can be a `Vec<&str>` / `&[&str]`.
let labels = ndarray::Array1::from_vec(vec![0_i64, 1, 0, 1]);
let model = classifier.fit(training_features.view(), labels.view())?;
let labels_out = model.predict_labels(query_features.view())?;
let probabilities = model.predict_probabilities(query_features.view())?;
}

The builder is the only constructor. It exposes:

SetterDefaultMeaning
nearest_neighbors_count5how many neighbours vote
weightsUniformDistance uses inverse-distance weighting
algorithmAutoKdTree, BallTree, BruteForce or automatic
metricEuclideanEuclidean, Manhattan, Chebyshev, Cosine
leaf_size40tree leaf bound (dense tree paths)
backendFaercarried into the model and its spans
execution_modeAutomaticrecorded configuration

The regressor (SKKNeighborsRegressor) has the same surface and returns responses.

2. What fit stores

fit keeps:

  • the training design as an owned dense block or a CSR matrix — never a copy per query;
  • the label table for classification (SKLabelTable), built in first-occurrence order, the library-wide convention;
  • the configuration, including the resolved search strategy.

A fitted classifier exposes classes() (the label table), the resolved strategy and the stored representation; the regressor exposes the same minus the table.

3. How predict searches

Auto resolves once, when the model is fitted:

DataMetricStrategy
dense, $\ge 64$ training rows, $\le 20$ featuresEuclidean/Manhattan/Chebyshevk-d tree
dense, $\ge 64$ rows, $> 20$ featuresEuclidean/Manhattan/Chebyshevball tree
dense, < 64 rowsanybrute force (a tree costs more than it saves)
sparse or mixedanybrute force over stored entries
anyCosinebrute force (cosine has no tree-pruning form)

An explicit KdTree or BallTree request on a representation the index cannot serve returns UnsupportedRepresentation with a suggestion to use Auto or BruteForce. Sparse input is never densified.

The brute-force searcher and the trees share one contract, so the neighbour list is always ordered by distance, then the smallest training index — the determinism guarantee that the vote and the probabilities rely on.

4. Voting and probabilities

Classification takes the majority of the $k$ neighbours. With Distance weighting each neighbour contributes $1/d$ (a zero-distance neighbour uses the documented convention, so weights stay finite). Probabilities are the weighted neighbour fractions and sum to one; the columns follow the class table. A vote tie goes to the smallest canonical class index.

Regression returns the mean of the neighbour responses (uniform) or their inverse-distance weighted mean. Integer targets are promoted to the model scalar.

5. What to test when you add a neighbour variant

Follow the companion-module rule: put the tests beside the implementation.

  1. Dense/sparse parity — the same logical design gives the same predictions.
  2. Brute-force agreement — the new path returns exactly what the trees return.
  3. Ties — equidistant neighbours and tied votes resolve deterministically.
  4. Representation rejection — an explicit unsupported tree request is a structured error.
  5. Concurrency — a fitted model is Send + Sync and parallel prediction equals sequential.

6. Out-of-core today

The memory-mapped base (SKMappableSource, memmap2) and model persistence/export are Phase 7 (interop) work, not part of the neighbours change. Streaming fit_streaming and radius-based estimators are explicit non-goals of this change; the estimators hold the training design in memory. The PRD records both deferrals in the Phase 3 section.

Contribute

⭐ Star the project

Stars are the simplest contribution: they boost visibility, attract contributors and tell us the community wants this. If sciencekit would help your work, a star takes two seconds.

Where help is needed

The roadmap is large by design — every algorithm is an isolated, well-scoped opportunity:

AreaWhat you would doGood for
🔢 AlgorithmsImplement one estimator following naive → tests → performance → out-of-coreRust + ML enthusiasts
🧮 Math kernelPairwise distances, sparse ops, SIMD hot paths in sciencekit_mathPerformance engineers
🐍 Python bindingsPyO3 interfaces with maximum zero-copy, per completed algorithmPyO3 experience
🎮 GPU backendsOpenCL → CUDA → ROCm behind SKComputeBackendGPU/HPC developers
📚 DocumentationThis book, API docs, examples from real testsWriters & newcomers
🐛 Testing & bugsReproduce issues, improve coverage of companion test modulesEveryone

Open an issue or grab one labeled good first issue — specs are written before code, so you always start with clear requirements.

How we work

  1. Spec first (OpenSpec): each change gets a proposal, spec deltas and tasks on a dedicated -openspec branch.
  2. TDD: tests are written first and must fail; implementation follows minimally.
  3. Small PRs: every change alters the minimum necessary; work happens in git worktrees, never directly on main.
  4. Independent review: an independent reviewer validates the spec was met before merge.
  5. Acceptance: every implementation runs with lots and little data, under concurrency, exports its model and produces metrics.

Full engineering rules live in AGENTS.md and the product truth in the PRD.

Getting started

git clone https://github.com/neurono-ml/sciencekit.git
cd sciencekit
cargo build && cargo test    # Rust 1.85 pinned via rust-toolchain.toml
First contribution idea: documentation is a great entry point — this book itself is built from markdown anyone can improve. See the Documentation Guide.

License

Apache-2.0 — including patent protection. By contributing you agree your contributions are licensed under it.

Documentation Guide

Instructions for agents and contributors writing or updating this book. Follow them so every page keeps the same visual language and quality bar.

Where things live

PathPurpose
docs/book.tomlmdBook configuration (site URL, theme, search)
docs/src/Chapters in markdown (SUMMARY.md defines the table of contents)
docs/skin/custom.cssDesign system — all visual components
docs/skin/custom.jsSidebar brand, scroll-reveal animations, counters
.github/workflows/deploy-documentation.ymlBuilds and publishes the book to GitHub Pages

Branch workflow (mandatory)

  • The documentation lives on branch docs/documentations — never commit directly to it from main.
  • Every docs change happens in a worktree: temporary/worktrees/docs/<change-name> on branch docs/<change-name>, merged into docs/documentations when done.
  • Pushing to docs/documentations automatically rebuilds and deploys the site.

Local preview

mdbook serve docs --open     # live reload at http://localhost:3000
mdbook build docs            # output in docs/book/ (never committed)

Language rules

  • The book is written in English. Everything durable in this repository is English.
  • The PRD (docs/PRD.md) is the source of truth; translate its concepts faithfully, never invent scope.
  • Code identifiers stay exactly as they are (SKStandardScaler, sk_train_test_split) — do not translate names.

Component catalog

Use the ready-made components instead of raw styling. All accept standard HTML attributes.

Hero + announcement pill

<div class="sk-hero reveal">
  <div class="sk-announce">
    <span class="sk-announce__tag">New</span>
    Supporting text
  </div>
  <h1 class="sk-hero__title">Big statement title</h1>
  <p class="sk-hero__subtitle">Supporting sentence.</p>
</div>

Cards grid

<div class="sk-cards reveal">
  <div class="sk-card">
    <span class="sk-card__icon sk-icon--sky">⚡</span>
    <div class="sk-card__title">Title</div>
    <p>Description.</p>
  </div>
</div>

Icon tints: sk-icon--sky | violet | emerald | amber | rose | neutral. Add sk-card--flow for gradient-washed feature cards.

Callout boxes

<div class="sk-box sk-box--info">…</div>

Variants: sk-box--info (blue), sk-box--tip (violet), sk-box--success (green), sk-box--warning (amber), sk-box--danger (red).

Stats band

<div class="sk-stats reveal">
  <div class="sk-stats__item"><div class="sk-stats__value js-count" data-target="39" data-suffix="+">39+</div><span class="sk-stats__label">algorithms mapped</span></div>
</div>

js-count animates the number when it scrolls into view.

Pills (status badges)

<span class="sk-pill sk-pill--emerald">Done</span>

Variants: sk-pill--sky | violet | emerald | amber | rose | neutral.

Progress bar

<div class="sk-progress"><div class="sk-progress__bar sk-progress__bar--amber" style="width:18%"></div></div>
<div class="sk-progress__meta"><span>label</span><span>18%</span></div>

Bar colors mirror pills: --sky, --violet, --emerald, --amber.

Timeline (roadmap)

<div class="sk-timeline">
  <div class="sk-timeline__item is-active reveal">
    <div class="sk-timeline__card">
      <div class="sk-timeline__head">
        <span class="sk-timeline__title">Phase N — Name</span>
        <span class="sk-pill sk-pill--amber">In progress</span>
      </div>
      <p>Summary.</p>
    </div>
  </div>
</div>

Item states: is-done (green dot), is-active (amber dot), default (violet dot).

Donut chart & CSS bars

Copy the SVG structure from Algorithms and recompute segments: circumference = $2\pi \times 80 \approx 502.65$; segment = $\text{count} / \text{total} \times 502.65$; each circle’s stroke-dashoffset is the negative sum of all previous segments. Keep legend counts in sync.

For horizontal bars reuse .sk-bars rows as seen in Plan & Roadmap.

Terminal window

<div class="sk-window">
  <div class="sk-window__bar">
    <span class="sk-window__dot sk-window__dot--r"></span>
    <span class="sk-window__dot sk-window__dot--y"></span>
    <span class="sk-window__dot sk-window__dot--g"></span>
    <span class="sk-window__title">bash</span>
  </div>

  ```bash
  cargo test --workspace
  ```

</div>

Statement panel & closing CTA

<div class="sk-statement reveal"><p class="sk-statement__text">One strong sentence.</p></div>

<div class="sk-cta reveal">
  <div class="sk-cta__title">Call to action</div>
  <p>Why act.</p>
  <a class="sk-btn sk-btn--star" href="#">⭐ Label</a>
</div>

Buttons

<a class="sk-btn sk-btn--primary" href="./page.html">Primary action</a>       <!-- dark -->
<a class="sk-btn sk-btn--secondary" href="#">Secondary</a>                    <!-- outline -->
<a class="sk-btn sk-btn--star" href="...">⭐ Star-flavored</a>                <!-- amber -->

Content rules

  1. Add new chapters to SUMMARY.md under the right part (Project / Engineering / Community / Development Explained).
  2. Keep numbers honest: algorithm counts, phase progress and status pills must match the roadmap state.
  3. Prefer components over custom inline CSS; extend skin/custom.css only for genuinely reusable pieces.
  4. Add the reveal class to major blocks for scroll animation — sparingly.
  5. Internal links use relative paths ending in .html (./algorithms.html).
  6. Run mdbook build docs and fix every warning before pushing; create-missing = false means broken links fail the build.
  7. Diagrams must be Mermaid, never ASCII. Write a ```mermaid fence; the book renders it client-side (see AGENTS.md → Documentation). Add an accTitle/accDescr to every diagram so it is accessible.
  8. Mermaid colors must use the fixed --sk-* pairs. Every classDef/style declares fill + stroke + color from the approved pairs below — never fill alone, so text stays legible in both book themes:
    • blue: fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    • green: fill:#f0fdf4,stroke:#16a34a,color:#14532d
    • orange: fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    • violet: fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    • amber: fill:#fef3c7,stroke:#d97706,color:#78350f
    • rose: fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
  9. Mermaid labels must not clip. Keep each line at or below ~24 characters, break long node labels with explicit <br/>, and put spaces around separators in edge labels (|InProcess* | whole array|, not |InProcess*|whole array|). Unbreakable tokens (type names, paths) go on their own <br/> line.
  10. Equations must be LaTeX, not plain text. Write $...$ (inline) or $$...$$ (display) so KaTeX renders them. Do not paste ‖a‖², Σ, √ etc. as plain text.
  11. Every image needs descriptive alt text. Diagrams carry accTitle/accDescr; images (.png/.svg) must have an alt attribute that explains the content as read, not just a filename or raw code.

Analytics, search indexing and SEO

The published book carries its own analytics and search-discovery setup, so traffic and indexing can be measured without touching every chapter.

Analytics and verification tags

docs/theme/head.hbs injects, into the <head> of every generated page:

TagPurposeIdentifier
Google Analytics 4traffic and behaviour reportsG-HSGHJJVTEX (property “sciencekit docs”)
Microsoft Claritysession replays and heatmaps (Bing/Microsoft)z93niam8d4 (project “sciencekit documentation”)
Google Search ConsoleGoogle ownership verification8SLqi9ZwwJxRL7gm08BvIqJdCRUKCn3Lc0fatfK_OFA
Bing Webmaster ToolsBing ownership verificationA59C6DA6DA95C4B3AAC7D9FC2D822269

To verify ownership manually, the Search Console HTML file (docs/src/google29e18863a8e69344.html) and the Bing verification meta tag must stay in place — removing them revokes ownership.

SEO metadata

docs/theme/head.hbs also writes the author, robots, Open Graph, Twitter Card and SoftwareSourceCode JSON-LD metadata. Per-page canonical and og:url values are added after mdbook build by docs/scripts/postbuild.mjs, which also generates sitemap.xml from every rendered chapter. docs/src/robots.txt points crawlers at that sitemap.

IndexNow

Bing, Yandex and other IndexNow participants receive an instant notification after each Pages deployment. The workflow runs docs/scripts/submit-indexnow.mjs, which reads the sitemap and posts every URL to api.indexnow.org. The key file docs/src/4f6c6bea947c13936cc169b2f9e34826.txt must remain reachable at the site root; the key itself is not a secret, it only proves control of the host.

Checklist for a docs change

  • Worktree created on temporary/worktrees/docs/<name>
  • Content in English, consistent with the PRD
  • New pages registered in SUMMARY.md
  • Components used per catalog above
  • mdbook build docs passes with zero warnings
  • Merged into docs/documentations (Pages deploys automatically)

Developer Book

Welcome to the Developer Book — a textbook inside the sciencekit documentation. The other pages tell you what sciencekit is. These chapters tell you how sciencekit was built — decision by decision, pull request by pull request — and, more importantly, why each choice was made, and what alternatives were deliberately thrown away.

You do not need a background in Rust or in numerical computing to read it. You need:

  • Basic programming — you know what a function, a loop, a variable and an if are.
  • Curiosity — you want to know why, not just what.
  • Patience — some ideas (traits, generics, zero-copy) take a chapter or two to click.

How to read this book

Each chapter corresponds to one real pull request that changed the code, and each is written as a self-contained lesson with the same skeleton:

  1. The problem we were solving — a plain-language story, before any math.
  2. The decisions — and the roads not taken — the choices, and the alternatives we rejected.
  3. The concepts, taught from zero — the Rust and numerical ideas the chapter needs.
  4. Each object, explained — every public struct, trait, enum and function, and why it exists.
  5. A real walk-through, using the tests — the actual tests from the repository, read line by line.
  6. Look inside — a diagram and a strong insight.
  7. Recap — what you should take away.

Why we use the tests as examples

sciencekit is built with test-driven development: the tests in the *_tests.rs companion modules are the executable specification of every function. When a chapter says “here is how this works”, it points you at the real test that proves it. You can read the code, then run cargo test and watch it pass. The test is the proof; the chapter is the explanation.

The order matters

The chapters follow the order the code was written. Earlier chapters build concepts that later chapters assume. In particular, Core contracts is the keystone — almost every later chapter builds on the types it introduces. If you only read one chapter first, read that one.

Bootstrap: workspace & CI     — the skeleton
Core contracts                — the vocabulary (traits, errors, views)  ← keystone
Math kernels & BLAS           — the numeric substrate
Execution & observability
The host-centric backend
Module hygiene                — how the code is organised as it grows
Parallel kernels & streaming
The first algorithm           — SKStandardScaler, the estimator template

How to keep this book honest

sciencekit is still being built. When new algorithms land, or a bug fix changes behaviour, these chapters must change too. The final chapter, Maintaining this book, explains that rule: new features get a new chapter; fixes and refactors update an existing one. If you find a chapter that no longer matches the code, that is a bug — in the book, not in the code — and it should be fixed the same way a code bug is.

Bootstrap: the Cargo workspace & CI

Every machine-learning library is, underneath, a collection of many small pieces that must agree on shared rules: how numbers are typed, how errors are reported, how code is formatted, and how it is proven to work. When sciencekit started, it was an empty repository — no code at all. The very first engineering decision was therefore not which algorithm to write, but how to lay the ground so that every later chapter has a stable place to stand. This chapter is about that foundation: a Cargo workspace that splits the library into sub-crates, a pinned Rust toolchain, and an automated CI pipeline that guards the whole thing.

1. The problem we were solving

Imagine you are going to build a house. You do not start by picking paint colors. You start with the foundation, the plumbing, the frame — the parts that are invisible once the house is finished but that everything else depends on.

A Rust library has the same hidden first step. Before you can write a single estimator, you need to answer boring-but-critical questions:

  • Where does the code live? One giant folder, or several small, related folders?
  • Which version of the Rust language are we writing for? Rust evolves every six weeks; we must say exactly which one we target.
  • How do we prove the code works? Running the tests by hand on your laptop is not enough. A machine must re-run them automatically on every change, forever, so a mistake is caught the moment it is made.

If you skip these questions, you get a pile of code that:

  • compiles on the author’s machine but not anyone else’s;
  • mixes unrelated concerns in one huge, slow-to-compile crate;
  • silently breaks because nobody re-ran the tests.

In sciencekit’s case the very first commit had no code at all — the repository was freshly initialized under the name neurono-ml. So the first task, called Phase 0.1 “bootstrap”, was to create the skeleton: a workspace, a pinned toolchain, and a CI pipeline. Nothing else. Two pull requests did this:

  • PR 96b77ab — “bootstrap sciencekit workspace”: added Cargo.toml (the workspace root), rust-toolchain.toml (the pinned toolchain), a LICENSE, and a nearly-empty src/lib.rs.
  • PR dd3b524 — “add CI workflow”: added .github/workflows/ci.yml with five automated gates.

Everything you will read in later chapters — sciencekit_common, sciencekit_math, every algorithm — sits on top of this skeleton. That is why the chapter is called “bootstrap”: a library cannot build itself up until this scaffolding exists.

2. The decisions — and the roads not taken

A bootstrap is almost entirely decisions about structure. Here are the four big ones, and the alternatives we consciously rejected.

DecisionWhy we chose itAlternatives we discarded
Split into a Cargo workspace of sciencekit_* sub-crates (PRD §3.1)Compile times stay small (each sub-crate rebuilds independently), dependencies are isolated per area, and PRs stay small because each new area lands as its own crate.One giant crate. Everything in a single crate forces a full recompile on every change and mixes concerns. Rejected at the architecture level (PRD §3.1).
Empty members = [] at bootstrap, sub-crates added one per changeAt bootstrap there is nothing to add yet. PRD §3.1 mandates sub-crates arrive one per change to keep PRs small; the workspace starts empty and grows deliberately.Create all sub-crates immediately. Would have created a dozen empty crates with no content — noise and guessing about future boundaries.
Pin the toolchain to exactly Rust 1.85, edition 2024 (PRD §3.6)A clean clone compiles with exactly 1.85 regardless of the contributor’s installed Rust. Upgrading becomes an explicit, reviewable change (the comment in rust-toolchain.toml says exactly this).No pin / “use whatever is installed”. Builds become non-reproducible — the same code behaves differently on different machines. Rejected because reproducibility is a core requirement.
CI gates: fmt + strict clippy + test + examples + MSRVEach gate catches a different failure class early and automatically: formatting (consistency), clippy (likely bugs and code smells), tests (behavior), examples (documented usage compiles), and a dedicated MSRV job (guarantees 1.85 still builds).Only run cargo test. Would pass even if formatting is chaotic or the code is full of warnings-as-errors; the stricter gates exist precisely to prevent those.

Two smaller but telling decisions in the same spirit:

  • License: Apache-2.0 — chosen for the project (visible in Cargo.toml), standard for an international open-source library.
  • src/lib.rs declares #![forbid(unsafe_code)] — a library this concerned with correctness opts out of unsafe Rust by default, so no unsound code can sneak in silently. (A later phase reintroduces a controlled, reviewable amount of unsafe for SIMD — but only behind explicit, approved features.)

3. The concepts, taught from zero

Before we read the files, we need three ideas from scratch. If you already know them, skim; if not, this is the whole foundation.

3.1 What is a “crate”? What is a “workspace”?

A crate is Rust’s unit of compilation and distribution. Think of it as a package: it has a name, a version, a set of dependencies, and a set of source files. When you build, Rust compiles each crate as a unit.

A workspace is a collection of crates that are developed together in one repository. They share a single Cargo.toml at the root that lists them. You can build, test, and release them all with one command (cargo build --workspace).

Why does this matter for a library? Three reasons:

  1. Isolation. If sciencekit_math (linear algebra) pulls in a heavy dependency, that dependency only affects sciencekit_math. The other crates do not see it, do not recompile because of it, and are not slowed down by it.
  2. Small PRs. Each algorithm area becomes its own crate, added in its own change. Reviewers read one focused change instead of a megamorphic one.
  3. Reuse. Sub-crates can depend on each other cleanly — sciencekit_math depends on sciencekit_common, for instance — using path dependencies (relative paths inside the workspace) rather than downloading from the internet.

Think of a workspace like a monorepo: one repository holding several related projects that know about each other.

3.2 Edition 2024 and MSRV

Rust has two “versions” knobs that beginners often confuse:

  • The edition is a language compatibility mode. Every few years the Rust team makes a release that may change how some syntax behaves. To avoid breaking all existing code, they ship these as “editions” (2015, 2018, 2021, and now 2024). Picking edition = "2024" just says “write this crate using the 2024 rules of the language.” It is set once, in Cargo.toml.

  • MSRV stands for Minimum Supported Rust Version. It is the oldest Rust compiler that this project promises to work with. Our MSRV is Rust 1.85 (set via rust-version = "1.85" in Cargo.toml). This is a compatibility promise to users: they can build with 1.85 or anything newer.

There is also the subtle difference between the two places we record the toolchain:

  • rust-version = "1.85" in Cargo.toml is a promise to the world — it says “1.85 is the minimum you need.” It is metadata.
  • rust-toolchain.toml is a declaration for our own machines — it says “use exactly 1.85, no matter what is installed.” It enforces reproducibility for contributors and CI.

The difference matters: one is a guarantee, the other is a lock.

3.3 What is a CI pipeline? What are “gates”?

CI stands for Continuous Integration. The idea: instead of hoping everyone runs the tests locally, a remote server automatically runs a checklist of checks on every code change. If any check fails, the change is blocked — it cannot be merged.

Each check is a gate: a rule the code must pass to be accepted. Think of it like airport security — you do not board until every checkpoint clears. The sciencekit CI has five gates, and each guards a different failure:

GateWhat it checksWhat it catches
fmtDoes the code match rustfmt’s canonical formatting?Chaotic, inconsistent whitespace/style that makes diffs unreadable.
clippyDoes the code pass linting with -D warnings (warnings become errors)?Likely bugs, unnecessary clones, dead code, common mistakes.
testDo all unit tests and doctests pass?Broken behavior.
examplesDo the example programs compile and run?Documentation/examples that have drifted from the real API.
msrvDoes everything still build and pass on exactly Rust 1.85?Accidental use of features newer than the promised MSRV.

The msrv gate is the subtle one: our own machines might run Rust 1.90, but if someone on 1.85 is promised support, the code must actually build there. A dedicated job running exactly 1.85 proves it. That is the “reproducibility promise” made real.

3.4 The naming convention: SK / sk_

One more foundation stone, defined in PRD §3.4, will be visible in every later chapter, so it is worth learning now:

  • No abbreviations, except a single project prefix. Names must be complete and self-explanatory: maximum_number_of_iterations, not max_iter; nearest_neighbors_count, not k.
  • The project prefix sk / SK is the only allowed abbreviation.
  • Structs and traits get SK + PascalCase: SKEstimator, SKStandardScaler, SKExecutionMode.
  • Free functions, variables, and modules get sk_ + snake_case: sk_train_test_split, sk_resolve_execution_plan.
  • Methods (functions inside an impl block) get no prefix: fit, predict, execution_mode.
  • Crates always keep the full name sciencekit_* — never abbreviated.

Why? Machine-learning code is full of cryptic one-letter names (k, c, X, y). The project deliberately bans them for readability and self-documentation. The sk prefix is a namespace marker: it tells readers “this object belongs to sciencekit” the way a brand marks its products.

4. Each object, explained

For the bootstrap, the “objects” are configuration files and the workflow, not Rust structs. Each one is explained below in the same mini-structure.

4.1 Cargo.toml (workspace root)

What it is. The workspace’s identity card and command center. It declares the crate sciencekit and the workspace that will hold the sub-crates.

Why it exists. It is where the workspace is born. It records the name, version, edition, license, MSRV, and — crucially — the empty list of workspace members. Here is the real content (from PR 96b77ab):

#![allow(unused)]
fn main() {
[package]
name = "sciencekit"
version = "0.1.0"
edition = "2024"
license = "Apache-2.0"
rust-version = "1.85"
description = "Machine Learning library in Rust reimplementing all of scikit-learn — extreme performance, zero-copy and native out-of-core."
repository = "https://github.com/neurono-ml/sciencekit"

[workspace]
resolver = "3"
members = []
}

What we rejected. Filling members with a dozen not-yet-written sub-crates. The decision (PRD §3.1) is to add sub-crates one per change, so members starts empty and grows deliberately. The resolver = "3" line picks the modern dependency-resolution strategy (required for edition 2024 workspaces).

4.2 rust-toolchain.toml

What it is. The reproducibility lock. It tells any machine that opens this repository, “install and use exactly this Rust toolchain.”

Why it exists. To guarantee that a clean clone compiles identically for every contributor and for CI. The real content:

# Pin the exact Rust toolchain for reproducible builds (PRD §3.6).
# A clean clone compiles with exactly 1.85, edition 2024, regardless of the
# contributor's installed Rust. Upgrading the channel is an explicit, reviewable change.

[toolchain]
channel = "1.85"
components = ["rustfmt", "clippy"]
profile = "minimal"

Note the components line: it asks for rustfmt (the formatter) and clippy (the linter) to be installed alongside the compiler — the two tools our CI gates depend on. profile = "minimal" avoids installing extra docs/components we do not need, keeping clones fast.

What we rejected. Not pinning, or pinning to a moving “stable” channel. Both would break reproducibility.

4.3 src/lib.rs (the umbrella crate)

What it is. The root source file of the sciencekit crate — currently nearly empty.

Why it exists. It is the future umbrella: PRD §3.1 and §3.3 describe sciencekit as the crate that re-exports the public surface of all the sciencekit_* sub-crates, so users can write use sciencekit::prelude::* and get everything. At bootstrap there is nothing to re-export yet, so it carries only the two attribute declarations:

#![allow(unused)]
fn main() {
//! `sciencekit` — Machine Learning library in Rust reimplementing all of
//! scikit-learn, with extreme performance, zero-copy and native out-of-core.
//!
//! This crate is the umbrella re-export of the `sciencekit_*` sub-crates.

#![forbid(unsafe_code)]
#![warn(missing_docs)]
}

#![forbid(unsafe_code)] refuses any unsafe block (a correctness stance). #![warn(missing_docs)] warns when public items lack documentation (a quality gate — the whole library is to be documented).

What we rejected. Putting the umbrella crate logic inside the workspace root crate from day one. It will be a separate crate under crates/ once there is something to re-export.

4.4 .github/workflows/ci.yml (the CI pipeline)

What it is. The automation recipe. It is a GitHub Actions workflow: a YAML file that tells GitHub’s servers what to run on every push and every pull request.

Why it exists. To make the five gates (Section 3.3) run automatically and block bad changes. It triggers on push to main and on every pull_request. Let us look at the shape of two jobs, then the test job, then the MSRV job.

The fmt job checks formatting:

  fmt:
    name: Formatting (cargo fmt)
    runs-on: ubuntu-latest
    steps:
      - name: Install Rust 1.85 toolchain (rustfmt)
        uses: dtolnay/rust-toolchain@1.85
        with:
          components: rustfmt
      - name: cargo fmt --all -- --check
        run: cargo fmt --all -- --check

Note the trick in the last step: cargo fmt --check does not reformat the code; it only reports whether the code already matches the canonical format. If a contributor forgot to format, this job fails.

The clippy job runs the linter with warnings promoted to hard errors:

      - name: cargo clippy --workspace --all-targets -- -D warnings
        run: cargo clippy --workspace --all-targets -- -D warnings

The -D warnings flag is the teeth: a mere warning (e.g. an unnecessary .clone()) becomes a build error. This is deliberate strictness — the project would rather block a merge than ship a smell.

The test job runs everything:

      - name: cargo test --workspace --all-targets
        run: cargo test --workspace --all-targets

--workspace builds and tests every sub-crate; --all-targets also builds test code, examples, and benchmarks so that their compilation is checked too.

And the msrv job re-runs build + test on the exact promised minimum, closing the reproducibility loop:

  msrv:
    name: MSRV gate (exact 1.85)
    runs-on: ubuntu-latest
    steps:
      - name: Install exact Rust 1.85 toolchain (rustfmt + clippy)
        uses: dtolnay/rust-toolchain@1.85
        with:
          components: rustfmt, clippy
      - name: cargo build + test on exact 1.85
        run: |
          cargo build --workspace --all-targets
          cargo test --workspace --all-targets

What we rejected. A single catch-all cargo test job. Splitting fmt / clippy / test / examples / msrv into separate jobs means each failure is reported independently and clearly, and the CI can tell you exactly which guarantee was broken.

4.5 A peek at the future: the sub-crate layout

The workspace’s members list is empty today, but the plan (PRD §3.1) is a folder tree like this:

flowchart TD
    accTitle: The planned sciencekit workspace layout
    accDescr: A sciencekit workspace root containing Cargo.toml, a crates folder with one sub-crate per algorithm area, and a docs folder.
    ROOT[sciencekit/]
    ROOT --> CARGO[Cargo.toml<br/>workspace root]
    ROOT --> CRATES[crates/]
    ROOT --> DOCS[docs/]
    CRATES --> UMBRELLA[sciencekit/<br/>umbrella crate re-exports]
    CRATES --> COMMON[sciencekit_common/<br/>base traits, types, errors]
    CRATES --> MATH[sciencekit_math/<br/>linear algebra, BLAS, SIMD, sparse]
    CRATES --> PREP[sciencekit_preprocessing/<br/>scalers, encoders]
    CRATES --> LINEAR[sciencekit_linear_model/<br/>regressions, logistic, SGD]
    CRATES --> MORE[... one crate per algorithm area]

    style ROOT fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style CRATES fill:#fef3c7,stroke:#d97706,color:#78350f
    style UMBRELLA fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style COMMON fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style MATH fill:#f0fdf4,stroke:#16a34a,color:#14532d

To see how a sub-crate actually registers into the workspace, here is the real sciencekit_math/Cargo.toml (from a later phase). Notice it is a member only once its own change adds it to the root’s members list, and it depends on sciencekit_common by path:

#![allow(unused)]
fn main() {
[package]
name = "sciencekit_math"
version = "0.1.0"
edition = "2024"
license = "Apache-2.0"
rust-version = "1.85"
description = "Computational kernels and the BLAS/LAPACK interface for sciencekit: pairwise distances, dense/sparse products, higher-order operations and memory-layout helpers."

[dependencies]
sciencekit_common = { path = "../sciencekit_common" }
faer = "0.24"
ndarray = { version = "0.17", features = ["rayon"] }
rayon = "1"
}

The path = "../sciencekit_common" is the workspace in action: an internal dependency resolved from a sibling folder, not from the internet.

5. A real walk-through, using the tests

Bootstrap (Phase 0.1) adds no algorithm code and therefore no *_tests.rs files — there is nothing to test yet. So the honest “executable example” here is the CI itself: what the pipeline actually runs on every change. Let us walk through the test job’s command as if we were the machine.

Step 1 — what cargo test --workspace --all-targets does

cargo test --workspace --all-targets

Run this in the terminal (it is what CI runs). Cargo:

  1. Reads the root Cargo.toml and discovers the workspace and its members.
  2. Compiles every crate in the workspace and their dependencies (the build).
  3. Finds every #[test] function in every crate, builds them, and runs them.
  4. Also builds and runs doctests — code examples written inside /// documentation comments. These are real, executable tests that prove the documented examples still work.
  5. With --all-targets, it additionally compiles examples and benchmarks, catching compilation errors in those too, even though it only runs the tests.

At bootstrap the output is essentially “0 tests” — but the build succeeds, which proves the workspace itself is sound. That is the whole point of this phase: a green build with nothing inside is the green light to start adding crates.

Step 2 — how a gate blocks a change

Suppose a contributor (or an agent) pushes a change with a single formatting slip — say, an extra space. The fmt job runs:

cargo fmt --all -- --check

Because --check only verifies, it exits with a non-zero status code (a failure). GitHub Actions marks the job red. The pull request shows ❌ Formatting (cargo fmt). The change is blocked until the contributor runs cargo fmt --all (without --check) to actually fix the formatting, then pushes again.

This is the loop that keeps the codebase healthy forever: write → push → machine verifies every guarantee → fixes if any gate fails.

Step 3 — why the MSRV gate exists

Here is a scenario the msrv job is designed to catch. A developer’s local Rust is version 1.90. They use a brand-new API that only exists in 1.90. It compiles fine locally, and cargo test passes. But the project promises support for 1.85. If nothing checks, this promise silently breaks.

The msrv job installs exactly 1.85 and builds + tests again:

cargo build --workspace --all-targets
cargo test --workspace --all-targets

If that 1.90-only API was used, the build fails here — even though it passed on the developer’s machine. The promise is enforced, not assumed.

6. Look inside

The key insight of this chapter: a workspace and a CI pipeline are the same idea at different scales. The workspace splits a big thing (the library) into small, isolated, verified pieces. The CI gates split "does it work?" into small, isolated, verified checks. Both are about making correctness *provable and incremental* rather than trusting a single big "it probably works."

The relationship between all the pieces we built:

flowchart TB
    accTitle: How the workspace, toolchain and CI gates fit together
    accDescr: The Cargo.toml workspace root ties together the toolchain file, the umbrella crate and the CI workflow. The crates subfolder grows one crate per change, and the CI pipeline runs fmt, clippy, tests, examples and an MSRV check as gates.
    Root["Cargo.toml<br/>(workspace root, members = [])"] --> Toolchain["rust-toolchain.toml<br/>channel = 1.85, edition 2024"]
    Root --> Umbrella["src/lib.rs<br/>#!forbid(unsafe_code)"]
    Root --> CI["ci.yml<br/>(GitHub Actions)"]

    subgraph Crates["crates/ (added one per change)"]
        Common["sciencekit_common"]
        Math["sciencekit_math"]
        More["... more later"]
    end

    Root -. grows into .-> Crates
    Common -. path dependency .-> Math

    subgraph Gates["CI gates"]
        Fmt["fmt"] --> Clippy["clippy -D warnings"]
        Clippy --> Test["test + doctests"]
        Test --> Ex["examples"]
        Ex --> Msrv["MSRV 1.85"]
    end
    CI --> Gates

    classDef root fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef crate fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef gate fill:#f0fdf4,stroke:#16a34a,color:#14532d
    class Root,Toolchain,Umbrella,CI root
    class Common,Math,More crate
    class Fmt,Clippy,Test,Ex,Msrv gate

The workspace root points at the toolchain (what version to use), the umbrella lib.rs (the crate that will one day re-export everything), and the CI workflow. The CI runs the five gates in order. The crates/ folder starts empty and is filled one sub-crate per change, wired together by path dependencies.

7. Recap

  • A Cargo workspace splits the library into small, isolated sciencekit_* sub-crates so each area compiles independently, keeps PRs small, and shares dependencies by path.
  • Edition 2024 is a language compatibility mode; MSRV 1.85 is a compatibility promise. rust-toolchain.toml enforces 1.85 on our machines, while rust-version in Cargo.toml announces it to the world.
  • CI is automated enforcement: the five gates (fmt, clippy -D warnings, test, examples, msrv) each catch a different failure class, and a red gate blocks the change until it is fixed.
  • The naming convention (SK / sk_, no other abbreviations) is decided now and applied to every object in every later chapter.
  • Bootstrap is the skeleton: it contains no algorithms, but every algorithm that follows stands on it.

Next chapter: with the workspace and CI in place, the first real content arrives — the shared contract vocabulary in sciencekit_common, where SKFloat, SKError, and the fundamental traits like SKEstimator begin.

Core contracts in sciencekit_common

Before any algorithm can crunch numbers, the whole library has to agree on a shared vocabulary: what a number is, what an error looks like, what a piece of data is, and what “fit” or “predict” even mean as a promise. That shared vocabulary lives in one crate, sciencekit_common. This chapter walks through the foundational traits and types every future algorithm will compile against — starting from a reader who has never seen Rust generics, traits, or even floating-point numbers.


1. The problem we were solving

Imagine a whole team of engineers each building a different algorithm: one builds a linear regression, another a decision tree, another a clustering method. If they each invent their own way to represent the data, their own error messages, and their own idea of what “fit” means, the library becomes a zoo — every algorithm speaks a different dialect, and nothing composes with anything else.

Rust makes this worse because of its philosophy of strict types. The compiler refuses to let two functions interoperate unless their types line up exactly. So the very first thing a library like this needs is not an algorithm at all — it is a contract: a set of shared building blocks that every future piece of code can agree on.

sciencekit_common is that contract. It is the crate that “freezes the vocabulary every future crate compiles against” (as its own lib.rs header says). It decides:

  • what a valid floating-point number is (SKFloat),
  • how failures are reported (SKError),
  • how feature data and target data enter an algorithm (SKDataView, SKTargetView),
  • what it means for an algorithm to fit, predict, or transform (SKSupervisedFit, SKUnsupervisedFit, SKRegressorPredictor, SKClassifierPredictor, SKFeatureTransformer).

Without this crate, sciencekit would be dozens of disconnected experiments. With it, every algorithm starts from a proven, shared foundation — like every room in a building sharing the same electrical standard and the same wall sockets.

Think of it as a plug-and-socket problem. Every appliance (algorithm) needs the same plug shape (the data-view contract), the same socket voltage (the scalar type), and the same way to tell you it broke (the error type). sciencekit_common manufactures those plugs, sockets, and fuses once, so every appliance can share a single wall.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
One sealed SKFloat trait for continuous numbersEvery generic algorithm can accept f32 or f64 through a single bound, but external crates cannot invent their own numeric types (spec scalar-typing). The private seal module enforces “only the floats we chose” at compile time.Loose bounds like Float + Send + Sync scattered everywhere — allows any third-party to satisfy the contract, which is risky and inconsistent.
Enums (SKDataView, SKTargetView) marked #[non_exhaustive]Dense vs sparse features and continuous vs integer vs nominal targets fit naturally as an either-or choice; non_exhaustive lets us add variants later without breaking consumers who match on the enum.Separate trait objects or several distinct function signatures per representation — more code, less uniform, harder to extend.
Zero-copy views, not owned copies, at public inputsThe whole point of the library is speed; borrowing the caller’s existing buffer (via ArrayView2/CsMatView) avoids duplicating huge matrices (spec data-view-boundary).Passing owned Array2 by value forces a copy and forces the caller to give up their data.
Public inputs over the TryInto conversion seamAny type that can convert into a SKDataView (including third-party types) is accepted automatically; fallible conversions report a structured SKError instead of panicking.Fixing the API to only accept ndarray/sprs types — locks out external integrators.
Central SKError enum + per-algorithm error via FromOne precise taxonomy (shape, unsupported representation, hyperparameter, convergence, I/O, conversion) shared everywhere; algorithms still get their own error type that converts from it automatically (spec error-model).Ad-hoc error types per algorithm, or a single String error — either loses precision or loses consistency.

3. The concepts, taught from zero

This chapter leans on several Rust ideas and several numerical ideas. Let’s meet each before we look at real code.

Rust concept 1: what a trait is

A trait in Rust is like an interface in other languages: a promise that a type can do certain things. When we write

#![allow(unused)]
fn main() {
trait SKFloat: Float { /* ... */ }
}

we are saying: “anything that claims to be an SKFloat must also be a Float” — that is, it must support arithmetic like +, *, .abs(), and so on. Types then implement the trait:

#![allow(unused)]
fn main() {
impl SKFloat for f32 {}
impl SKFloat for f64 {}
}

This says “the types f32 and f64 promise to be SKFloat.”

Rust concept 2: generics — writing one function for many types

A generic function is written once but works on many types. In many languages you write template <typename T>; in Rust you write <T> or, in our case, <F: SKFloat>. The colon is a bound: “F can be any type, as long as it satisfies SKFloat.”

#![allow(unused)]
fn main() {
fn scale<F: SKFloat>(value: F, factor: F) -> F {
    value * factor
}
}

This function does not care whether F turns out to be f32 or f64 — it just knows that whatever F is, it supports * and can be returned. The caller chooses the type:

#![allow(unused)]
fn main() {
let x32 = scale(2.0_f32, 3.0_f32); // F is f32
let x64 = scale(2.0_f64, 3.0_f64); // F is f64
}

Both call the same function, but the compiler produces a specialized version for each concrete type. This is called monomorphization, and it is why generics cost nothing at runtime — there is no “boxing” or dynamic lookup; it is just ordinary statically typed code, duplicated per type.

Rust concept 3: sealed traits (why only f32/f64 can be SKFloat)

A sealed trait is a trait that outsiders cannot implement. We want SKFloat to be implemented only by f32 and f64 — not by some future third-party numeric type, and certainly not by integers. Rust has no built-in “seal” keyword, so we achieve sealing with a clever trick: make the trait require a private supertrait that only we can implement.

#![allow(unused)]
fn main() {
pub trait SKFloat: Float + Send + Sync + 'static + private::SKFloatSealed {}
}

The private::SKFloatSealed supertrait lives in a private module that is not exported. Because no outside crate can even name that module, no outside crate can write impl SKFloatSealed for MyType. And since implementing SKFloat requires implementing SKFloatSealed, only the two implementations we wrote (for f32 and f64) can ever exist. The sealing is enforced at compile time, by the module system itself.

This is subtle and powerful: the constraint is not checked at runtime — it cannot even be written by anyone outside the crate. That is exactly the safety we want.

Rust concept 4: enums — a value that is one of several shapes

An enum is a type whose value is exactly one of a fixed set of possibilities. In Rust each possibility can carry its own data. For example:

#![allow(unused)]
fn main() {
pub enum SKDataView<'a, F> {
    Dense(ArrayView2<'a, F>),   // a 2-D dense matrix view
    Sparse(CsMatView<'a, F>),   // a sparse matrix view
}
}

A SKDataView value is either a dense view or a sparse view — never both. When we later match on it, we write one branch per case and the compiler guarantees we handled every possibility. #[non_exhaustive] means “there may be more variants in the future, so don’t write a match without a wildcard _ arm.”

Rust concept 5: associated types (type Model)

Some traits promise not just methods but also a type that is chosen by the implementer. This is an associated type:

#![allow(unused)]
fn main() {
pub trait SKSupervisedFit<F: SKFloat> {
    type Model;   // the fitted model type, chosen by the implementer
    fn fit<'a, X, T>(&self, features: X, targets: T) -> Result<Self::Model, Self::Error>;
}
}

Whoever implements SKSupervisedFit must say what Model is. When a linear regression implements this trait, its Model is a fitted-linear-regression struct; when a decision tree does, its Model is a fitted-tree struct. The contract of fit is fixed, but the concrete fitted type is up to each algorithm. type Error is the same idea for errors: each algorithm may pick its own error type, as long as it can be built From the central SKError.

Rust concept 6: zero-copy views vs owned arrays

This is both a Rust and a performance concept. An owned array (Array2<f64>) owns its data in memory — it is the actual box of numbers. A view (ArrayView2<'a, f64>) is like a window that looks at somebody else’s numbers without owning them. The view is tiny (a few pointers and length fields), and it borrows the underlying buffer.

The 'a is a lifetime: it says “this view is only valid for as long as the data it borrows is alive.” Rust’s borrow checker guarantees you never hold a view to data that has been freed. The lib.rs crate even forbids unsafe_code at the crate level (#![forbid(unsafe_code)]), relying entirely on safe Rust and the borrow checker for memory safety.

Creating a view is free — no elements are copied. Copying a big matrix element-by-element is exactly the kind of waste this library was built to avoid.

Rust concept 7: the TryInto conversion seam

Rust’s standard library provides two conversion traits:

  • Into<T> — an infallible conversion that cannot fail.
  • TryInto<T> — a fallible conversion that returns a Result, so it can fail.

The key insight in sciencekit is that public APIs declare their inputs over TryInto, not over a fixed concrete type. So fit does not say “give me an Array2”; it says “give me anything that can TryInto a SKDataView”:

#![allow(unused)]
fn main() {
where
    X: TryInto<SKDataView<'a, F>, Error = SKError>,
}

Because f64: Into<T> is automatically also TryInto<T> (a blanket rule in the standard library), an infallible conversion is accepted for free. And a third-party library can integrate by writing its own impl TryFrom<TheirType> for SKDataView. This makes the library open to extension at its boundaries without ever changing the core.

Rust concept 8: error handling via Result + thiserror

Rust functions that can fail return a Result<T, E> — either Ok(value) on success or Err(error) on failure. The thiserror crate makes defining good error types easy: you write the enum, and #[derive(Error)] plus #[error("...")] attributes generate the Display and source implementations for you. That is why our error enum is so readable.

Numerical concept 1: what a floating-point scalar is

Numbers like 3.14 or -0.001 with fractional parts are floating-point numbers. A computer stores them in binary as sign + exponent + mantissa (scientific notation in base 2). They are approximate — not every decimal fraction can be represented exactly. The name “float” comes from the decimal point being able to “float” to any exponent.

Numerical concept 2: why f32 vs f64

  • f32 is 32-bit single precision: smaller (4 bytes each), faster on some hardware, but stores about 7 significant decimal digits.
  • f64 is 64-bit double precision: larger (8 bytes each), slower, but stores about 15–16 significant decimal digits — the standard for scientific computing.

Machine learning often defaults to f64 for correctness in training (where repeated arithmetic accumulates error) and can use f32 for memory/throughput when accuracy is good enough. Our sealed SKFloat allows both, so a single algorithm works with either — the caller picks, and the code is generic over both. Integers, by contrast, are not allowed here: continuous algorithms need fractional values and decimal precision, which integers fundamentally lack (spec scalar-typing).

Numerical concept 3: what a “view” over data means, and why zero-copy matters

A view over data is a lens, not a copy. If you have a 10-million-element matrix and you pass a view to a function, the function sees the same underlying numbers without the cost of duplicating 10 million elements. This is the heart of zero-copy: no bytes are moved; only a lightweight descriptor travels.

Why does zero-copy matter for performance? Copying memory is slow relative to arithmetic. In a pipeline of many stages (transform → scale → train), if every stage copied its input, a matrix would be duplicated over and over — each copy costing bandwidth and time. By borrowing views all the way through, the data stays in place and only descriptors move. On very large, possibly out-of-core datasets, avoiding copies is the difference between “fits in memory” and “swaps.”

Numerical concept 4: dense vs sparse (CSR) matrices

A dense matrix stores every cell, including all the zeros, in a regular grid. It is simple and fast when most cells are nonzero.

A sparse matrix stores only the nonzero entries plus enough bookkeeping to remember where they were. CSR stands for compressed sparse row: the matrix is stored row by row, keeping (a) the values, (b) which column each value lives in, and (c) pointers marking where each row begins. If 99% of a matrix is zeros (think user–item ratings, text, networks), storing everything densely wastes memory. Sparse storage packs the same data far more compactly.

A SKDataView can be either — an algorithm that works on both gets one uniform type to match on, instead of two code paths.

Numerical concept 5: what a “target” or “label” is in machine learning

In supervised learning you have features (the input, e.g. pixel values, measurements) and a target (what you want to predict — the answer). Three flavors matter here:

  • Continuous: a real number you predict, e.g. house price → F, the model scalar (regression).
  • Integer: a whole-number target, e.g. star ratings → i64 (elevated to F on demand).
  • Nominal: a category, e.g. "cat", "dog", "bird" → strings (classification).

SKTargetView is the single type that holds any of these three. Unsupervised algorithms (e.g. clustering) have no targets at all — which is exactly why SKUnsupervisedFit::fit takes only features.


4. Each object, explained

SKFloat (the sealed floating-point bound)

What it is: The single trait that says “this type is a valid continuous number for sciencekit.” It is Float + Send + Sync + 'static + private::SKFloatSealed, implemented only for f32 and f64. Send + Sync + 'static mean the value can be moved across threads and lives forever (needed because algorithms may run in parallel).

Why it exists: Every generic algorithm needs a numeric bound, and having exactly one guarantees consistency (spec scalar-typing). Send + Sync + 'static ensure a value of type F is thread-transferable, which future parallel algorithms depend on.

What we rejected: A scatter of loose bounds on every function, and allowing third-party numeric types. Sealing locks the surface so only our two floats are valid.

private::SKFloatSealed (the private seal — non-public but essential)

What it is: A hidden supertrait, #[doc(hidden)], defined in a private module, with implementations only for f32 and f64.

Why it exists: It is the mechanism that seals SKFloat. Because the module is private, outsiders cannot name the trait, so they cannot implement it, and therefore cannot implement SKFloat. This is the compile-time guarantee behind the whole scalar contract.

What we rejected: Language-level sealed keywords don’t exist in Rust; this module trick is the idiomatic, documented way to achieve sealing.

SKError (the central error taxonomy)

What it is: A #[non_exhaustive] enum, derived with thiserror, with eight variants: ShapeMismatch, UnsupportedRepresentation, InvalidHyperparameter, ExecutionModeIncompatible, BatchBufferOversize, NotConverged, Io, and Conversion. Each carries precise data (e.g. expected/found shapes, iteration counts, byte counts) and a readable Display message.

Why it exists: One shared taxonomy means the same failure means the same error everywhere (spec error-model). The #[from] io::Error variant lets platform I/O errors convert in automatically; #[non_exhaustive] lets us grow the enum without breaking consumers.

What we rejected: Ad-hoc error types per algorithm and plain String errors — both lose precision or consistency. Convenience constructors like SKError::shape_mismatch_2d and SKError::not_converged exist to keep call sites tidy.

SKDataView (the zero-copy feature view)

What it is: A #[non_exhaustive] enum over the two feature representations: Dense(ArrayView2<'a, F>) and Sparse(CsMatView<'a, F>). Both are views — they borrow the caller’s data. It derives Debug, Clone, Copy.

Why it exists: One uniform type for “the input features,” whether dense or sparse, enables a single dispatch per operation (spec data-view-boundary). The .representation() method returns "dense"/"csr" for one-time dispatch and diagnostics; .as_dense() returns the dense view or rejects a sparse input before processing any element.

What we rejected: Passing owned arrays (forces copies) and separate functions per representation (duplication, no uniformity). #[non_exhaustive] keeps room for future variants.

Representation parity: dense, sparse and mixed inputs

Having one type for both representations is only half the story. The other half is a rule about what an algorithm does with it — and that rule is representation parity (spec data-view-boundary, PRD §4.5.1).

The rule has three parts:

  1. Parity. An algorithm that mathematically tolerates more than one representation accepts dense, sparse and mixed dense/sparse inputs on every public operation. The same logical matrix, supplied densely or as CSR, produces the same result within the documented tolerance.
  2. One dispatch, no densification. The algorithm looks at SKDataView::representation() once per operation and follows that path to the end. It never materialises a dense copy of a sparse input — that would defeat the entire point of sparse storage.
  3. Two-matrix operations cover all four combinations. dense×dense, sparse×sparse, sparse×dense and dense×sparse agree, after shapes are validated before any element is touched.

Some mathematics, however, genuinely wants dense geometry: a k-d tree stores axis-aligned boxes, a ball tree stores centres and radii — neither has a meaningful sparse form. For those, the spec allows a dense-only exception, but only under three conditions: the kernel rejects a sparse view before processing any element with UnsupportedRepresentation and a suggestion; the estimator built on it still serves dense, sparse and mixed input through a documented alternative path (typically a brute-force searcher over the stored training features); and the change proposal explains why the mathematics needs dense geometry and names that path.

flowchart TD
    accTitle: Representation parity dispatch
    accDescr: An operation receives dense, sparse or mixed input and dispatches on the representation once. A tolerant algorithm takes the dense or sparse path and never densifies. An algorithm that needs dense geometry rejects sparse input with UnsupportedRepresentation before processing any element, and the estimator falls back to a documented alternative path such as brute force over the stored features. Every path ends in the same result within tolerance.
    A["Public operation receives<br/>dense, sparse or mixed input"] --> B{"representation()<br/>once per operation"}
    B -->|dense| C["Dense path<br/>(tree index, dense kernel)"]
    B -->|sparse| D{"Does the math<br/>require dense geometry?"}
    D -->|no| E["Sparse path<br/>never densify"]
    D -->|yes| F["UnsupportedRepresentation<br/>before processing any element"]
    F --> G["Estimator alternative path<br/>(brute force over stored features)"]
    C --> H["Same result within tolerance"]
    E --> H
    G --> H
    classDef entry fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef tolerant fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef reject fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A,B entry
    class C,E,G tolerant
    class D,F reject
    class H result

The diagram reads as follows: whatever representation arrives, the operation dispatches once. A tolerant algorithm takes the dense or sparse path directly and never densifies. An algorithm that needs dense geometry rejects sparse immediately, and the estimator above it falls back to the documented alternative path so the user still gets parity.

Why we wrote the rule down instead of leaving it implicit: every new algorithm change would otherwise re-decide the policy, and a silent .to_dense() inside a kernel is invisible in review. The rule lives in the data-view-boundary capability, is restated in PRD §4.5, and is part of the AGENTS.md code conventions so planners and implementers see it before they write code.

What we rejected: “accept what you can, densify the rest” (silently breaks the memory promise on wide sparse matrices) and “dense-only everywhere” (throws away the sparse support that lasso, linear SVMs and text classification depend on).

SKModelState (the format-agnostic export contract)

What it is: Everything a format adapter needs to persist a fitted model: an SKModelMetadata (estimator name, format version, feature count, class labels, hyperparameters) plus a deterministic BTreeMap<String, SKTensor<F>> of named tensors — the learned arrays.

Why it exists: Waves 7 and beyond export models to safetensors, ONNX and a JSON debug format. If each format crate invented its own container, every estimator would need one export method per format. Instead the model describes its state once, and each format crate serializes that state. SKExportable produces it, SKImportable consumes it, and sk_validate_import_metadata checks the identity triple before any tensor is trusted: an importer validates estimator and version first, reads the tensors, then confirms the feature count against the metadata.

The two design rules that matter:

  1. Names are stable and unique. A tensor is addressed by a stable dotted name such as linear.coefficients, not by array position. Reordering an internal struct must not silently change the file format. Construction rejects duplicate names; BTreeMap gives a deterministic order, so the same model always yields the same tensor order, so two adapters written against the same release see the same layout.
  2. No serde in the contract. The contract is plain Rust values. serde would couple the core crate to one serialization model and make the state of a model depend on a derive; the format crates own their encodings. This keeps sciencekit_common dependency-light and lets ONNX (protobuf), safetensors (a header plus a raw buffer) and JSON each do the right thing.
flowchart TD
    accTitle: One model state, several format adapters
    accDescr: A fitted model exports an SKModelState made of metadata and uniquely named tensors. The safetensors, ONNX and JSON debug formats each serialize that same state. Import validates the estimator name, format version and feature count before rebuilding the model, so no format needs its own export method per estimator.
    M["Fitted model"] -->|"SKExportable::export_state"| S["SKModelState<br/>metadata + named tensors"]
    S --> A["Safetensors adapter"]
    S --> O["ONNX adapter"]
    S --> J["JSON debug adapter"]
    A --> I["SKImportable::import_state"]
    O --> I
    J --> I
    I --> V["Validate estimator, version<br/>and feature count"]
    V --> R["Rebuilt model"]
    classDef model fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef state fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef format fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#4c1d95
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class M model
    class S,V state
    class A,O,J,I format
    class R result

Test walk-through: interop_traits_round_trip_preserves_predictions

The reference model in interop/mock_model.rs is a tiny linear scorer (x·coefficients + intercept). The test fits nothing: it builds the model directly, exports its state, imports it back and asserts that both score the same rows identically. That is the whole point of the contract — the state must carry all learned information, not just the arrays that happened to be convenient. A companion test, interop_traits_export_preserves_class_labels, proves the class table survives the round trip, and the validation tests prove a foreign state is rejected before it can be mistaken for this model.

Validation is deliberately split: a wrong estimator or format version is an UnsupportedRepresentation (this state describes something else), a feature-count disagreement is a ShapeMismatch (right model, wrong shape), and a missing required tensor is an InvalidHyperparameter (the state is malformed for this estimator).

SKClusterLabel (typed cluster assignments: a label that knows what noise is)

Clustering has a problem the other predictors do not: a clusterer’s output is not a number you can round into an index. KMeans returns cluster 0, 1, 2…, but DBSCAN can declare a point noise — it belongs to no cluster at all. Storing noise as -1 inside a usize is impossible; storing it as a sentinel inside an i64 works until someone genuinely needs cluster -1 or forgets to check the sentinel. The contract therefore makes the distinction part of the type:

#![allow(unused)]
fn main() {
pub enum SKClusterLabel {
    Cluster(SKClusterIdentifier),
    Noise,
}
}

SKClusterIdentifier stores index + 1 in a NonZeroU32. That single decision buys two properties. First, cluster 0 is representable (the stored value is 1), so the common case does not need a special value. Second, the zero bit pattern inside NonZeroU32 is a niche: the compiler reuses it to encode the Noise variant, so the whole enum is four bytes — the same size as a bare u32 — with no sentinel and no possibility of collision.

flowchart LR
    accTitle: Cluster index stored through a NonZeroU32 niche
    accDescr: A public cluster index is shifted by one and stored in a NonZeroU32. Cluster 0 stores 1, cluster 7 stores 8. The unused zero pattern is the niche that encodes the Noise variant, so the label is four bytes and a cluster can never collide with noise.
    A["Public index<br/>0, 1, 7, …"] -->|"+ 1"| B["NonZeroU32<br/>1, 2, 8, …"]
    B --> C["Cluster(index) variant"]
    Z["Zero bit pattern<br/>(a niche)"] --> N["Noise variant"]
    C --> S["SKClusterLabel<br/>4 bytes total"]
    N --> S
    classDef public fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef stored fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef niche fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A public
    class B,C stored
    class Z,N niche
    class S result

The external world, however, uses the i64 convention: scikit-learn and most file formats write noise as -1 and a cluster as its non-negative index. to_i64 and from_i64 translate at the boundary only, which is why the type is called typed rather than plain: -1 becomes Noise, non-negative values become clusters, and anything below -1 is rejected with a structured error instead of inventing a cluster that no model produced.

Two more pieces complete the contract. SKClustererPredictor<F> is the model-side trait — the same TryInto<SKDataView> seam as the other predictors, so dense and CSR batches share one entry point — and sk_validate_cluster_assignments is the single shape check that the unsupervised scorer uses, so “one label per row” is defined once. Unlike a regressor, the scorer bound is now M: SKClustererPredictor<F>: it obtains typed assignments and never rounds a continuous response. A scorer that meets noise documents whether it excludes or rejects those rows, and never treats noise as a cluster.

SKTargetView (the zero-copy target view)

What it is: A #[non_exhaustive] enum over three target representations: Continuous(ArrayView1<'a, F>), Integer(ArrayView1<'a, i64>), and Nominal(&'a [&'a str]). Also derives Debug, Clone, Copy.

Why it exists: Supervised algorithms need a single type for “the answers” that covers regression (continuous), integer targets, and classification (nominal). .as_continuous() elevates continuous or integer targets to the model scalar F (exact while the value is representable in F) and rejects nominal with a clear suggestion.

What we rejected: Separate per-kind target arguments (forces the caller to know the kind up front) and forcing nominal text to be copied (we borrow the strings instead — spec data-view-boundary).

SKSupervisedFit (the supervised fit contract)

What it is: A trait with associated Model and Error types whose fit(&self, features, targets) takes both features and targets, each declared over the TryInto seam, and returns Result<Self::Model, Self::Error>.

Why it exists: It is the promise every supervised estimator keeps: given features and targets, produce a fitted model (spec estimator-contracts). Taking &self keeps the configured estimator unchanged and reusable.

What we rejected: Returning the learned state on the estimator itself (that would let you predict before fitting and prevent concurrent fits). The model is a separate type.

SKUnsupervisedFit (the unsupervised fit contract)

What it is: A trait with associated Model and Error types whose fit(&self, features) takes only features and returns Result<Self::Model, Self::Error>.

Why it exists: Clusterers and other unsupervised algorithms have no targets; making the signature lack targets makes it impossible to pass them (compile-time rejection). Taking &self keeps the estimator immutable and reusable, including concurrent fits.

What we rejected: Reusing one fit trait with an optional/ignored target parameter — that would let callers pass meaningless targets and lose the type-level guarantee.

SKRegressorPredictor (the regressor prediction contract)

What it is: A trait generic over F: SKFloat with an associated Error whose predict(&self, features) returns Result<ndarray::Array1<F>, Self::Error> over the TryInto seam.

Why it exists: Prediction lives on the fitted model, never on the configured estimator (spec estimator-contracts). That makes “predict before fit” a compile-time error. predict returns a dense Array1<F> — responses in the same scalar the model was fitted on, so an f32 pipeline never pays an f64 detour.

What we rejected: A single f64-only predict for every model. It forced an upcast on every f32 prediction and a cast back to chain the next stage — and it encoded class labels as floats (0.0/1.0), which is a lie of a type.

SKClassifierPredictor (the classifier prediction contract)

What it is: A trait generic over F: SKFloat with an associated Error whose predict_labels(&self, features) returns Result<ndarray::Array1<i64>, Self::Error> and whose predict_probabilities(&self, features) returns Result<ndarray::Array2<F>, Self::Error>, both over the TryInto seam.

Why it exists: Classifier outputs are labels, not floats. Labels are canonical i64 indices — independent of the feature scalar, so f32 and f64 runs agree exactly — while probabilities preserve the model scalar F.

What we rejected: Putting predict_labels on the estimator type. That would break the “cannot predict before fitting” guarantee and the shared model across threads.

SKFeatureTransformer (the feature-transformer contract)

What it is: A trait with associated Output and Error types whose transform(&self, features) returns Result<Self::Output, Self::Error> over the TryInto seam.

Why it exists: Transformers (e.g. scalers) need a typed Output so pipelines can check at compile time that one stage’s output feeds the next stage’s input (spec estimator-contracts). The associated type makes incompatible chaining fail early.

What we rejected: Returning an untyped or fixed output — that would push type compatibility checking to runtime.

Here is the whole family at a glance:

flowchart TD
    accTitle: The sciencekit_common vocabulary at a glance
    accDescr: Numbers, data views and errors feed the fit traits on the estimator and the prediction and transform traits on the fitted model.
    COMMON[sciencekit_common] --> NUM[numbers]
    COMMON --> DATA[data and errors]
    NUM --> FL[SKFloat sealed: f32, f64]
    FL --> SEAL[SKFloatSealed private seal]
    DATA --> ERR[SKError enum]
    DATA --> DV[SKDataView: Dense or Sparse]
    DATA --> TV[SKTargetView: Continuous, Integer or Nominal]
    TV --> SF[SKSupervisedFit: features plus targets]
    DV --> SF
    DV --> UF[SKUnsupervisedFit: features only]
    SF --> RP[SKRegressorPredictor on the model]
    SF --> CP[SKClassifierPredictor on the model]
    UF --> M[model type]
    DV --> RP
    DV --> CP
    RP --> FT[SKFeatureTransformer: transform]

    style COMMON fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style NUM fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
    style DATA fill:#fef3c7,stroke:#d97706,color:#78350f
    style SF fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style UF fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style RP fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style CP fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style FT fill:#f0fdf4,stroke:#16a34a,color:#14532d

5. A real walk-through, using the tests

The most convincing way to learn is to read actual tests that passed. Here are three real tests from data_view_tests.rs and sk_float_tests.rs.

Test 1: borrowed_dense_enters_without_copying

This test proves the zero-copy promise: a dense matrix enters the library without copying.

#![allow(unused)]
fn main() {
#[test]
fn borrowed_dense_enters_without_copying() {
    let data = Array2::from_shape_vec((2, 2), vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let view: SKDataView<'_, f64> = ArrayView2::from(&data).try_into().unwrap();
    match view {
        SKDataView::Dense(v) => {
            assert_eq!(v.as_slice_memory_order().unwrap(), &[1.0, 2.0, 3.0, 4.0]);
        }
        other => panic!("expected dense, got {other:?}"),
    }
}
}

Line by line:

  1. let data = Array2::from_shape_vec((2, 2), vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap(); — we build an owned 2×2 dense matrix (2 rows, 2 columns) holding the four values 1.0, 2.0, 3.0, 4.0. The _f64 suffix says the numbers are 64-bit floats. .unwrap() unwraps the Result; here it cannot fail.
  2. let view: SKDataView<'_, f64> = ArrayView2::from(&data).try_into().unwrap(); — first we make a view of data (borrowing it, no copy), then we ask to convert it into a SKDataView. The '_ lifetime says “this view is valid for as long as data lives.” The conversion is the TryFrom<ArrayView2> impl we saw — it just wraps the view as SKDataView::Dense. No elements are copied.
  3. match view { ... } — we check which variant we got. Since we handed it a dense view, we expect SKDataView::Dense(v).
  4. assert_eq!(v.as_slice_memory_order().unwrap(), &[1.0, 2.0, 3.0, 4.0]); — we confirm the dense view exposes exactly the four original values, in the same order. The other => panic! arm catches the (impossible here) case where it came back sparse.

The lesson: the same buffer data is reused; the test’s very name asserts no copy was made.

Test 2: dense_only_consumer_rejects_sparse_precisely

This test proves that an algorithm supporting only dense data rejects a sparse input with a precise error, before touching any element.

#![allow(unused)]
fn main() {
#[test]
fn dense_only_consumer_rejects_sparse_precisely() {
    let csr = CsMat::new_csc((2, 2), vec![0, 0, 0], vec![], Vec::<f64>::new());
    let view: SKDataView<'_, f64> = csr.view().try_into().unwrap();
    let dense_result = view.as_dense();
    match dense_result {
        Err(SKError::UnsupportedRepresentation { representation, .. }) => {
            assert_eq!(representation, "csr");
        }
        other => panic!("expected unsupported-representation, got {other:?}"),
    }
}
}

Line by line:

  1. CsMat::new_csc((2, 2), vec![0, 0, 0], vec![], Vec::<f64>::new()) — build a 2×2 sparse matrix with no stored values (an empty sparse matrix). Note the new_csc here really produces a sparse matrix in the sprs crate’s row-compressed form usable as CSR.
  2. let view: SKDataView<'_, f64> = csr.view().try_into().unwrap(); — take a view of the sparse matrix and convert it through the same seam. This time it becomes SKDataView::Sparse(...).
  3. let dense_result = view.as_dense(); — we simulate a dense-only algorithm calling the dispatch method. Since the view is sparse, as_dense() returns an Err.
  4. The match checks that the error is exactly SKError::UnsupportedRepresentation with representation == "csr" — not a vague shape error. This matches the spec: “the operation fails before processing any element, with an error indicating the mismatch and the suggested conversion path.” The other => panic! arm catches any wrong error kind.

The lesson: representation errors are precise and distinct from shape errors, and they happen up front — never after a wasted pass over the data.

Test 3: native_floats_satisfy_the_contract

This test proves the sealed SKFloat works for both supported floats, through a generic function.

#![allow(unused)]
fn main() {
#[test]
fn native_floats_satisfy_the_contract() {
    let x32 = scale(2.0_f32, 3.0_f32);
    assert_eq!(x32, 6.0_f32);

    let x64 = scale(2.0_f64, 3.0_f64);
    assert_eq!(x64, 6.0_f64);
}
}

The helper scale is defined just above it:

#![allow(unused)]
fn main() {
fn scale<F: SKFloat>(value: F, factor: F) -> F {
    value * factor
}
}

Line by line:

  1. fn scale<F: SKFloat>(value: F, factor: F) -> F — a generic function over F, bounded by SKFloat. It takes two values and returns one, all of type F.
  2. value * factor — the body uses *. This compiles only because SKFloat: Float guarantees multiplication exists. The function never needs to know whether F is f32 or f64.
  3. In the test, scale(2.0_f32, 3.0_f32) instantiates F = f32 and yields 6.0_f32; scale(2.0_f64, 3.0_f64) instantiates F = f64 and yields 6.0_f64. Both assert_eq! checks pass.

The companion test integers_do_not_satisfy_the_contract documents the other side: i32 does not implement SKFloat, so calling a continuous function with an integer is a compile-time error. And floats_are_thread_transferable asserts f32/f64 are Send + Sync + 'static, guaranteeing they can cross thread boundaries — the basis for future parallel algorithms.


6. Look inside

One strong insight: the entire sciencekit_common vocabulary is engineered around type-level safety. Sealing SKFloat, keeping predict off the estimator, making the fit traits reject missing targets at compile time, and using TryInto for an open conversion seam — all of these push mistakes out of the running program and into the compiler, where they are caught for free, before anything executes.

Here is how the fit/predict/transform contracts relate to the estimator, the model, and the data views:

flowchart TD
    accTitle: The fit, predict and transform contracts and their shared inputs
    accDescr: The configured estimator carries SKSupervisedFit and SKUnsupervisedFit, which take features and targets and produce a fitted model. The fitted model carries SKRegressorPredictor for continuous responses in the model scalar, SKClassifierPredictor for scalar-independent integer labels plus scalar-preserving probabilities, and SKFeatureTransformer. All of them consume SKDataView and SKTargetView, and all report errors through SKError.
    subgraph est[Configured estimator - immutable, reusable]
        SF[SKSupervisedFit] -->|fit features + targets| M1(Model type)
        UF[SKUnsupervisedFit] -->|fit features only| M2(Model type)
    end

    subgraph model[Fitted model - sole bearer of learned state, thread-shareable]
        RP[SKRegressorPredictor] -->|predict features| OUT[Array1 F]
        CP[SKClassifierPredictor] -->|predict labels| OUTL[Array1 i64]
        CP -->|predict probabilities| OUTP[Array2 F]
        FT[SKFeatureTransformer] -->|transform features| OUT2[Output type]
    end

    DV["SKDataView: Dense or Sparse"] --> SF
    DV --> UF
    DV --> RP
    DV --> CP
    DV --> FT
    TV["SKTargetView: Continuous, Integer or Nominal"] --> SF

    ER[SKError] --> SF
    ER --> UF
    ER --> RP
    ER --> CP
    ER --> FT

    style est fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style model fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style DV fill:#fef3c7,stroke:#d97706,color:#78350f
    style TV fill:#fef3c7,stroke:#d97706,color:#78350f
    style ER fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

The diagram shows the two halves of the system: the estimator side (which fits) and the model side (which predicts/transforms). The fitted model is deliberately a separate type from the estimator, and both depend only on the shared data views and the central error.


7. Which float should I use?

Both f32 and f64 satisfy SKFloat, and a model fitted on one predicts in the same one — the scalar flows end to end with no implicit cast. The choice is a trade-off:

  • f32 halves memory traffic and doubles throughput on SIMD and GPU kernels, which is what out-of-core and large-batch workloads want. Prefer it unless you need the extra precision.
  • f64 keeps roughly 15–16 decimal digits of precision for ill-conditioned solves and long accumulations. Prefer it when numerical stability dominates.

A pipeline carries a single scalar: every stage agrees on F, so mixing an f32 stage into an f64 pipeline fails at compile time until an explicit cast stage bridges them.

Migration note

Before this change, predict returned Array1<f64> and continuous targets were ArrayView1<f64> regardless of the feature scalar. After it, regressor predictions and continuous targets use Array1<F>/ArrayView1<F>, and classifier labels are Array1<i64> instead of float-encoded indices. Call sites that assumed f64 update to the model scalar F; classifiers switch from comparing floats to comparing label indices.


8. Recap

  • SKFloat is sealed — only f32 and f64 are valid continuous numbers, enforced at compile time by a private supertrait (private::SKFloatSealed).
  • Predictions preserve the model scalar — regressors return Array1<F>, classifiers return Array1<i64> labels plus Array2<F> probabilities; continuous targets are SKTargetView::Continuous(ArrayView1<F>).
  • SKError is one precise taxonomy — shape, unsupported representation, hyperparameter, execution mode, batch overflow, convergence, I/O, and conversion — built with thiserror, #[non_exhaustive], and automatic From conversion into per-algorithm errors.
  • Data enters through zero-copy views — SKDataView (dense/sparse) and SKTargetView (continuous/integer/nominal) borrow the caller’s buffers rather than copying them, which is the heart of the performance promise.
  • Public inputs are declared over TryInto — any type that can convert into a view is accepted, making the library open to third-party integration without breaking.
  • Fit, predict, and transform are separate contracts — SKSupervisedFit and SKUnsupervisedFit split by supervision; SKRegressorPredictor, SKClassifierPredictor, and SKFeatureTransformer live on the model type, making “predict before fit” a compile-time error.

Next chapter: now that we have the shared vocabulary of numbers, errors, and data views, we can look at how an actual algorithm puts it to work — fitting a model and predicting on new data using these very contracts.

sciencekit_math: kernels, distances and the BLAS interface

Every machine-learning algorithm, from linear regression to clustering to a support-vector machine, is at its heart just arithmetic done very, very fast over big tables of numbers. Before sciencekit could train its first model, it needed a solid numeric engine — a crate that knows how to walk every element of a table, how to measure how far apart two rows are, how to multiply a sparse matrix by a dense one, and how to outsource the heaviest algebra to a tuned library. That engine is sciencekit_math. This chapter opens it up from the very beginning: first the Rust ideas it leans on, then the math, then the real objects and the real tests that prove they work.


1. The problem we were solving

Imagine you are teaching a machine to tell apart two types of flowers by measuring their petal lengths and widths. You store the measurements as a table: each row is one flower, each column is one measurement (a “feature”). To build most models you must do three kinds of work on such a table:

  1. Transform every number. Normalize a column so every value sits between 0 and 1, or scale every value by some constant.
  2. Summarize. Add up a column, or the whole table.
  3. Measure similarity. “How far apart are these two flowers?” — the heart of clustering and nearest-neighbor methods.

That sounds simple, but doing it well is a performance minefield. A realistic dataset has millions of rows. If you loop over every element by hand, one by one, in the slowest way, even a tiny model takes ages. And the algorithms downstream don’t want to care how the arithmetic is done — they just want a number back.

The bigger problem is the heavy algebra. Models routinely need things like the inverse of a matrix, eigenvalues, or a singular-value decomposition — the “H-bombs” of linear algebra. Writing those from scratch is both slow and error-prone. Professional libraries have spent decades tuning them. But pulling in the traditional C/Fortran implementations (“system BLAS”) means the library will not even compile on a machine without a C toolchain — a heavy burden for a pure-Rust project.

So sciencekit_math had to solve two things at once:

  • a fast, reusable set of small operations (the “kernels”) written the Rust way — with zero copying and parallelism — that downstream algorithms call like building blocks; and
  • a single clean door (an interface) through which all the heavy algebra passes, so that today it uses a pure-Rust implementation and tomorrow, if a user enables it, a blazing system BLAS — without changing a single line of algorithm code.

The rest of this chapter is the story of how those two pieces were built and why they look the way they do.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Higher-order kernels via azip!/par_azip!, never manual index loopsThe PRD (§4.2) mandates higher-order iteration. Passing the operation as a closure (`x
Squared-Euclidean distance via the norm expansion $|a|^2 - 2a \cdot b + |b|^2$Expanding the square avoids a per-pair subtract loop, reuses a SIMD-friendly dot product over contiguous row memory, and is symmetric with a stable diagonal (spec pairwise-distances).The literal $\sum (a_k - b_k)^2$ loop per pair — correct but slower and harder to vectorize.
Pure-Rust faer as the default BLAS/LAPACK backendA pure-Rust implementation compiles anywhere with no C/Fortran toolchain, which the PRD requires as the default (spec blas-interface, Decision 1). faer compiles on the project’s Rust 1.85.oxiblas — a competing pure-Rust BLAS, rejected because it fails to compile on Rust 1.85.
The blas-backend feature as an opt-in escape hatchUsers who want the fastest possible system BLAS (OpenBLAS/BLIS/MKL/Accelerate) can enable a feature flag to swap faer for ndarray-linalg; faer stays available as a fallback (spec blas-interface).Linking a system BLAS always — would make the default build fail on machines without one.
Sparse products over zero-copy CsMatView, never densifyingLasso, linear SVMs and text classification operate on very sparse matrices (mostly zeros); copying them into dense form would waste memory (spec dense-sparse-products). The CSR×dense kernel walks only the non-zero entries.Turning the sparse input into a dense array and using a normal multiply — simple but memory-hostile for sparse data.

3. The concepts, taught from zero

This chapter needs a handful of Rust ideas and a handful of mathematical ones. Let’s meet them gently before touching any real code.

Rust concept 1: closures — functions you can hand around

In Rust you can write a small function “in place,” inline, right where you need it. Such an anonymous function is called a closure. You have already seen them in this book’s earlier chapters (|x| 2.0 * x + 1.0). The key superpower of a closure is that you can pass it as an argument to another function.

#![allow(unused)]
fn main() {
// `transform` is a parameter that is itself a function: it takes an F and returns an F.
pub fn sk_elementwise_transform<F: SKFloat>(
    input: &ArrayView<F, ndarray::Ix1>,
    transform: impl Fn(F) -> F + Sync + Send,
    parallelism: usize,
) -> Array<F, ndarray::Ix1>
}

Read the middle parameter type: impl Fn(F) -> F + Sync + Send. Fn is the Rust name for “this is a callable thing,” and (F) -> F says it takes one value of type F and returns one. So sk_elementwise_transform is a generic worker: it does not know what the operation is — the caller supplies the operation as a closure, and the worker applies it to every element. This is the essence of a higher-order function: a function that takes or returns other functions. It separates “what computation” (the closure, chosen by the caller) from “how to sweep the array” (the kernel, written once). The + Sync + Send bits are promises that the closure can be shared across threads — which we need when we parallelize.

Rust concept 2: azip! and par_azip! — elementwise iteration done right

The whole library refuses to write for i in 0..n manual index loops for elementwise work. Instead it uses the ndarray macros azip! and par_azip!, which iterate element-by-element across one or more arrays in lockstep, element 0 with element 0, element 1 with element 1, and so on. Look at the body of the transform:

#![allow(unused)]
fn main() {
azip!((out in &mut output, a in input) { *out = transform(*a); });
}

This says: “walk input and output together; for each pair, put transform(*a) into *out.” The macro handles the striding and indexing for you. par_azip! does the same thing in parallel — it splits the work across a thread pool. Because both macros share the exact same body syntax, you get parallelism almost for free: the only change between the sequential and parallel versions is the macro name.

Rust concept 3: owned arrays vs zero-copy views

An owned array, Array<F, Ix2>, owns its numbers in memory — it is the sole holder and can resize, mutate, or be dropped. A view, ArrayView2<F>, does not own data; it is a “window” that borrows someone else’s owned array, remembering the shape and how to reach each element. Views are the library’s secret to speed: a function can take a view of your existing buffer, do work, and hand you an answer — without ever copying your data. Copying a matrix of a million rows is expensive; borrowing a view of it is essentially free. That is why every public kernel here takes &ArrayView2<F> (a borrow of a view) and only returns a fresh owned Array2<F> when it genuinely needs a new result.

Rust concept 4: traits and a trait-object-free generic backend

A trait is a promise that a type can do certain things (an interface). Here the central trait is SKMathBackend:

#![allow(unused)]
fn main() {
pub trait SKMathBackend<F: SKFloat>: Send + Sync {
    fn gemm(&self, a: ArrayView2<F>, b: ArrayView2<F>, alpha: F, parallelism: usize) -> Array2<F>;
    fn svd(&self, a: ArrayView2<F>) -> Result<SKSingularValueDecomposition<F>, SKError>;
    // ... more: qr, cholesky, solve, eigh, lu, ...
}
}

Any type that impls this trait is a “math backend”: it promises to perform GEMM (matrix multiplication), SVD, QR, and so on. The trick here is that the trait is generic over F and the concrete backend type is known at compile time — the caller writes let backend = SKFaerBackend::new(); and then calls backend.gemm(...). Because the concrete type is fixed, the compiler generates a direct, specialized call. This is the opposite of a trait object (a Box<dyn SKMathBackend>), which would defer the choice to runtime and pay for a dynamic dispatch on every call. For a performance crate, avoiding that indirection — “trait-object-free” — is deliberate: heavy algebra runs on hot paths where an extra virtual call per operation would add up.

Numerical concept 1: what a “kernel” is

In numerical libraries a kernel is a small, reusable operation applied over an array or matrix. We meet three families:

  • Elementwise transform — a function applied to every element independently: x → 2x + 1. Input and output have the same shape.
  • Reduction — collapse many values into fewer (often one): a sum turns a column into a single number.
  • In-place transform — mutate the existing buffer rather than allocate a new one, saving memory.

The sciencekit_math kernels are the “LEGO bricks” that downstream algorithms snap together.

Numerical concept 2: what a distance matrix is, and squared-Euclidean math

A distance matrix is a table where entry [i, j] is “how far apart are row i of the first set and row j of the second set.” Each row of a matrix is a point in multi-dimensional space (here, one point per flower).

The Euclidean distance between two points $a$ and $b$ is the length of the straight line between them: $\sqrt{\sum (a_k - b_k)^2}$. Its square is $\sum (a_k - b_k)^2$. Computing that literally means subtracting each coordinate pair. But algebra gives us a shortcut by expanding the square:

$$ |a - b|^2 = \sum (a_k - b_k)^2 = \sum (a_k^2 - 2 a_k b_k + b_k^2) = |a|^2 - 2(a \cdot b) + |b|^2 $$

where $|a|^2 = \sum a_k^2$ (the squared “length” of $a$) and $a \cdot b = \sum a_k b_k$ is the dot product of $a$ and $b$. Why bother? Because we can precompute $|a|^2$ for every row once, and $|b|^2$ for every row of the other set once, and then each cell only needs one dot product — a tight, SIMD-friendly loop over contiguous memory. This is the norm-expansion formulation the spec mandates, and it is the whole reason sciencekit_math computes distances this way.

Numerical concept 3: cosine and Manhattan distances

Cosine distance measures the angle between two points rather than their distance. The cosine of the angle between $a$ and $b$ is $\frac{a \cdot b}{|a| , |b|}$. If the vectors point the same way the cosine is $1$; if they are perpendicular (orthogonal) it is $0$. Distance is then defined as $1 - \text{cosine}$, so identical directions score $0$ and orthogonal directions score $1$. Nice property: cosine distance is scale-invariant — $[1,2]$ and $[10,20]$ point the same way, so their cosine distance is $0$.

Manhattan distance (also called L1) is the distance you would walk along a city grid — only left/right and up/down, no diagonals: $\sum |a_k - b_k|$. It is the sum of the absolute coordinate differences.

Numerical concept 4: sparse data and the CSR format

A matrix is sparse when most of its entries are zero — think of text classification, where each row is a document and each column says “how many times word X appeared.” Storing all those zeros as real numbers wastes memory and time. The CSR (Compressed Sparse Row) format stores only the non-zero values, in three parallel lists:

  • the non-zero values themselves,
  • the column each value belongs to,
  • a pointer array that says where each row begins.

To multiply a CSR matrix by a dense matrix, you only touch the non-zero entries — no need to ever build a big dense matrix full of zeros. sciencekit_math consumes CSR through a view (CsMatView) so even the sparse input is never copied.

Numerical concept 5: C vs F memory contiguity

A matrix is stored in memory as a long list of numbers. Row-major (C) order lays out each row back-to-back; column-major (F) order lays out each column back-to-back. Most languages default to row-major (the “C” convention); Fortran-derived libraries default to column-major (“F”). For a hot loop it matters a lot which layout a buffer has, because CPUs love reading memory that is sequential. A contiguous buffer (all elements one after another) is much faster to sweep with SIMD than a strided one. So the layout helpers detect which case we are in and, when a kernel needs contiguous memory, produce a contiguous copy only when necessary — borrowing when already contiguous (zero copy) and owning a fresh copy only when strided.

Numerical concept 6: what BLAS and LAPACK are

BLAS (Basic Linear Algebra Subprograms) is a de-facto standard set of routines for vector and matrix arithmetic — the crown jewel being GEMM, the general matrix multiplication $C = \alpha \cdot A \cdot B$. LAPACK builds on BLAS to provide the higher-level decompositions: SVD, QR, Cholesky, LU, eigenvalues, least squares. For decades these have been hand-tuned in C/Fortran (OpenBLAS, Intel MKL, and so on) to be staggeringly fast. The catch: they need a native C toolchain to compile. sciencekit_math solves this by defining its own SKMathBackend interface and letting the default implementation be faer, a modern pure-Rust BLAS/LAPACK — fast, and compiles anywhere Rust does.


4. Each object, explained

SKMathBackend (the dense algebra trait)

What it is: The single host-centric interface for all heavy dense algebra. It is a trait generic over SKFloat, whose methods take zero-copy ArrayView2 inputs and return owned Array2 results. The surface spans gemm, svd, qr, cholesky, solve_triangular, solve, eigh, lu, slogdet, pinv, inv, lstsq, and norm/vector_norm. It also has default implementations: for example slogdet is derived from LU, pinv and lstsq are composed from an SVD, and norm reduces host-side — so a backend can implement only the primitives and still get everything else for free.

Why it exists: Downstream algorithm crates must not care which library does the heavy algebra. They call methods on the trait; swapping faer for ndarray-linalg (under the blas-backend feature) is a config change, not a rewrite (spec blas-interface). The zero-copy views on input keep the promise of not copying the caller’s data.

What we rejected: Letting a concrete backend type leak into the algorithm surface, and using a trait object (Box<dyn ...>) — the latter would add runtime dispatch on hot numerical paths, which the performance mandate rules out.

SKFaerBackend (the pure-Rust default backend)

What it is: A tiny, Debug + Clone + Copy + Default unit struct — it holds no data — created with SKFaerBackend::new(). It implements SKMathBackend<f64> and SKMathBackend<f32> by delegating GEMM to faer’s blocked matmul (honouring the plan’s parallelism) and the decompositions to faer’s high-level SVD/QR/Cholesky/LU/eigen solvers. A sibling SKMatrixMultiplyBackend routes GEMM to matrixmultiply and the decompositions to faer.

Why it exists: The default must work with no C toolchain. faer compiles on Rust 1.85 and is competitive, so the default build links no system BLAS at all.

What we rejected: Making a system BLAS the default, and oxiblas (fails to compile on the project’s Rust version). The unsafe here is contained in the SIMD/GEMM glue only.

sk_elementwise_transform (the elementwise kernel)

What it is: A free function that applies a closure x → transform(x) to every element of a 1-D view and returns a new owned array. It reads the resolved parallelism: 1 runs the sequential azip! form (zero dispatch overhead); > 1 runs par_azip! across the compute pool.

Why it exists: It is the most basic LEGO brick — every scaling, normalization or feature transform reuses it (spec higher-order-kernels). Iteration is delegated to azip!, never a manual index loop.

What we rejected: Hand-written index loops, and always-owning a fresh buffer when the caller might prefer an in-place variant (that is sk_scale_in_place’s job instead).

sk_binary_combine (the pairwise elementwise kernel)

What it is: A free function that pairs two equal-length views element by element, combine(left_k, right_k), and returns a new owned array. It asserts the lengths match and, like the transform, honours parallelism (1 → zip_mut_with, > 1 → par_azip!).

Why it exists: Many operations need two arrays at once — adding a bias term, multiplying two feature sets, comparing two signals. It is the binary sibling of the transform.

What we rejected: Requiring a pre-allocated output buffer from the caller; the function owns its result, keeping call sites simple.

sk_axis_sum (the reduction kernel)

What it is: A free function that sums a 2-D array along one axis into a 1-D result. axis = 0 collapses rows → per-column sums (length = number of columns); axis = 1 collapses columns → per-row sums (length = rows). It honours parallelism. The parallel axis-0 path splits rows into chunks, reduces each chunk into its own accumulator, then combines the partials — deliberately avoiding any shared mutable accumulator, so there is no data race.

Why it exists: Summing along an axis is everywhere (totals, statistics, normalization denominators). The race-free parallel design is the careful part (spec higher-order-kernels).

What we rejected: Writing directly into a single shared accumulator from multiple threads (that would race), and manual index loops for the reductions.

sk_scale_in_place (the in-place kernel)

What it is: A free function that multiplies every element of a 2-D array by a scalar factor in place, returning nothing. It mutates the caller’s buffer, allocating no new array (spec higher-order-kernels).

Why it exists: When you only need to scale existing data, copying the whole array is wasteful; in-place is the zero-allocation path.

What we rejected: Returning a new array for scaling (that is sk_elementwise_transform’s mode); this function’s whole point is to avoid the copy.

SKMemoryLayout, sk_memory_layout, sk_force_contiguous (the layout helpers)

What they are: SKMemoryLayout is a three-variant enum — CContiguous (row-major), FContiguous (column-major), Strided (neither). sk_memory_layout detects which case a view is in; sk_is_c_contiguous / sk_is_f_contiguous ask one yes/no question; and sk_force_contiguous returns a CowArray: a zero-copy borrow when the input is already contiguous, or a fresh owned contiguous copy when it is strided.

Why they exist: Hot SIMD kernels want contiguous memory. Detecting layout lets code feed fast paths with contiguous buffers and only pay for a copy when it truly has to.

What we rejected: Always copying (defeats zero-copy), and assuming a layout that the data does not have (would silently run slow or wrong).

The distance functions: sk_squared_euclidean_distance_matrix, sk_euclidean_distance_matrix, sk_manhattan_distance_matrix, sk_cosine_distance_matrix

What they are: Four free functions that take two &ArrayView2<F> feature matrices and return an owned Array2<F> distance matrix. Squared-Euclidean uses the norm-expansion $|a|^2 - 2a \cdot b + |b|^2$, with row norms precomputed and each cell needing one SIMD dot product; Euclidean is its element-wise square root; Manhattan is $\sum |a_k - b_k|$; cosine is $1 - \frac{a \cdot b}{|a| , |b|}$, with a guard that maps zero-norm rows to distance $1$ (matching scikit-learn).

Why they exist: Nearest-neighbor search, clustering, SVM kernels and imputation all need distance matrices. The norm-expansion formulation is the performance heart (spec pairwise-distances).

What we rejected: The naive per-pair subtract loop $\sum (a_k - b_k)^2$ for squared Euclidean (slower, not SIMD-friendly), and dividing by zero in cosine without a guard.

sk_csr_dense_product and sk_sparse_product (the sparse products)

What they are: sk_csr_dense_product multiplies a CsMatView by a dense ArrayView2, walking each non-zero entry of the CSR operand once and accumulating value * dense_row into the output row via azip! — the sparse operand is never densified. sk_sparse_product multiplies two CsMatView<f64> and delegates to sprs’ sparse matrix-matrix product (SMMP), returning a sparse CsMat<f64>.

Why they exist: Sparse workloads (Lasso, linear SVMs, text classification) would blow up memory if densified (spec dense-sparse-products). Both take zero-copy views.

What we rejected: Densifying the sparse operand before multiplying, and copying the sparse input.


5. A real walk-through, using the tests

The most convincing way to learn is to read actual tests that passed. Here are three real tests: one from kernels_tests.rs, one from pairwise_tests.rs, and one that proves the parallel and sequential paths agree.

Test 1: axis_one_sum_matches_row_totals (from kernels_tests.rs)

This test checks that sk_axis_sum with axis = 1 sums each row correctly.

#![allow(unused)]
fn main() {
#[test]
fn axis_one_sum_matches_row_totals() {
    let input: Array2<f64> = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]];
    let sums = sk_axis_sum(&input.view(), 1, 1);
    assert_eq!(sums, array![6.0, 15.0, 24.0]);
}
}

Line by line:

  1. let input: Array2<f64> = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]; — we build an owned 3×3 matrix of f64. The array! macro lays out three rows, each with three numbers, so input has 3 rows and 3 columns.
  2. let sums = sk_axis_sum(&input.view(), 1, 1); — we call the kernel. The &input.view() hands the function a view (a borrow, no copy). The first 1 is the axis: we are summing along axis 1, which collapses columns and keeps rows. The second 1 is the parallelism: run sequentially.
  3. assert_eq!(sums, array![6.0, 15.0, 24.0]); — we compare to the hand-computed row totals. Row [1,2,3] sums to 6, row [4,5,6] to 15, row [7,8,9] to 24. The kernel’s sequential path iterates rows and folds each one, so the output is exactly this.

Test 2: squared_euclidean_matches_direct_computation (from pairwise_tests.rs)

This test proves the norm-expansion squared-Euclidean kernel against hand-computed values.

#![allow(unused)]
fn main() {
#[test]
fn squared_euclidean_matches_direct_computation() {
    let left: Array2<f64> = array![[0.0, 0.0], [3.0, 4.0]];
    let right: Array2<f64> = array![[1.0, 1.0]];
    let distance = sk_squared_euclidean_distance_matrix(&left.view(), &right.view());
    // dist([0,0],[1,1]) = 2 ; dist([3,4],[1,1]) = 4 + 9 = 13.
    assert!((distance[[0, 0]] - 2.0).abs() < 1e-12);
    assert!((distance[[1, 0]] - 13.0).abs() < 1e-12);
}
}

Line by line:

  1. let left: Array2<f64> = array![[0.0, 0.0], [3.0, 4.0]]; — the first feature set has two points: (0,0) and (3,4). let right: Array2<f64> = array![[1.0, 1.0]]; — the second set has one point (1,1). So the distance matrix will be 2×1.
  2. let distance = sk_squared_euclidean_distance_matrix(&left.view(), &right.view()); — we hand both sets in as views. Inside, the kernel computes $|a_{\text{row}}|^2$ for both rows ($0$ and $25$), $|b_{\text{row}}|^2$ for the single right row ($2$), then fills the $2 \times 1$ matrix with $|a|^2 + |b|^2 - 2(a \cdot b)$ per cell.
  3. assert!((distance[[0, 0]] - 2.0).abs() < 1e-12); — the distance from (0,0) to (1,1) is $0 + 2 - 2(0 \cdot 1 + 0 \cdot 1) = 2$, matching the straight-line square $(1-0)^2 + (1-0)^2 = 2$. The .abs() < 1e-12 is a floating-point tolerance: we expect exactly 2, allowing tiny rounding.
  4. assert!((distance[[1, 0]] - 13.0).abs() < 1e-12); — from (3,4) to (1,1) the squared distance is $(1-3)^2 + (1-4)^2 = 4 + 9 = 13$, which the norm-expansion also produces.

Test 3: elementwise_parallel_matches_sequential_on_large_array (from kernels_tests.rs)

This test checks that the parallel kernel agrees with the sequential one, which is the whole point of the parallelism switch.

#![allow(unused)]
fn main() {
#[test]
fn elementwise_parallel_matches_sequential_on_large_array() {
    let n = 1 << 16;
    let input: Array1<f64> = Array1::from_shape_fn(n, |i| (i as f64) / 7.0);
    let f = |x: f64| (x * 3.0 + 2.0).sin();
    let sequential = sk_elementwise_transform(&input.view(), f, 1);
    let parallel = sk_elementwise_transform(&input.view(), f, 8);
    assert_close(&sequential, &parallel);
}
}

Line by line:

  1. let n = 1 << 16; — n is 2¹⁶ = 65536, a large array so that parallelism actually matters.
  2. let input: Array1<f64> = Array1::from_shape_fn(n, |i| (i as f64) / 7.0); — we build a 1-D array of 65536 elements; element i is i / 7.0. from_shape_fn fills the shape by calling the closure for each index.
  3. let f = |x: f64| (x * 3.0 + 2.0).sin(); — the transform: sin(3x + 2). Note the same closure is passed to both calls; this is the higher-order design in action.
  4. let sequential = sk_elementwise_transform(&input.view(), f, 1); — run it sequentially (parallelism = 1).
  5. let parallel = sk_elementwise_transform(&input.view(), f, 8); — run the same transform with parallelism = 8, which dispatches par_azip! across the pool.
  6. assert_close(&sequential, &parallel); — the test’s own helper checks the two agree within a relative tolerance. Why tolerance instead of exact equality? Parallel reordering can shift the last bits of floating-point results, so we allow tiny differences. This is the contract that parallel kernels stay correct.

6. Look inside

One strong insight: the crate's performance is an act of architecture, not just clever loops. The kernels separate what to compute (a closure) from how to sweep memory (`azip!`/`par_azip!`), distances are rewritten into a form that reuses one SIMD dot product per cell, sparse data is never densified, and the heavy algebra hides behind a generic trait so the default is pure Rust and the fast path is an opt-in flag — all without a single algorithm ever changing.

Here is how the crate’s modules hang together:

flowchart LR
    accTitle: Modules of the sciencekit_math crate and their key functions
    accDescr: sciencekit_math groups kernels, layout, pairwise distances, sparse operations and a backend. Each module exposes free functions, and the backend module exposes the SKMathBackend trait implemented by faer, matrix multiply and ndarray-linalg.
    MATH[sciencekit_math] --> K[kernels]
    MATH --> L[layout]
    MATH --> PW[pairwise]
    MATH --> SO[sparse_ops]
    MATH --> BE[backend]

    K --> K1[sk_elementwise_transform]
    K --> K2[sk_binary_combine]
    K --> K3[sk_axis_sum]
    K --> K4[sk_scale_in_place]
    K --> AZ["azip! / par_azip! (higher-order iteration)"]

    L --> L1["SKMemoryLayout: C, F, or Strided"]
    L --> L2["sk_force_contiguous returns a CowArray"]

    PW --> P1[sk_squared_euclidean_distance_matrix]
    PW --> P2[sk_euclidean_distance_matrix]
    PW --> P3[sk_manhattan_distance_matrix]
    PW --> P4[sk_cosine_distance_matrix]
    P1 --> SIMD["wide f64x4 SIMD dot (simd_dot.rs)"]

    SO --> S1["sk_csr_dense_product (never densifies)"]
    SO --> S2["sk_sparse_product uses sprs SMMP"]

    BE --> TRAIT[SKMathBackend trait]
    TRAIT --> F[SKFaerBackend - pure Rust, default]
    TRAIT --> G[SKMatrixMultiplyBackend]
    TRAIT --> H["ndarray-linalg (opt-in blas-backend)"]

    style MATH fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style K fill:#fef3c7,stroke:#d97706,color:#78350f
    style L fill:#fef3c7,stroke:#d97706,color:#78350f
    style PW fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style SO fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style BE fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
    style TRAIT fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

The diagram shows sciencekit_math as the numeric substrate: the four module families (kernels, layout, pairwise, sparse_ops) supply the reusable operations, all built on azip!/par_azip! and zero-copy views, while backend supplies the single heavy-algebra door that defaults to pure-Rust faer and can be swapped for a system BLAS via a feature flag.


7. Recap

  • Kernels separate what from how. sk_elementwise_transform and sk_binary_combine take a closure (the operation) and sweep memory with azip!/par_azip! — so switching to parallel is a one-word change, never a rewrite.
  • Reductions are race-free by design. sk_axis_sum accumulates per-chunk partials in parallel rather than writing into one shared accumulator, so parallel results match the sequential ones within a tiny floating-point tolerance.
  • Distances use math to win. Squared-Euclidean is computed as $|a|^2 - 2a \cdot b + |b|^2$, reusing a SIMD dot product per cell; cosine and Manhattan have their own clean formulas, all over zero-copy row views.
  • Sparse stays sparse. sk_csr_dense_product walks only the non-zero entries and never densifies, while sk_sparse_product delegates to sprs’ SMMP.
  • Heavy algebra hides behind one trait. SKMathBackend with the pure-Rust SKFaerBackend default, plus an opt-in blas-backend feature for a system BLAS — the default needs no C toolchain, and algorithms never change when the backend does.

Next chapter: armed with kernels, distances, sparse products and a linear-algebra door, we are ready to watch the first real estimator put them to work — fitting a model and making predictions on new data.

Execution modes, resolution and observability

A machine-learning library cannot assume one-size-fits-all execution: the same algorithm must run instantly on a small in-memory dataset, stream through one too large to fit in RAM, or shuffle bytes off a memory-mapped file. And when it does run, an engineer needs to see what happened — which mode was chosen, how long it took, whether it failed. This chapter explains how sciencekit turns a loose intent (“just run it the best way”) into a concrete plan (a specific mode, thread count, and batch size), how that plan drives a double-buffered streaming pipeline, and how every operation emits a trace span you can export to OpenTelemetry.


1. The problem we were solving

Imagine you build a library that does math on datasets. Some datasets are tiny — a few hundred rows, the kind you could hold in a spreadsheet. Others are enormous — a terabyte of sensor readings that will never, ever fit in your computer’s memory at once.

If you write your algorithm assuming one of these, you break the other. Assume “everything fits in memory” and the big dataset crashes or swaps painfully. Assume “always stream” and the tiny dataset pays an absurd overhead of threading and batching for no reason.

The naive solution is to make the caller decide: pass a flag that says “in-memory” or “streaming”. That works, but it is a burden on the user — and, worse, a source of bugs. The user might pick “in-memory” for data that is actually too large, or pick “streaming” for an algorithm that fundamentally needs random access (jumping to arbitrary positions), which streaming cannot provide.

The library should be smarter than that. It should let the user say “just pick the right one” (an automatic intent), and then decide for itself, based on how much memory is available, how big the dataset is, and what kind of access the algorithm needs. That is the first half of this chapter: execution mode resolution.

The second half is observability. When something runs — especially something slow or concurrent — you want to know what happened. Did fit choose in-memory or streaming? How many milliseconds did it take? Did it fail? Answering these questions requires wrapping every operation in a “span” — a named, timed box of structured metadata — that a tracing system can collect and export. This must be cheap by default and opt-in for export, so the default library never sends telemetry traffic over the network.

Both halves share one philosophy, which the previous chapter called the library’s core strength: push mistakes out of the running program and into the compiler and the types. We will see that philosophy again and again — in enums that make invalid states unrepresentable, in a deterministic resolver that cannot depend on hidden global state, and in a builder pattern that makes an unconfigured model impossible to construct.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Intent and plan are separate typesThe user declares a loose intent (Automatic, InProcessSynchronous, OutOfCoreStreaming…), stored in the builder. Only at operation time — when the dataset size is finally known — is that intent resolved into a concrete plan carrying mode, parallelism, and batch size. This lets fit and predict resolve differently, because their data sizes differ (spec execution-decision: “each heavy operation SHALL resolve its own plan”).Resolving once at build time — but data size is unknown until the operation’s input arrives, so a fixed plan would be wrong.
Resolution is a pure, deterministic function with an injectable contextsk_resolve_execution_plan(intent, context) reads nothing global: memory, cores, and dataset size are passed in an SKExecutionContext. Same inputs → same plan, guaranteed, and tests can inject a fake machine instead of reading the real one (spec execution-planning: “the context SHALL be providable by the caller, enabling deterministic tests independent of the machine”).Reading sysinfo directly inside the resolver — makes every test depend on the physical machine and makes behavior non-reproducible.
Automatic never fails; explicit incompatible modes fail loudlyIf the user says Automatic, the resolver always finds a compatible mode. If they insist on OutOfCoreStreaming for a random-access algorithm, it returns SKError::ExecutionModeIncompatible before processing any data, naming both sides of the conflict (spec: “automatic mode SHALL NEVER produce such an error”).Silently downgrading an explicit choice — hides a likely programmer error behind surprising behavior.
SKExecutionMode and SKAccessPattern are enums, #[non_exhaustive]A mode/pattern is one of a closed set; an enum makes “invalid mode” a compile-time error. non_exhaustive lets us add modes later without breaking consumers who match on them.Free-form strings ("streaming") — a typo would fail at runtime, and there’d be no central list of valid values.
Observability is tracing spans, exported opt-in behind a feature flagEvery operation opens a tracing span with structured fields (operation, shape, mode, backend, duration, error). Export to OpenTelemetry is gated behind the observability-export feature, so the default build compiles the export path out and emits no OTLP traffic (spec observability: “the default build emits no OTLP traffic”).Instrumenting with a heavyweight SDK unconditionally — would force every consumer to configure an exporter they may not want.

3. The concepts, taught from zero

Rust concept 1: enums with data-carrying variants

An enum is a type whose value is exactly one of a fixed set of possibilities. In Rust each possibility (a variant) can carry its own data. We met this in chapter 2 with SKDataView. Here it powers the execution intent:

#![allow(unused)]
fn main() {
pub enum SKExecutionMode {
    Automatic,
    InProcessSynchronous,
    InProcessAsynchronous,
    OutOfCoreStreaming,
    OutOfCoreMemoryMapped,
}
}

A value of this type is one of those five — never two, never none. The compiler knows the full list, so when we match on it we must handle every variant, and the compiler refuses to let us forget one. #[non_exhaustive] above the enum tells the compiler: “outsiders should still add a wildcard arm, because we may add variants in the future.” Inside our own crate we are exhaustive; outside, consumers write a _ => catch-all to stay future-proof.

Rust concept 2: the builder pattern — mandatory here

Rust structs often hold many optional settings. The builder pattern solves “too many optional parameters” by giving you a chainable object that you configure step by step, then finally ask to produce the real value.

In sciencekit this is mandatory: you cannot call a constructor directly. Every public estimator exposes a builder, and construction goes through build() (spec base-builders). Two shared pieces make this uniform across every algorithm:

  • SKBuilderState — the reusable “storage drawer” that remembers the execution intent and knows how to resolve it into a plan.
  • SKBuilder — the trait (an interface) every builder implements, guaranteeing the same two methods: execution_mode(...) and build().

The reason this is mandatory is safety-by-construction: a model only ever exists after build() has validated its configuration and returned Result. You cannot accidentally use an unbuilt, half-configured model.

Rust concept 3: fluent setters and the Automatic default

A builder method that returns &mut Self lets you chain calls. The key default is that the execution intent starts as Automatic:

#![allow(unused)]
fn main() {
pub fn execution_mode<E>(&mut self, mode: E) -> &mut Self
where
    E: TryInto<SKExecutionMode>,
}

Notice the argument is generic over E: TryInto<SKExecutionMode>. We learned TryInto in chapter 2. The point here: you can pass an SKExecutionMode directly (it converts infallibly), and a mis-typed string cannot compile, because a string cannot TryInto an SKExecutionMode. The &mut self return means you can chain: .execution_mode(...) then .build().

Because SKBuilderState::new() starts at Automatic, a consumer who never calls execution_mode still gets automatic behavior — the requirement “a consumer who does not set it still gets automatic execution.”

Rust concept 4: Result and error propagation

Functions that can fail return Result<T, E> — either Ok(value) or Err(error). The resolver returns Result<SKExecutionPlan, SKError>, and the builder’s build() returns Result<Model, SKError>. SKError is the central taxonomy we met in chapter 2; two variants matter here:

#![allow(unused)]
fn main() {
#[error("execution mode `{mode}` is incompatible with the declared access pattern `{pattern}`")]
ExecutionModeIncompatible { mode: &'static str, pattern: &'static str },

#[error("streaming batch buffer overflow: {required_bytes} bytes needed (2 × {batch_bytes} per batch) exceeds {available_bytes} bytes available")]
BatchBufferOversize { batch_bytes: u64, required_bytes: u64, available_bytes: u64 },
}

The #[error("...")] comes from thiserror, which generates the human-readable message. The fields give the caller structured information — not just “it failed”, but exactly which mode, which pattern, how many bytes were needed. The ? operator propagates a Result up the call stack automatically, but here the resolver builds its errors by hand with Err(...) when it detects an incompatibility or an oversized buffer.

Rust concept 5: threads, Arc, Mutex, and Condvar (the streaming driver)

The streaming driver runs two threads that share a buffer. Rust’s answer to shared mutable state is precise:

  • Arc<T> (atomic reference count) is a smart pointer that many threads can hold a clone of; when the last clone drops, the value is freed. It lets the producer thread and the consumer thread both “hold onto” the same shared state.
  • Mutex<T> wraps a value so only one thread can read/write it at a time (mutual exclusion). You lock it to get a guard, work, then drop the guard to release it.
  • Condvar (condition variable) is a way for a thread to wait until a condition becomes true and be notified when it changes. The producer waits when the buffer is full; the consumer waits when the buffer is empty.

You will see these three working together in the walk-through: the buffer is Mutex-protected state plus a Condvar for signaling, all shared through an Arc.

Numerical concept 1: what “in-memory vs out-of-core” means

  • In-memory execution: the whole dataset sits in RAM, so the algorithm can touch any element at any time (random access) and pass over it repeatedly. Fast, but bounded by memory.
  • Out-of-core execution: the dataset is bigger than memory, so it lives on disk and is processed in pieces. Two flavors: streaming (read a sequential batch, compute, move on) and memory-mapped (the OS lazily pages parts of the file into memory as you access them, giving random access to a file larger than RAM).

Numerical concept 2: what an access pattern is

An algorithm declares how it wants to touch data:

  • Sequential: read a batch, move to the next, never look back — perfect for streaming.
  • RandomAccess: jump to element i in O(1) — only possible in-memory or memory-mapped.
  • Iterative: pass over the whole dataset repeatedly (e.g. gradient descent epochs) — fits in-memory or streaming, but not a single forward scan.

This is the crux of the incompatibility rule: you cannot stream an algorithm that needs random access, because a streaming pipeline only hands you batches in order.

Numerical concept 3: double buffering

In streaming, the reader (I/O) and the compute (math) are two different speeds. If the reader waits for compute to finish before reading the next batch, the I/O sits idle. If compute waits for the reader, the CPU sits idle.

Double buffering keeps both busy: while compute works on batch k, the reader fetches batch k+1 into a second buffer. When compute finishes batch k, the already-fetched k+1 is ready — no waiting. The buffer_depth in the plan (double buffering = 1) is the number of prefetched batches ahead. The guard in the resolver ensures two resident batches fit in memory: if one batch is $B$ bytes, double buffering needs $2 \times B$, and if that exceeds available memory the plan is rejected before any data is processed.

Numerical concept 4: the “grain” — how many elements per thread

Parallelizing has a fixed overhead: spawning a thread and coordinating it costs time. If a dataset is tiny, splitting it across threads costs more than it saves. So the resolver needs a grain: the minimum number of elements per thread that justifies a thread. The number of threads is ceil(elements / grain), clamped to the core count. A 100-element dataset below one grain (e.g. 1,024 elements) resolves to one thread; a 10-million-element dataset resolves to ceil(10,000,000 / 1,024) = 9,766, clamped to, say, 8 cores. This is why parallelism is part of the plan.

Observability concept: tracing spans

tracing is a Rust library for structured, hierarchical logging. A span is a named region of execution with a start, an end, and structured fields (key–value pairs). Spans can nest (a fit span containing a predict span). A span is created, its fields are filled in over time (some like duration_ms and error start empty and are filled at the end), and it is finalized when the operation completes. An OpenTelemetry layer is a piece that plugs a subscriber (the thing collecting spans) together with an exporter that sends them to a collector (like Jaeger). Making that layer opt-in behind a feature flag keeps the default build free of any network exporter.


4. Each object, explained

SKExecutionMode

What it is: A #[non_exhaustive] enum with five variants — Automatic, InProcessSynchronous, InProcessAsynchronous, OutOfCoreStreaming, OutOfCoreMemoryMapped. It is the intent the consumer declares; it is stored in the builder and can be Copy + Clone + PartialEq (cheap to duplicate and compare).

Why it exists: It separates “what the user wants” from “what will actually happen”. The user picks one value (or leaves it Automatic); the resolver later turns that into a plan. The Automatic variant is the key: it is the default that lets the library decide.

What we rejected: Free-form strings and allowing arbitrary extra modes without a fixed list. The enum makes invalid modes a compile-time error, and non_exhaustive still lets us grow the set later.

SKAccessPattern

What it is: A #[non_exhaustive] enum with three variants — Sequential, RandomAccess, Iterative. It is not a user choice; it is a property the algorithm declares about how it must touch its data.

Why it exists: It is the half of the compatibility check the user never controls. The resolver consults it to decide whether a requested mode is even possible: random access can never stream.

What we rejected: Letting the user set the access pattern (they would not know the algorithm’s internals) and deriving it heuristically at runtime (unsafe, opaque). The algorithm author declares it once, honestly, and the type keeps it honest.

SKExecutionContext

What it is: A plain struct holding the inputs to resolution: available_memory_bytes, cpu_cores, dataset_size_bytes, dataset_elements, scalar_size_bytes, grain, access_pattern, and batch_size_hint. It has two constructors: real() reads the physical machine (memory via sysinfo, cores via thread::available_parallelism), and tests build their own by hand with simulated values.

Why it exists: It makes resolution pure — all the environment enters through one explicit argument rather than hidden global state. That is what lets tests inject a fake 1-byte machine and get deterministic answers, and it is what makes “same inputs, same plan” a guarantee.

What we rejected: Reading the machine inside the resolver. That couples every resolution to the physical environment, breaks reproducibility, and makes the resolver impossible to unit test.

SKExecutionPlan

What it is: A struct with four fields — mode, parallelism, batch_size: Option<usize>, and buffer_depth. It is the output of resolution, PartialEq + Eq so two plans can be compared for equality.

Why it exists: It is the concrete, executable decision: “run in this mode, on this many threads, in batches of this size (if streaming), prefetching this many batches ahead.” It is what an algorithm actually consumes to run an operation.

What we rejected: Confusing the plan with the intent (they are deliberately different types), and leaving parallelism/batch_size out — an executable plan needs all of them.

sk_resolve_execution_plan

What it is: The free-scope public function sk_resolve_execution_plan(intent, context) -> Result<SKExecutionPlan, SKError>. It matches the intent; for Automatic it compares dataset_size_bytes to available_memory_bytes. If it fits, the mode is InProcessSynchronous; if not, the mode follows the access pattern (RandomAccess → OutOfCoreMemoryMapped; Sequential/Iterative → OutOfCoreStreaming). Explicit modes are kept unless a streaming intent meets a random-access pattern, which returns ExecutionModeIncompatible. Parallelism comes from parallelism_for(mode, context), and the buffer guard check_buffer_guard(context) rejects an oversized double-buffer footprint.

Why it exists: It is the pure, deterministic heart of the whole design (spec execution-decision). “Intent + context → plan” with no hidden state, so it is safe to call from any number of threads concurrently.

What we rejected: Resolving against the physical machine directly, and allowing automatic to ever produce an incompatibility error (it never does — automatic always picks a compatible mode).

sk_run_streaming_driver

What it is: The free-scope function that actually runs a streaming operation: sk_run_streaming_driver(source, state, update, plan) -> Result<(), SKError>. It spawns a dedicated producer thread that pulls batches from an SKLazySource into a bounded double buffer, while the caller’s thread consumes each owned SKDataBatch and applies the algorithm-supplied update(batch, parallelism, state) closure. update returns an SKStreamDecision (Continue or Stop) to steer the pipeline.

Why it exists: It implements the prefetch contract — input and computation overlap, batches arrive in order and fully owned, and a mid-stream read error surfaces as a central SKError with the effects of earlier batches preserved. This is the executor the plan’s streaming modes drive.

What we rejected: Reading and computing on the same thread (no overlap), and letting the algorithm push unboundedly ahead (hence the bounded buffer of buffer_depth).

SKBuilderState

What it is: A struct holding one field, execution_intent: SKExecutionMode, defaulting to Automatic. It offers execution_mode(...) (the chainable setter), execution_intent() (the getter), and resolve_plan(context) which delegates to sk_resolve_execution_plan.

Why it exists: It is the reusable “storage drawer” every algorithm builder embeds, so the execution-intent plumbing is written once instead of per algorithm (spec base-builders). It carries the Automatic default and knows how to turn stored intent into a concrete plan.

What we rejected: Each algorithm re-implementing intent storage and resolution — duplicated logic and drifting defaults. A single shared state type keeps the default uniform everywhere.

SKBuilder

What it is: A trait with two methods: execution_mode<E>(&mut self, mode: E) -> &mut Self where E: TryInto<SKExecutionMode> and build(self) -> Result<Model, SKError>.

Why it exists: It is the mandatory contract every estimator builder implements, so all builders look the same: configure execution, call build(), get a Result. It encodes “construction always goes through build()” at the type level (spec base-builders).

What we rejected: Letting algorithms skip the builder (they can’t — the trait and shared state are the foundation every one compiles against) and build() returning a bare model instead of a Result (loses the guarantee that invalid config surfaces as an error, not a panic).

SKOperationKind and SKBackendKind

What it is: Two enums of bounded strings. SKOperationKind is the closed set of library operations that emit spans (Fit, PartialFit, FitTransform, Transform, Predict, FitPredict, Score). SKBackendKind is the closed set of math backends (Faer, MatrixMultiply, NdArrayLinalg). Both implement Display so they render as clean strings like "fit" and "faer".

Why it exists: Structured observability needs bounded, compiler-checked values. Modelling these as enums means a misspelled operation or backend is a compile-time error, not a runtime surprise (spec observability: “the compiler rejects invalid values … instead of letting them surface at runtime”).

What we rejected: Free-form String attributes in the span — a typo would silently produce a mislabeled trace.

SKOperationAttributes

What it is: A struct bundling the structured fields of an operation span: operation (SKOperationKind), rows, columns, execution_mode (SKExecutionMode), and backend (SKBackendKind).

Why it exists: It is the single, type-safe bundle handed to the observability system when a span opens — one argument instead of five, all compiler-checked. Note it carries the resolved execution_mode, so a trace tells you which mode an operation actually ran in.

What we rejected: Passing each field separately to the span opener, and letting the span record raw, untyped values.

SKOperationObservation

What it is: A live span wrapper. It is created with begin(attributes), runs work via in_scope(...) (or enter()), records a failure with record_error(&error), and closes with finish(), which stamps the elapsed duration_ms onto the span.

Why it exists: It encapsulates the tracing::Span lifecycle so callers never touch tracing directly and never forget to fill duration_ms or record an error.

What we rejected: Exposing the raw tracing::Span and making callers manage its lifecycle — error-prone, and easy to leak a span.

sk_run_operation

What it is: A convenience function: sk_run_operation(attributes, operation) -> Result<T, E>. It opens an observation, runs the closure operation, records any error on the span, finishes the span, and returns the result unchanged.

Why it exists: It is the one-liner algorithm crates wrap each public operation in, so every fit/predict/transform is automatically traceable with failure visible in the trace (spec observability: “each public operation … so failures stay visible in the trace”).

What we rejected: Requiring each algorithm to hand-roll span open/error/close — duplication and easy to get wrong.

sk_opentelemetry_layer

What it is: A free-scope function that builds a Box<dyn tracing_subscriber::Layer<...>> wiring tracing to an OpenTelemetry tracer, given a tracer_name. It is only compiled when the observability-export feature is on.

Why it exists: It is the opt-in export path. The consumer configures the OpenTelemetry tracer provider and combines the returned layer with their subscriber; the default build compiles this out entirely and never initializes an exporter (spec observability: “the default build emits no OTLP traffic”).

What we rejected: Initializing an exporter by default, or coupling the library to a specific tracing subscriber — both would force telemetry behavior on consumers who don’t want it.


5. A real walk-through, using the tests

The most convincing way to learn is to read actual passing tests. Here are three — one from execution_tests.rs and two from streaming_driver_tests.rs.

Test 1: automatic_oversized_sequential_streams

This test proves that when an automatic intent meets a dataset larger than memory with a sequential access pattern, resolution picks streaming with the declared batch size.

#![allow(unused)]
fn main() {
#[test]
fn automatic_oversized_sequential_streams() {
    let ctx = simulated(
        1 << 30,          // available memory = 1 GiB
        4,                // CPU cores
        1 << 40,          // dataset size = 1 TiB  → larger than memory!
        None,             // dataset_elements unknown
        8,                // scalar size = 8 bytes (f64)
        SKAccessPattern::Sequential,
        Some(1024),       // batch size hint = 1024 elements
    );
    let plan = sk_resolve_execution_plan(SKExecutionMode::Automatic, &ctx).unwrap();
    assert_eq!(plan.mode, SKExecutionMode::OutOfCoreStreaming);
    assert_eq!(plan.batch_size, Some(1024));
}
}

Line by line:

  1. let ctx = simulated(...) — we call the test helper simulated, which builds an SKExecutionContext by hand, never touching the physical machine. The 1 << 30 is bit-shift notation for 2^30 = 1 GiB of available memory; 1 << 40 is 2^40 = 1 TiB of dataset. The dataset is a thousand times bigger than memory.
  2. SKAccessPattern::Sequential tells the resolver the algorithm reads in order, so streaming is a legal option. Some(1024) is the caller’s batch-size hint.
  3. sk_resolve_execution_plan(SKExecutionMode::Automatic, &ctx) — automatic intent. Inside, the resolver sees dataset_size_bytes (1 TiB) <= available_memory_bytes (1 GiB) is false, so the dataset does not fit in memory. It then matches the access pattern Sequential and picks OutOfCoreStreaming. .unwrap() asserts the Result is Ok.
  4. assert_eq!(plan.mode, SKExecutionMode::OutOfCoreStreaming) — confirms the mode.
  5. assert_eq!(plan.batch_size, Some(1024)) — confirms the batch hint flowed into the plan, because in streaming mode batch_size is the hint (in other modes it is None).

The lesson: a single automatic intent produced a streaming plan purely from context — no user flag, no hidden machine reads.

Test 2: ordered_delivery_of_owned_batches

This test proves the streaming driver hands batches to the compute step in source order, and that each batch’s data survives even after the source has moved past it (i.e. the batch is owned, a copy, not a borrow).

#![allow(unused)]
fn main() {
#[test]
fn ordered_delivery_of_owned_batches() {
    let (mut source, _read_log, _outstanding, _max) = RecordingSource::new(5, None);
    let update =
        |batch: SKDataBatch<f64>, _parallelism: usize, state: &mut Vec<(usize, Vec<f64>)>| {
            let data = batch.view().as_dense().expect("dense batch").as_slice_memory_order().unwrap().to_vec();
            state.push((batch.position(), data));
            SKStreamDecision::Continue
        };
    let mut state = Vec::new();
    sk_run_streaming_driver(&mut source, &mut state, update, &streaming_plan()).unwrap();

    assert_eq!(state.len(), 5);
    for (index, (position, data)) in state.iter().enumerate() {
        assert_eq!(*position, index);
        assert_eq!(data, &[index as f64]);
    }
}
}

Line by line:

  1. RecordingSource::new(5, None) — the test’s instrumented source, total = 5 batches, fail_at = None (never fails). It also returns three shared log handles (read_log, outstanding, max) we ignore here.
  2. The update closure is the algorithm’s per-batch step. Its signature is (batch, parallelism, state). Here state is a Vec<(position, data)> we accumulate. Inside, batch.view() returns a SKDataView over the block (dense or CSR); .as_dense() selects the dense view and .as_slice_memory_order() .unwrap().to_vec() copies it into an owned Vec<f64>, and we push (position, data). We return SKStreamDecision::Continue to keep going.
  3. let mut state = Vec::new() — the algorithm’s mutable accumulator.
  4. sk_run_streaming_driver(&mut source, &mut state, update, &streaming_plan()).unwrap() — run the pipeline. The driver’s producer thread pulls batches from source into the double buffer; the caller’s thread calls update for each in order. .unwrap() asserts success.
  5. The assertions: state.len() == 5 (all five batches delivered), and for each index, the position equals the index and the data equals [index as f64] — i.e. batch k arrived at step k, holding the value k. Because we copied into an owned Vec, the assertion works even though the source has already produced the next batch — proving ownership.

The lesson: ordering is exact, and each batch is a fully owned SKDataBatch, safe to use after the source advances — exactly what the double-buffer prefetch promises.

Test 3: early_stop_halts_the_pipeline

This test proves an update returning Stop halts the pipeline, keeps the current batch’s effect, reads no batch beyond the one prefetched, and returns without error.

#![allow(unused)]
fn main() {
#[test]
fn early_stop_halts_the_pipeline() {
    let (mut source, read_log, _outstanding, _max) = RecordingSource::new(8, None);
    let update = |batch: SKDataBatch<f64>, _parallelism: usize, state: &mut Vec<usize>| {
        state.push(batch.position());
        if batch.position() == 2 {
            SKStreamDecision::Stop
        } else {
            SKStreamDecision::Continue
        }
    };
    let mut state = Vec::new();
    let result = sk_run_streaming_driver(&mut source, &mut state, update, &streaming_plan());

    assert!(result.is_ok(), "early stop should return without error");
    assert_eq!(state, vec![0, 1, 2]);
    let max_read = read_log
        .lock()
        .unwrap()
        .iter()
        .map(|(index, _)| *index)
        .max()
        .unwrap();
    assert!(
        max_read <= 3,
        "read beyond the prefetched batch: up to index {max_read}"
    );
}
}

Line by line:

  1. RecordingSource::new(8, None) — a source of 8 batches, never failing. We keep read_log this time.
  2. update pushes each batch’s position, then returns Stop exactly when position == 2, otherwise Continue.
  3. sk_run_streaming_driver(...) — note we do not .unwrap(); we capture result.
  4. assert!(result.is_ok()) — stopping early is a normal, successful end; no error.
  5. assert_eq!(state, vec![0, 1, 2]) — the effect of batches 0, 1, 2 is kept; batch 2 was the last processed.
  6. We inspect read_log (the recorded read timestamps). Since buffer_depth = 1 (double buffering), when compute stopped at batch 2 the producer had already prefetched batch 3 — so max_read <= 3 proves we read at most one batch ahead and then halted. No batch 4+.

The lesson: the driver hands control flow back to the algorithm through the return value of update — stopping is cooperative, keeps work already done, and bounds how far ahead the reader can go by the buffer depth.


6. Look inside

One strong insight: the whole design is about separating what the user wants (a loose intent), what the machine allows (a context), and what will actually run (a concrete plan). The resolver is the pure bridge between them — deterministic, injectable, and incapable of silently ignoring a mistake the user made explicit.

Here is the end-to-end flow from intent to streaming execution:

flowchart LR
    accTitle: From builder to streaming execution and observability
    accDescr: A builder holds the SKBuilderState with an execution intent. The resolver turns the intent and execution context into an SKExecutionPlan, or rejects incompatible or oversized plans. Streaming execution prefetches batches while updating state, and observability records each operation as an optional OpenTelemetry span.
    subgraph configure[Builder]
        BS[SKBuilderState] -->|intent<br/>SKExecutionMode::Automatic| RES
    end

    subgraph resolve[Resolution — pure & deterministic]
        CTX[SKExecutionContext<br/>memory, cores, size, pattern] --> RES
        RES[sk_resolve_execution_plan] --> PLAN[SKExecutionPlan<br/>mode · parallelism · batch_size · buffer_depth]
        RES -. incompatibility .-> ERR[SKError::ExecutionModeIncompatible]
        RES -. buffer overflow .-> ERR2[SKError::BatchBufferOversize]
    end

    PLAN -->|OutOfCoreStreaming| DRIVER
    subgraph run[Execution]
        DRIVER[sk_run_streaming_driver]
        SRC[SKLazySource] -->|batch k+1 prefetch| DRIVER
        DRIVER -->|owned SKDataBatch k| UPDATE[update batch → state]
        UPDATE -->|Continue / Stop| DRIVER
    end

    UPDATE --> OBS
    subgraph observe[Observability]
        OBS[sk_run_operation / SKOperationObservation<br/>span: operation · shape · mode · backend · duration · error]
        OBS -->|opt-in feature| OTL[sk_opentelemetry_layer → exporter]
    end

    style configure fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style resolve fill:#fef3c7,stroke:#d97706,color:#78350f
    style run fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style observe fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    style ERR fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
    style ERR2 fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

Reading the diagram: the builder holds the intent; resolution combines it with an injected context to produce a concrete plan (or a precise error); a streaming plan drives the double-buffered driver, which feeds owned batches to the algorithm’s update; and every operation runs inside an observability span, exported only if the feature is on.


7. Recap

  • Intent and plan are different. The user stores a loose SKExecutionMode (defaulting to Automatic); the operation resolves it against a context into a concrete SKExecutionPlan with mode, parallelism, batch size, and buffer depth.
  • Resolution is pure and deterministic. sk_resolve_execution_plan(intent, context) reads nothing global, so the same inputs always yield the same plan and tests can inject a fake machine.
  • Automatic never fails; explicit errors are loud. Automatic always finds a compatible mode; an explicit streaming intent on a random-access algorithm fails before processing any data with ExecutionModeIncompatible, and an oversized double-buffer footprint fails with BatchBufferOversize.
  • The builder pattern is mandatory. Every estimator goes through a typed builder embedding SKBuilderState and implementing SKBuilder, so construction always passes through build() → Result and the execution intent always defaults to Automatic.
  • Streaming double-buffers. sk_run_streaming_driver overlaps input and compute through a bounded buffer, delivers ordered owned batches, and lets update stop the pipeline early.
  • Observability is opt-in. Every operation runs under a tracing span with structured fields; exporting to OpenTelemetry is gated behind the observability-export feature so the default build emits no telemetry traffic.

Next chapter: now that an operation can resolve how it runs and be traced while it runs, we turn to the computational core — how the heavy math kernels are selected and parallelized under the hood.

The host-centric backend

The backend that does the heavy math started out married to one linear-algebra library (faer) and one numeric type (f64), so every algorithm that wanted a matrix product or a decomposition was stuck with that library’s data types. This chapter is the story of how we broke that marriage: we made the backend host-centric — it speaks only in the library’s own vocabulary (ndarray views in, ndarray results out) — and made the choice of who actually computes replaceable, without touching a single caller.


1. The problem we were solving

Imagine you run a restaurant. The kitchen uses one specific brand of stove, and every menu item is written as “cook it on that exact stove.” Now you want to add a faster stove, or a cheaper one, and offer both. You would have to rewrite every recipe. Worse, the waiters (your algorithms) would have to learn how each stove works just to write down an order.

That was our situation. The math backend — the code that multiplies matrices and factorizes them — used faer, a pure-Rust linear-algebra library, and hard-coded the floating-point type f64. Its public methods took faer::Mat and returned faer::Mat. So every algorithm that wanted a matrix operation had to think in faer’s types. There was no way to swap in a system-optimized BLAS library (OpenBLAS, MKL, Accelerate) without rewriting the algorithms. And there was only one numeric type, f64 — no room for the lighter, faster f32 that many models use to save memory.

What goes wrong without a fix? Every new algorithm (Linear Regression, PCA, Ridge, GMM — the roadmap was filling up) would be welded to faer, and adding a second backend would mean touching everything. The library could not grow. So we asked a simple question: what is the smallest, cleanest promise a math backend can make to the rest of the library?

The answer became the guiding idea of this whole chapter: the backend adapts to the library, not the other way around. The library already has its own container type, ndarray, for dense numbers. So the backend’s public surface is written in ndarray terms — you hand it a view of your numbers, it hands back an owned result. Whether faer, a system BLAS, or (much later) a GPU sits behind the curtain is the backend’s private business.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Host-centric, concrete surface — the trait takes ArrayView2<F> and returns Array2<F>The rest of the crate already treats ndarray as its canonical host container. A GPU backend is explicitly deferred, so we don’t need device types yet. Simplest thing that works for zero-copy, lazy, and out-of-core. (design Decision 1)Backend-native associated types (MatOwned/MatRef<'a>) — device-ready but drags in generics/GATs for a GPU we aren’t building yet; a generic matrix trait M — pushes the faer×ndarray×GPU unification problem onto every call site.
Generic over SKFloat, not hard-coded f64Algorithms want both f32 and f64; SKFloat is the sealed bound that already exists and admits exactly those two (proposal “What Changes”).Keeping f64 only — blocks half the users and the memory savings of f32.
LU pivot is a host Vec<usize>LAPACK ipiv and faer’s pivot are exactly this; every result is host-resident, so there is no backend-specific pivot representation to abstract over. (design Decision 2)A PivotInfo associated type — extra machinery with nothing to abstract.
Default = pure-Rust faer; system BLAS is opt-infaer compiles on Rust 1.85 with no C toolchain, so a default build “just works” everywhere. ndarray-linalg+blas-src (OpenBLAS/MKL/Accelerate) is gated behind the blas-backend feature, off by default. (spec blas-interface)Making BLAS the default — would force every user to install a C/Fortran BLAS even to try the library.
lstsq is a first-class backend opscikit-learn calls LAPACK gelsd for Linear Regression; centralizing rank-deficiency and rcond truncation in one place beats re-implementing tolerance logic per algorithm. (design Decision 7)Composing lstsq from svd/pinv in every algorithm — slow (full vs truncated SVD) and duplicated.

3. The concepts, taught from zero

Before we read any code, let’s build the two ideas you need: what a trait is, and what “host-centric” really means. We’ll also touch on the small vocabulary the code uses.

A trait is a contract

A trait in Rust is a set of promises a type makes. Think of an electrical outlet: the outlet promises “any device with the right plug can draw power here.” The device doesn’t care where the electricity comes from, and the outlet doesn’t care what the device is. A trait works the same way.

#![allow(unused)]
fn main() {
pub trait SKMathBackend<F: SKFloat>: Send + Sync {
    fn kind(&self) -> SKBackendKind;
    fn gemm(&self, a: ArrayView2<F>, b: ArrayView2<F>, alpha: F, parallelism: usize) -> Array2<F>;
    // ... and many more
}
}

This says: “any type that wants to be a math backend must provide a kind, a gemm, a svd, and so on.” The outlet (the trait) doesn’t say how to compute — it just says the plug fits. A backend like SKFaerBackend then declares “I am a math backend” and fills in each method using its own library.

Generic over <F: SKFloat>

The <F: SKFloat> is a generic parameter — a placeholder for a type, the way a recipe’s “add flour” leaves how much flour open. The little : SKFloat is a bound: it means F is not any type, only types that implement SKFloat. And SKFloat is sealed: only f32 and f64 can ever be SKFloat, because only those two are declared to implement it. So <F: SKFloat> is a polite way of saying “this works for f32 and f64, and nothing else.”

The whole trait is written once, generically over F. Then for each concrete float we plug in the real types — ArrayView2<f64>, ArrayView2<f32>, and so on — automatically.

dyn vs generics: why a box, not a concrete type

Rust has two ways to use a trait. Generics bake the concrete type in at compile time: SKFaerBackend::new().gemm(...) knows exactly which type it is, so the compiler can make everything fast and type-safe. But generics make the caller name the type.

Sometimes the caller doesn’t know — or doesn’t care — which backend it has. It just wants “a math backend.” That’s where dyn comes in. Box<dyn SKMathBackend<F>> is a trait object: a pointer to some value that happens to implement SKMathBackend<F>. The caller holds the box and calls the trait’s methods; the actual type is decided at runtime (the dispatch function decides, below).

Why not always use dyn? Because a trait object adds a small runtime indirection and the compiler can’t inline it. Why not always use generics? Because the default backend is chosen by build configuration, not by the caller — we literally do not know which type will be there. So we use generics for the concrete backends (fast, in algorithms that name them) and dyn at the boundary where configuration picks the type (Box<dyn SKMathBackend<F>>). Each tool for its job.

What “host-centric” means

The word host means “the machine the program runs on” — your CPU and RAM, as opposed to a separate device like a GPU. Host-centric is a design rule: the library’s public vocabulary is the host’s vocabulary (ndarray for dense data, sprs for sparse data), and the backend must translate to and from it at the door.

Concretely: the trait’s inputs are ArrayView2<F> — views, which are a borrowed window over data that already exists (zero copies). Its outputs are Array2<F> — owned containers, fresh memory the caller takes possession of. No faer type appears anywhere in the public surface. If we swap the backend from faer to ndarray-linalg, every algorithm keeps talking to ndarray exactly as before; only the door changes.

#![allow(unused)]
fn main() {
fn assert_host_centric_surface<F: SKFloat, B: SKMathBackend<F> + ?Sized>(
    backend: &B,
    a: Array2<F>,
) {
    let _ = backend.gemm(a.view(), a.view(), F::one(), 1);
    let _: Result<SKSingularValueDecomposition<F>, _> = backend.svd(a.view());
    let _: SKQRDecomposition<F> = backend.qr(a.view());
    // ...
}
}

This test compiles if and only if the trait’s public surface is free of faer types. It’s the compiler enforcing “host-centric” for us — a theme we’ll revisit in the walk-through.

A small vocabulary of the code

  • ndarray — the library’s dense-array container. Array2<F> is a 2-D grid of F (a matrix); ArrayView2<F> is a read-only view over one (borrowed, no copy).
  • SKFloat — the sealed scalar bound; only f32 and f64.
  • SKBackendKind — a small enum naming which backend produced a result (Faer, MatrixMultiply, NdArrayLinalg), recorded in observability spans.
  • SKError — the crate’s central error type; backends map their library’s errors into it so callers never see a faer or LAPACK error.
  • Decompositions — ways to rewrite a matrix into simpler pieces: SVD, QR, LU, Cholesky. They’re the building blocks of many ML algorithms.

4. Each object, explained

SKMathBackend<F> (trait)

What it is — The single contract for “a thing that can do heavy dense algebra.” It declares the operations the library needs: gemm (matrix multiply), svd, qr, cholesky, solve_triangular, solve, eigh, lu, slogdet, pinv, inv, lstsq, norm, and vector_norm. It is generic over F: SKFloat, so the same contract serves both f32 and f64. It is Send + Sync, so a math operation can be shared across threads (an execution plan can fan the work out).

Why it exists — It is the abstraction boundary. Everything above it (the algorithms, the execution planner) talks only to this trait, in ndarray terms. Everything below it (the concrete backends) does the actual number crunching. The library is written once, against the trait, and any backend that honors the trait plugs in.

What we rejected — We rejected leaking concrete types into the trait (the old f64 + faer::Mat surface), associated matrix types that would make the surface device-ready now, and making the trait async (the backend stays eager and pure; concurrency is the execution planner’s job). Also rejected: hard-coding a sequential GEMM — the trait takes a parallelism argument so large products scale with the plan.

SKNormKind<F> (enum)

What it is — The set of matrix/vector norm orders the backend understands: Frobenius, L2, L1, Infinity, their negatives, Nuclear, and a General { order: F } fallback for arbitrary p-norms. It mirrors numpy.linalg.norm / scipy.linalg.norm.

Why it exists — Many algorithms need a norm (a single number measuring “size”) in different flavors. Instead of a zoo of separate methods, one norm / vector_norm method takes an SKNormKind to say which flavor.

What we rejected — We rejected a separate method per order, and we kept the General p-norm fallback rather than only hard-coding the common cases.

The decomposition containers

These four structs are the results a backend returns. Crucially, each holds plain Array2<F> fields — owned ndarray matrices — so the result does not depend on which backend produced it. That is the host-centric promise made visible: you can take a decomposition from faer, hand it to the BLAS backend, and both are the same type.

SKSingularValueDecomposition<F>

What it is — The result of a singular value decomposition $A = U \Sigma V^{\mathsf{T}}$: fields u (left singular vectors, Array2<F>), singular_values (a Vec<F>, non-increasing), and v (right singular vectors, Array2<F>).

Why it exists — SVD is the workhorse behind pseudo-inverses, lstsq, PCA, and the spectral norm. A concrete, backend-independent container means an algorithm can use the result without caring who computed it.

What we rejected — Backend-native SVD types (faer’s Svd, LAPACK’s), which would leak the backend into every consumer.

SKQRDecomposition<F>

What it is — The result of a (thin) QR decomposition A = Q R: fields q (orthogonal factor) and r (upper-triangular factor), both Array2<F>.

Why it exists — QR is a numerically stable way to solve least-squares problems and to find orthonormal bases.

What we rejected — Any backend-specific QR representation.

SKLUDecomposition<F>

What it is — The result of an LU decomposition P A = L U: fields pivot (a host Vec<usize> row permutation where pivot[i] is the original row that lands at position i), l (unit-lower-triangular), and u (upper-triangular).

Why it exists — LU is the engine behind solve and inv. The pivot is kept as a plain Vec<usize> so the row permutation is portable and readable.

What we rejected — A PivotInfo associated type (design Decision 2): every result is host-resident, so there is nothing backend-specific to abstract.

SKLeastSquaresSolution<F>

What it is — The result of a minimum-norm least-squares solve $x = \operatorname{argmin} , |b - A x|_2$: fields solution (Array2<F>), rank (the effective rank after rcond truncation), singular_values (Vec<F>), and residual_sum_of_squares (an Option<Vec<F>>, present when the system is overdetermined, i.e. more rows than columns).

Why it exists — It bundles everything an algorithm (like Linear Regression) needs to report how well the fit worked, in one backend-neutral struct.

What we rejected — Returning only the solution and making callers recompute rank and residuals — duplicated tolerance logic per caller.

SKFaerBackend

What it is — The pure-Rust default backend. A tiny, zero-field struct that implements SKMathBackend<F> for both f32 and f64 by delegating to the faer library. GEMM uses faer’s blocked matmul (honoring parallelism); decompositions delegate to faer’s high-level SVD/QR/Cholesky/LU/eigendecomposition. No C or Fortran BLAS is linked.

Why it exists — It is the out-of-the-box path: compiles on Rust 1.85 with no external toolchain, so a default build “just works” for everyone (spec blas-interface).

What we rejected — Making a C BLAS the default (would force toolchain setup); using oxiblas (rejected because it fails to compile on Rust 1.85).

SKMatrixMultiplyBackend

What it is — A second pure-Rust backend that routes heavy GEMM to the matrixmultiply crate’s dense kernel. Decompositions aren’t in matrixmultiply, so they delegate to faer, which is always available.

Why it exists — It gives an explicit, non-faer GEMM path — useful as an experiment or fallback for matrix products specifically.

What we rejected — Nothing major; it’s a lean companion to the faer backend, and it exercises the same SKMathBackend contract.

SKNdArrayLinalgBackend

What it is — The opt-in system-BLAS backend, backed by ndarray-linalg over a configured blas-src library (OpenBLAS, BLIS, MKL, or Accelerate). It implements the same SKMathBackend<F> surface for f32 and f64. Its lstsq uses the native LAPACK gelsd driver, and its solve iterates columns of b using the native solve.

Why it exists — When you want the peak performance of a hand-tuned BLAS on your machine, you enable the blas-backend feature and this backend takes over heavy dense algebra. It is gated behind the blas-backend feature and is never on by default.

What we rejected — Making it the default (toolchain cost), and duplicating the whole feature behind an unconditional dependency.

sk_default_math_backend<F>()

What it is — A free function that returns the backend configured for the current build: Box<dyn SKMathBackend<F>>. With blas-backend enabled it returns SKNdArrayLinalgBackend; otherwise SKFaerBackend.

#![allow(unused)]
fn main() {
#[cfg(not(feature = "blas-backend"))]
pub fn sk_default_math_backend<F: SKFloat>() -> Box<dyn SKMathBackend<F>>
where
    SKFaerBackend: SKMathBackend<F>,
{
    Box::new(SKFaerBackend::new())
}
}

Why it exists — The execution planner needs “a math backend” but should not care which build was chosen. This is the single place where build configuration becomes a concrete backend. The #[cfg(...)] attributes mean the compiler picks the right body based on the blas-backend feature — a compile-time decision, so there is no runtime cost to choosing.

What we rejected — Baking the choice into every call site, or forcing callers to name a concrete type (they can’t — they don’t know the build config).

The input wrapper: FaerInput (private)

What it is — A small private enum inside faer_backend.rs that wraps a faer matrix view: either Borrowed(MatRef<'a, F>) for zero-copy input, or Owned(Mat<F>) when a copy was needed.

Why it exists — This is where “host-centric” meets “zero-copy” in practice. When the ndarray input is C-contiguous (row-major), the backend builds a faer view over the same memory — no copy. When the input has a non-standard (strided) layout, faer needs contiguous data, so the backend makes an internal copy. The public surface is always a zero-copy view; the copy, when it happens, is the backend’s private concern (design’s risk note).

What we rejected — Forcing every caller to guarantee contiguous memory (too strict), or always copying (wastes the zero-copy benefit). The Borrowed/Owned pair gives the best of both.

#![allow(unused)]
fn main() {
enum FaerInput<'a, F: SKFloat> {
    Borrowed(MatRef<'a, F>),
    Owned(Mat<F>),
}
}

5. A real walk-through, using the tests

Let’s read three tests from backend_tests.rs and see the ideas in action. The whole suite is deliberately host-centric: fixtures are built from ndarray, and no faer type appears in any test — that’s the discipline the design enforces.

Test 1: GEMM matches a hand-computed reference product

#![allow(unused)]
fn main() {
fn check_gemm_matches_reference_product<F: SKFloat + std::fmt::Debug>()
where
    SKFaerBackend: SKMathBackend<F>,
{
    let a = mat_from_rows(&[
        &[F::one(), F::from(2.0).unwrap()],
        &[F::from(3.0).unwrap(), F::from(4.0).unwrap()],
    ]);
    let b = mat_from_rows(&[
        &[F::from(5.0).unwrap(), F::from(6.0).unwrap()],
        &[F::from(7.0).unwrap(), F::from(8.0).unwrap()],
    ]);
    let backend = SKFaerBackend::new();
    let product = backend.gemm(a.view(), b.view(), F::one(), 1);
    let expected = mat_from_rows(&[
        &[F::from(19.0).unwrap(), F::from(22.0).unwrap()],
        &[F::from(43.0).unwrap(), F::from(50.0).unwrap()],
    ]);
    assert_close(&product, &expected, F::from(1e-4).unwrap());
}
}

Line by line:

  • The function is generic over F and demands SKFaerBackend: SKMathBackend<F> — i.e. “run this for whatever float makes the backend valid.” The same check then runs for f64 and f32 via two tiny #[test] wrappers.
  • mat_from_rows builds a 2-D Array2<F> from slices. F::one() and F::from(2.0) make values without assuming a concrete float type — this is how you write “the number two” generically.
  • We multiply a (the matrix [[1,2],[3,4]]) by b ([[5,6],[7,8]]) with alpha = 1.0. The 1 is parallelism (sequential).
  • The expected matrix is computed by hand: $1 \cdot 5 + 2 \cdot 7 = 19$, $1 \cdot 6 + 2 \cdot 8 = 22$, $3 \cdot 5 + 4 \cdot 7 = 43$, $3 \cdot 6 + 4 \cdot 8 = 50$. This is the “reference” — what matrix multiply must produce, no matter which backend.
  • assert_close checks every element is within 1e-4 (floating-point math is never exact, so we allow a tiny tolerance). The test proves the backend’s gemm is correct, not just that it runs.

Test 2: the trait surface stays host-centric (the compiler is the referee)

#![allow(unused)]
fn main() {
fn assert_host_centric_surface<F: SKFloat, B: SKMathBackend<F> + ?Sized>(
    backend: &B,
    a: Array2<F>,
) {
    let _ = backend.gemm(a.view(), a.view(), F::one(), 1);
    let _: Result<SKSingularValueDecomposition<F>, _> = backend.svd(a.view());
    let _: SKQRDecomposition<F> = backend.qr(a.view());
    let _ = backend.cholesky(a.view());
    let _ = backend.solve_triangular(a.view(), a.view(), true, false);
    let _ = backend.solve(a.view(), a.view());
    let _ = backend.eigh(a.view());
    let _ = backend.lu(a.view());
    let _ = backend.slogdet(a.view());
    let _ = backend.pinv(a.view());
    let _ = backend.inv(a.view());
    let _ = backend.lstsq(a.view(), a.view());
    let _ = backend.norm(a.view(), SKNormKind::Frobenius);
    let _ = backend.vector_norm(a.slice(ndarray::s![.., 0]), SKNormKind::L2);
}
}

Line by line:

  • This function is generic over any backend B: SKMathBackend<F> (note ?Sized, which allows dyn types too). It doesn’t build a backend or check results — it only exercises the whole public surface with ndarray views.
  • Every call passes ArrayView2<F> (a.view()) and every result is typed as an Array2<F>-based container. Notice how we annotate the types (: Result<SKSingularValueDecomposition<F>, _>) — these annotations are the assertion. If the trait leaked a faer type anywhere, the function would not compile with a generic B.
  • The test trait_surface_is_host_centric calls it with SKFaerBackend and with the default backend box:
    #![allow(unused)]
    fn main() {
    let backend = sk_default_math_backend::<f64>();
    assert_host_centric_surface(&*backend, a);
    }
    Both must compile — proving a dyn backend and a concrete backend present the same host-centric face. This is the design Decision 1 made executable: the compiler itself guarantees no backend type leaks.

Test 3: solve_triangular recovers a known solution

#![allow(unused)]
fn main() {
fn check_solve_triangular_upper<F: SKFloat + std::fmt::Debug>()
where
    SKFaerBackend: SKMathBackend<F>,
{
    let a = mat_from_rows(&[
        &[F::from(2.0).unwrap(), F::from(1.0).unwrap()],
        &[F::zero(), F::from(3.0).unwrap()],
    ]);
    let b = mat_from_rows(&[&[F::from(5.0).unwrap()], &[F::from(6.0).unwrap()]]);
    let backend = SKFaerBackend::new();
    let x = backend
        .solve_triangular(a.view(), b.view(), false, false)
        .unwrap();
    // 2x + y = 5; 3y = 6 => y = 2, x = 1.5
    assert!((x[(0, 0)] - F::from(1.5).unwrap()).abs() < F::from(1e-4).unwrap());
    assert!((x[(1, 0)] - F::from(2.0).unwrap()).abs() < F::from(1e-4).unwrap());
}
}

Line by line:

  • a is upper-triangular: [[2,1],[0,3]] (everything below the diagonal is zero). We pass (false, false) — lower = false (it’s upper), unit_diagonal = false.
  • We’re solving $A x = b$, i.e. $2x + y = 5$ and $3y = 6$. By hand: from the second equation, $y = 2$; plugging in, $2x + 2 = 5$, so $x = 1.5$. The comment spells this out.
  • backend.solve_triangular(...).unwrap() asks the backend to solve it; .unwrap() unpacks the Result and panics if there was an error (fine for a test).
  • Two assert!s check $x_{0,0} \approx 1.5$ and $x_{1,0} \approx 2.0$. Note we read the vector using two indices (row, col) — even a column vector is a 2-D Array2 here, so the single column is (0,0) and (1,0). This test checks numerical correctness of a less obvious operation, again generically over f64/f32.

Together, these three tests show the three pillars: correctness (test 1), a clean, backend-agnostic surface enforced by the compiler (test 2), and the expanded kernel working (test 3).


6. Look inside

The one insight. The backend’s power comes from subtracting types from the public surface, not adding them. The moment no faer type appears in the trait, the whole library stops caring which linear-algebra library is behind the curtain — and swapping backends becomes a build-configuration choice instead of a rewrite.

Here is the host-centric boundary as a picture: the library speaks ndarray/sprs, and each backend adapts at the door, translating to and from its own library internally.

flowchart LR
    accTitle: The host-centric backend boundary
    accDescr: The library speaks host types such as ndarray views. Those cross the SKMathBackend trait, which takes array views in and returns owned arrays or decomposition containers out. The default SKFaerBackend adapts to faer, and the opt-in SKNdArrayLinalgBackend adapts to ndarray-linalg over a system BLAS.
    subgraph Host["The library speaks host types (ndarray / sprs)"]
        A["Algorithm (LinearRegression, PCA, ...)"]
        P["Execution planner"]
        C["SKDataView (ndarray views)"]
    end

    subgraph Boundary["SKMathBackend<F: SKFloat>  (the trait)"]
        I["ArrayView2 / ArrayView1 in"]
        O["Array2 / decomposition containers out"]
    end

    subgraph Faer["SKFaerBackend (default, pure Rust)"]
        F1["faer::Mat & MatRef"]
        F2["matrixmultiply GEMM"]
    end

    subgraph Blas["SKNdArrayLinalgBackend (opt-in blas-backend)"]
        N1["ndarray-linalg + blas-src"]
        N2["OpenBLAS / MKL / BLIS / Accelerate"]
    end

    A --> P
    C --> I
    P --> I
    I --> Boundary
    Boundary --> O
    O --> A
    O --> P

    Boundary -- "faer" --> Faer
    Boundary -- "system BLAS" --> Blas

    F1 -. "zero-copy view (contiguous)" .-> F2
    F2 --> O
    N1 --> O

The important detail: the arrows from the trait to Faer and Blas are private — the host never reaches past the boundary. The FaerInput wrapper is the door for faer: borrow the memory when the layout allows, copy only when it must.


7. Recap

  • The backend is host-centric: it accepts ndarray views and returns owned ndarray results, so no concrete linear-algebra library leaks into the public surface.
  • Generic over SKFloat, the sealed bound for f32/f64, gives every operation both float types with code written once.
  • dyn vs generics is a judgment call: concrete backends are generic (fast), but the build-configured default is a Box<dyn SKMathBackend<F>> because the caller can’t know which type is active.
  • faer is the pure-Rust default (works with no C toolchain); system BLAS (ndarray-linalg) is an opt-in feature, chosen at compile time by sk_default_math_backend.
  • Decomposition containers are plain Array2<F> structs, so a result is portable across backends; zero-copy is preserved at the boundary, with internal copies only when input layout demands it.

Next, we’ll look at how the execution planner decides where and how to run work — the layer that calls this backend and composes the algorithms above it.

Module hygiene: folder modules & the tests-at-end rule

A machine-learning library starts as a handful of files and quietly becomes hundreds. Long before the algorithms get hard, the organization gets hard: you open a file to change one small thing and have to scroll through two thousand lines to find it. In this chapter we set up the discipline that keeps a growing Rust codebase navigable — a set of house rules about where code lives, not what it computes. We learn how a Rust file becomes a folder module, why a mod.rs should be a pure dispatcher that carries no logic, and why tests sit beside the implementation they check rather than being sprinkled through it or parked in a far-away tests/ directory.

1. The problem we were solving

Imagine a library that is really a filing cabinet. Early on, when the cabinet has three drawers, it does not matter much how you label them. But as the library grows — dozens of types, dozens of algorithms, thousands of lines — the cabinet fills up, and the way you organize it becomes the difference between finding a document in seconds or in hours.

sciencekit had reached that point. It had settled on a convention: when a source file grows past roughly 200 lines, you split it into a folder — a directory with a special mod.rs file that acts as the “label on the drawer”, telling the compiler what lives inside. And tests were supposed to live in companion files right beside the implementation they check.

But rules only help if every drawer follows them. Fourteen mod.rs files had drifted: instead of being just a label (a pure dispatcher), each of them had grown the actual implementation inline — the drawer label was also doing the filing. And there was no written rule at all about where inline tests must sit within a file. The result was a library where the same file had two jobs, where a small file became a big one and then a folder but nobody had finished the move, and where tests appeared at the top, middle, or bottom depending on whoever wrote them.

The change we walk through in this chapter, module hygiene, was a pure refactor: no new behavior, no new math, no changed results. It simply made every mod.rs a true pure dispatcher and codified the tests-at-end rule. It is the quiet maintenance work that keeps a codebase pleasant to live in, and it is a great lens for learning how Rust organizes code.

2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
mod.rs must be a pure dispatcher — it only declares submodules and re-exports them, carrying no implementation logic.A reader opening kernels/mod.rs should see the drawer’s whole catalogue at a glance, not be handed a wall of math. Every implementation has one obvious home file, so nothing hides. This is exactly the layout already proven in allocator/, builders/, and observability/.Keeping implementation inline in mod.rs (the pre-change drift). It made the catalogue unreadable and gave a single file two jobs.
Split into the minimum descriptive files per concern, not one file per function.A tiny 30-line module does not deserve ten micro-files; one descriptive implementation file plus its companion *_tests.rs reads cleanly and keeps the split meaningful rather than cosmetic.Over-fragmentation — one file per function. Creates a drawer full of matchsticks that is harder, not easier, to navigate.
Tests live in companion *_tests.rs modules beside the implementation.Tests belong next to the code they verify so they are found and updated together; there is no central tests/ graveyard that drifts out of sync.A global tests/ directory at the crate root. It separates tests from what they test and encourages duplication and drift.
The tests-at-end rule: any inline #[cfg(test)] block must sit at the very end of its file; companion test-module declarations go at the end of mod.rs.The implementation reads top-down: a reader reaches the real logic first, then (optionally) the tests. This was codified in AGENTS.md and mirrored in the OpenSpec config because it had never been written down.Allowing inline tests anywhere in the file. A test block in the middle breaks the top-down reading flow and hides the implementation.
A .rs file over ~200 lines becomes a standardized folder module.The line limit is a tripwire: it tells you, mechanically, when a file is doing too much and should become a folder with mod.rs, core_implementation.rs, *_tests.rs, etc.No limit (files grow indefinitely, become unreadable) or a limit enforced by emotion rather than a stated number.

Scope note: one of the fourteen modules, backend/, was deliberately excluded from this refactor. It was owned by a companion change (backend-kernel-expansion) that was restructuring it anyway. Splitting it twice would have caused conflicts, so this change covered the other thirteen and left backend/ alone.

3. The concepts, taught from zero

Rust: what a “module” is

In many languages you group related code into “files” and “packages”. Rust gives you a cleaner idea called a module. A module is simply a named container of code: it can hold functions, types, other modules, and even constants. You create one with the keyword mod:

#![allow(unused)]
fn main() {
mod shapes {
    pub struct Circle { radius: f64 }
}
}

This module is named shapes and contains a type Circle. The pub in front of struct says “let other code outside this module see it”. Without pub, the item stays private — visible only inside shapes.

Modules nest. A module inside a module, inside a module… This nesting is exactly what lets a big codebase be organized like a filing cabinet: each drawer is a module, and a drawer can contain smaller drawers.

How a file becomes a module, and then a folder module

Rust has a convenient rule: the file system can stand in for the module tree. If you write mod shapes; (note the semicolon, not a block), Rust looks for a file named shapes.rs and makes it the body of the shapes module.

But what if shapes grows too big for one file? Then you turn it into a folder:

flowchart TD
  accTitle: A folder module and the role of each file
  accDescr: The shapes directory is the module. Its mod.rs is the label file that declares the module contents, while circle.rs and rectangle.rs are separate implementation files inside the same module.
  ROOT["shapes/ (the module directory)"]
  ROOT --> MOD["mod.rs<br/>the label file: declares the module contents"]
  ROOT --> CIRCLE["circle.rs<br/>one implementation file"]
  ROOT --> RECT["rectangle.rs<br/>another implementation file"]

The special file mod.rs inside a folder is the module. Rust reads mod shapes; and finds the shapes/ folder with its mod.rs, and everything inside that folder becomes part of the shapes module. This is the folder module pattern.

mod.rs as a pure dispatcher

Here is the key discipline of this whole chapter: mod.rs should contain no implementation logic at all. It has exactly two jobs:

  1. Declare the submodules with mod <name>;.
  2. Re-export their public items with pub use, so that code using the folder can reach the items without knowing which file they came from.

A mod.rs that only does these two things is called a pure dispatcher — it does no work itself; it just points to the files that do the work.

pub use: re-exports

pub use is a way to “re-share” an item. Suppose circle.rs defines Circle. Inside shapes/mod.rs you write pub use circle::Circle;. Now anyone who uses the shapes module can write shapes::Circle even though Circle physically lives in circle.rs. This gives you freedom: you can rearrange the files inside the folder without changing anything for the code that uses the folder. The mod.rs is the stable public face; the file layout is an internal detail.

#[cfg(test)]: the compile-time “only when testing” gate

#[cfg(...)] means “configuration”: it tells the compiler to include this item only under certain conditions. #[cfg(test)] means “only include this module when compiling in test mode”. So you can write:

#![allow(unused)]
fn main() {
#[cfg(test)]
mod shapes_tests;
}

This module is compiled only when tests run; in a normal release build it simply does not exist. This is how test code stays out of your shipped library.

Two ways to attach tests

You have two main choices for where test code lives:

  • Inline: a #[cfg(test)] mod … block at the end of the same file as the implementation.
  • Companion module: a separate *_tests.rs file (or folder) beside the implementation file, declared at the end of mod.rs.

sciencekit’s rule: tests live in companion *_tests.rs modules beside the implementation, and any inline tests must sit at the very end of their file. Never a global tests/ directory.

4. Each object, explained

The folder module (mod.rs + submodule files)

What it is: A directory whose mod.rs declares and re-exports its submodules, with each implementation living in its own file inside the folder. Triggered by the ~200-line rule: a single .rs file that crosses that length becomes a folder.

Why it exists: It bounds the size of any one file, gives every piece of code one obvious home, and keeps the public interface stable while the internals are free to rearrange. Opening mod.rs shows the whole catalogue at a glance.

What we rejected: Keeping long files as single giant .rs files (unreadable), and splitting into one file per function (over-fragmented). The folder module is the middle path: big enough to hold a real concern, small enough to read.

Let us look at two real pure-dispatcher mod.rs files. First, kernels from sciencekit_math — the folder that holds the higher-order math kernels:

#![allow(unused)]
fn main() {
//! Higher-order operation kernels built on `azip!`/`par_azip!`/`zip_mut_with`.

mod elementwise;
mod grain;
mod reductions;
mod scaling;

pub use elementwise::{sk_binary_combine, sk_elementwise_transform};
pub use grain::{
    SK_AXIS_SUM_GRAIN, SK_BINARY_COMBINE_GRAIN, SK_ELEMENTWISE_TRANSFORM_GRAIN,
    SK_SCALE_IN_PLACE_GRAIN,
};
pub use reductions::sk_axis_sum;
pub use scaling::sk_scale_in_place;

#[cfg(test)]
mod grain_tests;
#[cfg(test)]
mod kernels_tests;
}

See the structure? Four mod declarations, four pub use re-exports, then the #[cfg(test)] companion test modules at the end. Zero math logic here. If you want to know everything the kernels folder offers, you read this 27-line file and you are done.

Now execution from sciencekit_common — the folder that turns a user’s requested execution intent into a concrete plan:

#![allow(unused)]
fn main() {
//! Execution planning.

mod context;
mod modes;
mod plan;
mod resolve;
mod streaming_driver;

pub use context::SKExecutionContext;
pub use modes::{SKAccessPattern, SKExecutionMode};
pub use plan::SKExecutionPlan;
pub use resolve::sk_resolve_execution_plan;
pub use streaming_driver::{SKStreamDecision, sk_run_streaming_driver};

#[cfg(test)]
mod execution_tests;
#[cfg(test)]
mod streaming_driver_tests;
}

Same shape, slightly bigger: five submodules, five re-export lines, two companion test modules. The data_view and builders folders follow the identical pattern. This consistency is the point — once you have seen one pure-dispatcher mod.rs, you have seen them all.

The companion *_tests.rs module

What it is: A test module that lives beside the implementation it checks, declared with #[cfg(test)] mod …_tests; at the end of mod.rs. It may itself be a single file or a small folder of test files.

Why it exists: Tests and the code they verify are updated together, found together, and reasoned about together. Keeping them adjacent (but in a separate file) means the implementation file reads top-down while the tests stay close by, never in a distant global tests/ directory that drifts out of sync.

What we rejected: A global tests/ directory, and scattering #[cfg(test)] blocks throughout implementation files. Both separate tests from what they test or bury the implementation.

Here is a real companion test folder. The scorer_traits folder holds a mod.rs plus a scorer_traits_tests/ folder whose own mod.rs is:

#![allow(unused)]
fn main() {
//! Companion tests for the scoring contracts (split into a folder module to
//! respect the 200-line limit).
pub mod example_contracts;
pub mod scoring_tests;
}

It is itself a tiny pure dispatcher: it just declares the two test files inside it. This is the folder-module pattern applied recursively to the tests themselves — the tests grew past 200 lines, so they became a folder too.

Compare that with execution, where the two test modules are plain single files (execution_tests.rs, streaming_driver_tests.rs) because each stayed under the limit. The rule adapts: small tests, one file; big tests, a folder.

The 200-line rule

What it is: A stated convention that a .rs file over roughly 200 lines becomes a standardized folder module, with files named by role (mod.rs, core_implementation.rs, *_tests.rs, and for builders builder.rs).

Why it exists: It is a mechanical tripwire that triggers exactly when a file is doing too much. You do not need to argue about taste — you count lines, and past the limit you split. It keeps every file a comfortable size and gives every concern a named home.

What we rejected: No limit (files grow into impenetrable walls of text) and an emotionally enforced limit (inconsistent — one developer’s “fine” is another’s “too long”). A hard, stated number is uniformly applied.

5. A real walk-through, using the tests

Tests are our executable documentation, so let us read two real tests and see what the test-at-end, companion-module organization enables.

Test 1: prefetching under a streaming plan

This test lives in execution/streaming_driver_tests.rs — a companion file to the streaming_driver.rs implementation. It checks a subtle concurrency promise: while one batch is computing, the driver should already be reading the next one (this is called prefetch). The test is reader_advances_while_compute_runs:

#![allow(unused)]
fn main() {
#[test]
fn reader_advances_while_compute_runs() {
    let (mut source, read_log, _outstanding, _max) = RecordingSource::new(5, None);
    let finish_log: Arc<Mutex<Vec<(usize, Instant)>>> = Arc::new(Mutex::new(Vec::new()));
    let finish = Arc::clone(&finish_log);
    let update = move |batch: SKDataBatch<f64>, _parallelism: usize, _state: &mut ()| {
        thread::sleep(Duration::from_millis(50));
        finish
            .lock()
            .unwrap()
            .push((batch.position(), Instant::now()));
        SKStreamDecision::Continue
    };
    let mut state = ();
    sk_run_streaming_driver(&mut source, &mut state, update, &streaming_plan()).unwrap();

    let reads = read_log.lock().unwrap().clone();
    let finishes = finish_log.lock().unwrap().clone();
    let read_time = |index: usize| reads.iter().find(|(i, _)| *i == index).map(|(_, t)| *t);
    let finish_time = |index: usize| finishes.iter().find(|(i, _)| *i == index).map(|(_, t)| *t);

    // For every k except the last, batch k+1 was read before batch k finished.
    for k in 0..4 {
        let read_next = read_time(k + 1).expect("batch k+1 must be read");
        let done = finish_time(k).expect("batch k must complete");
        assert!(
            read_next < done,
            "batch {} read after batch {} finished — no prefetch overlap",
            k + 1,
            k
        );
    }
}
}

Let us read it slowly. The test creates a RecordingSource with 5 batches (the RecordingSource is a small instrumented stand-in defined right in the test file: it logs every read and records the time). The update closure is the “computation”: it simulates work by sleeping 50 milliseconds, then logs which batch finished and when. We then run the streaming driver over the source with this callback.

After the run, the test grabs two logs: reads (when each batch was read) and finishes (when each batch finished). The clever part is the loop. For every batch k from 0 to 3, it asserts that batch k + 1 was read before batch k finished:

#![allow(unused)]
fn main() {
assert!(read_next < done, "batch {} read after batch {} finished — no prefetch overlap", ...);
}

If the driver were naive and processed one batch fully before touching the next, batch k+1 would be read after batch k finished, and this assertion would fail. So this one test pins down the whole prefetch contract: the reader runs ahead while compute runs. That is a subtle piece of concurrency, expressed clearly in ~20 lines, sitting in a file right beside the streaming_driver.rs code it validates.

Test 2: pure scoring must not re-infer

This test lives deeper — inside the scorer_traits/scorer_traits_tests/scoring_tests.rs folder. It checks a design contract: a scorer has a “pure” form that scores from predictions you already have, and it must not run the model again. Here it is:

#![allow(unused)]
fn main() {
#[test]
fn label_pure_form_does_not_re_infer() {
    let scorer = accuracy::<f64, ConstantClassifier>();
    let truth = array![1_i64, 1, 0];
    let labels = array![1_i64, 1, 1];
    let score = <Accuracy as SKLabelScorer<f64, ConstantClassifier>>::score_from_labels(
        &scorer,
        SKTargetView::try_from(truth.view()).unwrap(),
        labels.view(),
    )
    .unwrap();
    // 2 of 3 correct (predicted 1,1,1 vs true 1,1,0).
    assert!((score - 2.0 / 3.0).abs() < 1e-9);
}
}

The test sets up truth [1,1,0] and labels [1,1,1]. A ConstantClassifier always predicts label 1, so 2 of the 3 labels match the true labels. The score should be 2/3. We call the pure form directly, score_from_labels, handing it both the truth and the labels — and check the result equals 2/3 (within floating-point tolerance, hence the .abs() < 1e-9).

The sibling test label_convenient_form_runs_inference_and_delegates then verifies the other path: the convenient form runs the model once to get labels, then delegates to the same pure form — and the two scores match. Together, the two tests pin down that the pure form never re-infers and that both paths agree. All of this lives in a companion folder beside the scoring implementation, exactly as the hygiene rules demand.

What both walk-throughs show

Neither of these tests is in some far-away tests/ directory. Each sits beside the code it tests, in a companion module declared at the end of the relevant mod.rs. Because of the tests-at-end rule, the implementation files read top-down, and because of the pure-dispatcher rule, their mod.rs files are tiny catalogues. When a future engineer wonders “is prefetching really overlapped?”, the test is one folder over.

6. Look inside

The one insight: module hygiene is not about style points — it is about making a large codebase navigable. A pure-dispatcher mod.rs turns every folder into a one-screen catalogue, and the tests-at-end rule keeps every implementation file reading top-down. None of this computes a single number; all of it decides whether a growing library stays pleasant to work in.

Here is the folder-module tree for a couple of the real modules we studied, showing how mod.rs sits as the dispatcher above implementation files and companion tests:

flowchart TD
    accTitle: Two folder modules showing the pure-dispatcher pattern
    accDescr: Each folder module has a mod.rs that acts as a pure dispatcher, implementation files for each concern, and companion test files. The kernels folder holds elementwise, grain, reductions and scaling; the execution folder holds context, modes, plan, resolve and the streaming driver.
    subgraph K["sciencekit_math :: kernels/ (folder module)"]
        direction TB
        K_RS["mod.rs<br/><i>pure dispatcher</i>"]
        K_ELEM["elementwise.rs"]
        K_GRAIN["grain.rs"]
        K_RED["reductions.rs"]
        K_SCAL["scaling.rs"]
        K_TESTS["kernels_tests.rs + grain_tests.rs<br/><i>companion tests</i>"]
    end

    subgraph E["sciencekit_common :: execution/ (folder module)"]
        direction TB
        E_RS["mod.rs<br/><i>pure dispatcher</i>"]
        E_CTX["context.rs"]
        E_MODES["modes.rs"]
        E_PLAN["plan.rs"]
        E_RES["resolve.rs"]
        E_DRV["streaming_driver.rs"]
        E_TESTS["execution_tests.rs + streaming_driver_tests.rs<br/><i>companion tests</i>"]
    end

    K_RS --> K_ELEM
    K_RS --> K_GRAIN
    K_RS --> K_RED
    K_RS --> K_SCAL
    K_RS -.-> K_TESTS

    E_RS --> E_CTX
    E_RS --> E_MODES
    E_RS --> E_PLAN
    E_RS --> E_RES
    E_RS --> E_DRV
    E_RS -.-> E_TESTS

    style K_RS fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
    style E_RS fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
    style K_TESTS fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d,stroke-dasharray:5 5
    style E_TESTS fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d,stroke-dasharray:5 5

The solid arrows show mod.rs declaring its implementation submodules; the dashed arrows show it declaring the #[cfg(test)] companion test modules. Notice that every solid child is a real implementation file and every dashed child is a test file — and mod.rs itself, at the top of each folder, holds no logic at all.

7. Recap

  • A folder module (mod.rs inside a directory) is how Rust lets one conceptual module span multiple files once a single .rs file passes ~200 lines.
  • mod.rs must be a pure dispatcher: it only mod-declares submodules and pub use-re-exports them. It carries no implementation logic, so it reads as a one-screen catalogue.
  • Tests live in companion *_tests.rs modules beside the implementation — never in a distant global tests/ directory — and are declared with #[cfg(test)] at the end of mod.rs.
  • Tests-at-end: any inline #[cfg(test)] block sits at the very end of its file, so the implementation reads top-down.
  • This was a pure refactor: no behavior changed, every test stayed green. The value is purely in how the codebase is organized and how easy it is to navigate.

That is the discipline of module hygiene. In the next chapters we put this tidy filing cabinet to work as we climb back up to the algorithms — now that every folder has a clean label, we can always find where the math actually lives.

Parallel kernels and the streaming executor

Modern machines have many cores, but your data comes in all sizes. A library that blindly parallelizes everything wastes time on a 4-element array, and a library that never parallelizes ignores most of the hardware. And when a dataset is too large to hold in memory, the same library must keep the disk reader and the CPU working at the same time, not one after the other. This chapter explains how sciencekit decides how much parallelism each operation deserves, how the math kernels switch between sequential and parallel execution at the push of a single number, and how a streaming executor overlaps reading with computing so big data never idles the CPU.


1. The problem we were solving

Imagine a kitchen with several cooks. Each cook can chop vegetables independently — that is parallelism. But handing a single carrot to all four cooks is absurd: the time they spend arguing over who chops which slice is longer than just chopping it. The cooks are only worth using when there is a pile of carrots. Now add an oven: while one cook is waiting for the oven, the other cook can keep chopping the next tray. That overlap — preparing the next batch while the current one bakes — is what a streaming library must do when the vegetable pile is bigger than the counter can hold.

Before this change, sciencekit’s kitchen was incoherent. The library already had a resolver that produced an SKExecutionPlan with a parallelism field — how many threads to use — but nothing in the math layer actually read that field. The scaling kernel parallelized even a 4-element array (four cooks, one carrot), while the elementwise, binary, and reduction kernels never parallelized at all, no matter how big the data was. Parallelism was decided by accident, not by a plan.

Three things were missing. First, a decision rule: given the data size, the number of cores, and the known cost of each kernel, how many threads should an operation use — or should it stay sequential? Second, kernels that honor the plan: each math primitive must actually branch on the resolved parallelism. Third, a streaming executor: a reusable piece that runs the reader and the compute concurrently through a double buffer, so out-of-core data is processed without the CPU ever sitting idle waiting for the disk.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Parallelism is decided at resolution time, not inside the kernelEach kernel takes a parallelism: usize and only branches 1 → sequential / > 1 → parallel. All policy lives in sk_resolve_execution_plan, which stays pure and deterministic (spec higher-order-kernels: kernels “honor the resolved parallelism”).Unconditional par_azip! everywhere (a regression on small data); per-kernel internal thresholds (duplicated policy, untestable without a real machine); separate _par function variants (a duplicated API, pushing the decision onto every caller).
The crossover rule is min(cores, ceil(unit / grain)), with a grain measured per kernelA grain is the minimum elements per thread needed to amortize parallel-dispatch overhead. The number of threads is ceil(unit / grain) clamped to cores, so a unit below one grain stays sequential. Each kernel gets its own measured grain (cheap, medium, expensive closures over sizes 10¹–10⁷), reused identically in memory and streaming (design: “reuse one measured grain per kernel across regimes”).A single global threshold constant (wrong for at least one of machine, algorithm, or data); closure-cost hints plumbed into resolution (possible future extension, deferred until benches justify it).
Conservative grain direction: large in-memory, full streamingIn memory, an expensive closure parallelizing “late but well” is the safe error, so the grain errs large. In streaming, parallelism = cores by default: excess compute parallelism is nearly free while the pipeline is I/O-bound (cores idle between batches), but starvation when compute-bound loses the whole speedup.parallelism = 1 while streaming (discards compute-bound speedup, assumes disk-bound); runtime-adaptive measured downscaling (breaks the pure-resolution contract as a first version).
One generic streaming driver, not per-algorithm pipelinesA single sk_run_streaming_driver in sciencekit_common owns the prefetch pipeline — ordering, error propagation, final-batch delivery, early stop — so algorithms only write an update(batch, state) step. Concurrency subtleties get written and tested once.Per-algorithm prefetch loops (N copies of subtle concurrency code); a Tokio pipeline for disk sources (unnecessary dependency for synchronous iteration).
Axis-0 reductions parallelize via per-chunk partial accumulationParallel column sums split rows into chunks; each chunk accumulates into its own partial vector, then the partials are combined. No two threads ever write the same accumulator, so there is no race and no shared-mutable-state bookkeeping.Atomics on a shared accumulator (contention and a different summation order each run); keeping axis-0 sequential (asymmetric loss — it is the common shape for column statistics).

3. The concepts, taught from zero

Rust concept 1: rayon and parallel iterators

rayon is a Rust library for easy data parallelism. Instead of writing a loop that visits each element, you hand rayon an iterator and it splits the work across a pool of threads, giving you the result as if you’d run the loop sequentially — but faster.

The clever part is that a normal iterator and a parallel iterator have the same shape, so switching costs one word. An iterator produces items one at a time via a method that yields an Option (an optional value: Some(item) or None). A parallel iterator (into_par_iter, par_iter) distributes those items across threads. The whole point of this chapter’s design is that the kernels use the same higher-order iteration for both paths, only changing the kind of iterator based on the resolved parallelism.

Rust concept 2: azip! and par_azip! — looping without index arithmetic

ndarray is the array library sciencekit uses. The macros azip! and par_azip! are its idiomatic way to visit all elements of one or more arrays together — the “apply f pairwise across these arrays” operation. azip! is sequential; par_azip! is the rayon-parallel version. They share the same syntax, which is exactly why the kernels can swap them with a one-line branch.

#![allow(unused)]
fn main() {
use ndarray::{Array, ArrayView, azip, par_azip};

let mut output = Array::zeros(input.dim());
if parallelism > 1 {
    par_azip!((out in &mut output, a in input) { *out = transform(*a); });
} else {
    azip!((out in &mut output, a in input) { *out = transform(*a); });
}
}

Inside the macro body, out is a mutable reference to each output element and a is a reference to each input element. The macro visits every element position once, pairing the output slot with its input element. This is a higher-order form — you provide the closure (the { ... } body) and the library provides the traversal. The project’s rule is never a manual index loop: writing output[i] = f(input[i]) by hand is forbidden, because the macro form is clearer, safer, and lets the same body run parallel with a one-word change.

Rust concept 3: closures capturing by move

A closure is an anonymous function you can define inline and pass around. |x| 2.0 * x + 1.0 takes one argument and returns twice it plus one. A closure can capture variables from the surrounding scope — “remember” them. In sciencekit’s kernels the closure must be Sync + Send:

#![allow(unused)]
fn main() {
pub fn sk_elementwise_transform<F: SKFloat>(
    input: &ArrayView<F, ndarray::Ix1>,
    transform: impl Fn(F) -> F + Sync + Send,
    parallelism: usize,
) -> Array<F, ndarray::Ix1>
}
  • Sync means the value is safe to be referenced from multiple threads at once.
  • Send means it is safe to be moved to another thread.

These bounds are required because par_azip! takes the closure and runs it on the rayon pool — across many threads simultaneously. The compiler enforces this: if you try to capture a value that is not Sync + Send, the code will not compile. This is Rust pushing the mistake out of the running program and into the compiler: a closure that cannot safely run in parallel is rejected before it ever runs.

Numerical concept 1: what “grain” means

Parallelism has a fixed dispatch overhead: splitting work, coordinating threads, and rejoining them all cost time. A single thread on a tiny array is therefore faster than many threads, because the overhead swamps the tiny amount of work. The grain is the minimum number of elements per thread that makes a thread worth spawning.

Think of it as the “amortization” point. If a thread must process at least g elements to pay for the cost of spawning it, then for a unit of u elements you can afford at most ceil(u / g) threads. The resolver computes:

threads = min(cores, ceil(unit_elements / grain))
  • If unit_elements < grain, then ceil(unit / grain) = 1, so it runs on one thread — sequential.
  • If unit_elements is huge, ceil climbs toward the core count, where it is capped.

The grain is measured per kernel by a calibration benchmark, not guessed. grain.rs records the measured crossover for each kernel on a specific machine and date — that is called provenance (where the number came from) — so a magic constant is never unexplained. The same grain applies to in-memory and streaming work, because dispatch overhead and per-element cost do not change just because the data came from disk.

Numerical concept 2: the “work unit” — whole dataset vs one batch

The grain needs a unit to be applied to: the number of elements we are parallelizing over. This is where mode matters:

  • In-memory: the work unit is the whole dataset. unit = dataset_elements.
  • Streaming: compute happens one batch at a time, so the work unit is one batch. unit = batch_size_hint.
  • Memory-mapped: an arbitrary shard can be touched, so unit is treated as “always large” and resolves to cores.

This is why the same parallelism field means “threads for the current operation’s unit”, decided once at resolution and carried in the plan down to each kernel.

Numerical concept 3: double buffering — the producer/consumer overlap

Reading from disk (or any slow source) and computing are two different speeds. If they run strictly one after the other, one of them is always idle: the disk waits while the CPU computes, then the CPU waits while the disk reads.

Double buffering fixes this with a producer/consumer relationship:

  • A producer (the reader) fetches batches from the source.
  • A consumer (the compute side) processes them.
  • Between them sits a bounded buffer — a fixed-size queue of batches.

The producer and consumer run on different threads. While the consumer computes batch k, the producer reads batch k+1 into the buffer. When the consumer finishes batch k, batch k+1 is already waiting — no idle time. The buffer is bounded (it holds at most buffer_depth prefetched batches, plus the one being computed) so the reader never runs unboundedly ahead.

The name “double buffering” refers to the simplest bound: buffer_depth = 1, so at most one batch is computing and one is prefetched — two resident batches. That is why the resolver checks $2 \times \text{batch} \le \text{available memory}$ before it will even allow a streaming plan: two batches must fit in RAM. The plan field is literally called buffer_depth, and 1 is double buffering.

Numerical concept 4: closures for per-element math, not shared accumulators

When a kernel reduces many rows into one answer (a sum), the naive parallel temptation is a single shared accumulator every thread adds to. That needs locking (slow) or atomics (also slow, and order-dependent). The design instead gives each chunk its own partial accumulator, computed in parallel with no sharing, then combines the partials at the end. This is lock-free and race-free by construction: no two threads ever touch the same memory while running. (The trade-off is that floating-point addition is not associative, so a parallel sum may differ from a sequential one in the last bits — which is why the tests compare with a tolerance, never bit-for-bit equality.)


4. Each object, explained

parallelism_for (private, but the heart of the decision)

What it is: A private helper inside the resolver (resolve.rs) that computes the parallelism for a resolved mode: min(cores, ceil(unit / grain)). It returns 1 if there are at most one core, if the unit is unknown or zero, or if the unit is below one grain.

Why it exists: It is the single, pure place where “how many threads?” is answered from the size of the work unit — whole dataset for in-memory, one batch for streaming, $\infty$ (so “always cores”) for memory-mapped shards. Because it is a pure function of the context, it is testable by injecting simulated values with no real machine involved (see grain_governs_resolution_across_regimes below).

What we rejected: A fixed global threshold, reading sysinfo inside the resolver, and deciding parallelism per-kernel at the point of execution. All of those either couple the decision to the physical machine or duplicate the policy. The number, the unit, and the grain all flow through this one formula, deterministically.

sk_elementwise_transform

What it is: The free-scope kernel sk_elementwise_transform(input, transform, parallelism) -> Array, which maps x → transform(x) over a 1-D vector and returns a brand-new owned array. It branches on parallelism: 1 runs the sequential azip!, > 1 dispatches par_azip!.

Why it exists: It is the most basic building block of “do something to every element.” It must exist in both sequential and parallel form because a transform closure can be cheap (e.g. multiply) or expensive (e.g. sin), so the right amount of parallelism changes. The iterator form (never a manual index loop) honors the project’s higher-order-function rule.

What we rejected: A single always-parallel version (a regression on the cheap-closure, small-array case) and two separate functions for the two paths (a duplicated API that pushes the decision onto every caller). One function, one parallelism number, two internal paths.

sk_binary_combine

What it is: The kernel sk_binary_combine(left, right, combine, parallelism) -> Array, pairing each element of left with the corresponding element of right and applying combine(left_value, right_value). It asserts the two inputs have equal length, seeds the output from left, then branches: > 1 uses a three-array par_azip!, 1 uses the sequential zip_mut_with.

Why it exists: Many operations (adding two matrices, elementwise products, comparisons) take two inputs and produce one output. It needs the same parallel/sequential switch as the unary transform. Its measured grain is the largest of the set (10⁷) precisely because a three-array par_azip! has the highest dispatch overhead — a measured fact recorded in grain.rs, not a guess.

What we rejected: Running combine on an index loop; writing into one input in place without seeding from left (that would destroy left); and a shared-accumulator approach. The three-array zip keeps all three buffers aligned by construction.

sk_axis_sum

What it is: The reduction kernel sk_axis_sum(input, axis, parallelism) -> Array, summing a 2-D array along one axis into a 1-D result. axis = 0 collapses rows (per-column sums, length = columns); axis = 1 collapses columns (per-row sums, length = rows). It has four paths: sequential and parallel for each axis.

Why it exists: Reductions are where parallelism is most valuable and most dangerous. The axis-0 parallel path uses per-chunk partial accumulation: rows are split into chunks, each chunk sums into its own partial vector, then the partials are combined. This never writes a shared accumulator concurrently. Axis-1 parallelizes trivially, one independent row per thread. The sequential fallbacks exist so small data (or parallelism = 1) avoids all dispatch.

What we rejected: Atomics on a shared accumulator (contention and nondeterministic order), and a single shared output array written by all threads (a data race). The partial-accumulation design is race-free by construction and only reorders the final floating-point additions by a few bits — which the tolerance-based assert_close contract in the tests accepts.

sk_run_streaming_driver

What it is: The free-scope executor sk_run_streaming_driver(source, state, update, plan) -> Result<(), SKError>. It spawns a dedicated producer thread that reads batches from an SKLazySource into a bounded double buffer, while the caller’s thread consumes each owned SKDataBatch and applies the algorithm-supplied update(batch, parallelism, state) closure. update returns an SKStreamDecision — Continue or Stop — to steer the pipeline.

Why it exists: It is the reusable embodiment of the I/O ∥ CPU overlap. Ordering, error propagation, final-batch delivery, and early stop are written and tested once; an algorithm gains streaming by writing only its update step. The compute side never blocks on input waits — the producer thread does the waiting, on its own thread, while rayon computes on the pool.

What we rejected: Reading and computing on the same thread (no overlap); letting the producer read unboundedly ahead (hence the bounded buffer_depth); and a Tokio-based pipeline for synchronous disk sources (an unnecessary dependency). A plain scoped thread is enough for the synchronous SKLazySource contract.


5. A real walk-through, using the tests

The most convincing way to learn is to read actual passing tests. Here are three: two from grain_tests.rs that exercise the decision rule, and one from kernels_tests.rs that proves a parallel reduction equals the sequential reference.

Test 1: grain_governs_resolution_across_regimes

This test proves that a unit below the grain stays sequential (parallelism = 1) and a unit far above it parallelizes — using only a simulated context, never the physical machine.

#![allow(unused)]
fn main() {
#[test]
fn grain_governs_resolution_across_regimes() {
    let grain = SK_AXIS_SUM_GRAIN;
    let below = context(Some((grain - 1) as u64), grain, 8);
    let above = context(Some((grain * 8) as u64), grain, 8);

    let below_plan = sk_resolve_execution_plan(SKExecutionMode::Automatic, &below).unwrap();
    let above_plan = sk_resolve_execution_plan(SKExecutionMode::Automatic, &above).unwrap();

    assert_eq!(below_plan.parallelism, 1);
    assert_eq!(above_plan.parallelism, 8);
}
}

Line by line:

  1. let grain = SK_AXIS_SUM_GRAIN; — we grab the axis-sum kernel’s measured grain (100,000 elements) directly from the constant in grain.rs.
  2. let below = context(Some((grain - 1) as u64), grain, 8); — the test helper context builds an SKExecutionContext by hand. The Some(grain - 1) is the dataset element count: one fewer than one grain. The grain argument is the kernel’s grain, and 8 is the simulated core count. So this context says: 99,999 elements, grain 100,000, 8 cores.
  3. let above = context(Some((grain * 8) as u64), grain, 8); — a dataset of eight grains (800,000 elements) on the same 8 cores.
  4. We resolve an Automatic plan for each. .unwrap() asserts resolution succeeds.
  5. assert_eq!(below_plan.parallelism, 1) — because ceil(99,999 / 100,000) = 1, the plan is sequential even though 8 cores are available. The work is too small to pay for threads.
  6. assert_eq!(above_plan.parallelism, 8) — ceil(800,000 / 100,000) = 8, clamped to the 8 cores, so it parallelizes fully.

The lesson: the grain is the throttle. The same resolver, same cores — only the size changed, and the parallelism followed the min(cores, ceil(unit / grain)) rule exactly. Nothing about a real machine was read.

Test 2: every_kernel_exposes_a_positive_grain

This short test guards the provenance: every kernel must have a real, positive grain constant — never a zero or a placeholder that would silently disable parallelization.

#![allow(unused)]
fn main() {
#[test]
fn every_kernel_exposes_a_positive_grain() {
    for grain in [
        SK_ELEMENTWISE_TRANSFORM_GRAIN,
        SK_BINARY_COMBINE_GRAIN,
        SK_AXIS_SUM_GRAIN,
        SK_SCALE_IN_PLACE_GRAIN,
    ] {
        assert!(grain > 0);
    }
}
}

Line by line:

  1. The test iterates over the four measured grain constants from grain.rs.
  2. assert!(grain > 0) — each must be strictly positive. A grain = 0 would make ceil(unit / 0) a division-by-zero hazard; a grain of usize::MAX would effectively disable parallelism forever. This test pins the constants to a sane, measured range.

The lesson: these are measured numbers with provenance (machine, date, protocol) recorded in grain.rs, and this test keeps them honest. A kernel whose grain was never calibrated cannot silently ship a wrong constant.

Test 3: parallel_axis_zero_sum_matches_sequential_reference

This test proves the race-free parallel axis-0 reduction equals the sequential column sums within floating-point tolerance — across many rows, where a naive shared accumulator could race.

#![allow(unused)]
fn main() {
#[test]
fn parallel_axis_zero_sum_matches_sequential_reference() {
    let (rows, cols) = (4096, 256);
    let input: Array2<f64> =
        Array2::from_shape_fn((rows, cols), |(i, j)| (i as f64) * 0.001 + (j as f64) * 0.5);
    let sequential = sk_axis_sum(&input.view(), 0, 1);
    let parallel = sk_axis_sum(&input.view(), 0, 8);
    assert_close(&sequential, &parallel);
}
}

Line by line:

  1. let (rows, cols) = (4096, 256); — a wide, tall matrix: 4,096 rows and 256 columns.
  2. Array2::from_shape_fn((rows, cols), |(i, j)| ...) — build the array by computing each cell from its position (i, j). This avoids listing 1M numbers by hand and gives every element a deterministic value. The closure |(i, j)| (i as f64) * 0.001 + (j as f64) * 0.5 blends row and column contributions so the columns are genuinely different.
  3. let sequential = sk_axis_sum(&input.view(), 0, 1); — reduce along axis 0 (per-column sums) with parallelism = 1, which runs the plain sequential path.
  4. let parallel = sk_axis_sum(&input.view(), 0, 8); — the same reduction with parallelism = 8, which takes the parallel path: rows split into chunks, each chunk sums into its own partial vector, then the partials are combined.
  5. assert_close(&sequential, &parallel) — compare the two within a relative floating-point tolerance (1e-9, scaled by magnitude). Because the parallel path reorders the floating-point additions (chunk partials summed in a different order), the result may differ in the last bits — but never beyond tolerance. This is the contract the design documents: parallel is correct, not bit-identical.

The lesson: the parallel path produces the right column sums across 4,096 rows without any shared-accumulator race — and the tolerance-based comparison is what makes “parallel equals sequential” a testable guarantee rather than a hope.


6. Look inside

One strong insight: parallelism is not a property of a kernel — it is a decision made once, from the size of the work unit and a measured per-kernel grain, carried in the plan down to every math primitive. The kernels themselves are embarrassingly boring: one number, one branch, `azip!` or `par_azip!`. And the streaming executor reuses that same plan on the compute side while a producer thread keeps the disk busy — so the decision and the overlap are each written once and reused everywhere.

Here is the full pipeline, from resolution to a parallel kernel, and the double-buffer producer/consumer that keeps streaming from ever idling the CPU:

flowchart TD
    accTitle: The resolve, parallel kernel and streaming pipeline
    accDescr: Resolution turns an execution context into an execution plan with parallelism and batch size. Kernels branch on parallelism to use a parallel or sequential iterator. A streaming plan hands the parallelism to a double-buffered producer and consumer, so reading and computing overlap.
    subgraph resolve[Resolution — pure & deterministic]
        CTX[SKExecutionContext<br/>memory · cores · unit size · grain] --> RES[sk_resolve_execution_plan]
        RES --> PLAN[SKExecutionPlan<br/>mode · parallelism · batch_size · buffer_depth]
    end

    PLAN -->|parallelism & batch_size| KERNEL
    subgraph compute[Parallel kernels]
        KERNEL{parallelism > 1?}
        KERNEL -- yes --> PAR[par_azip! across the compute pool]
        KERNEL -- no --> SEQ[azip! / zip_mut_with — sequential]
        PAR --> OUT[owned result]
        SEQ --> OUT
    end

    PLAN -->|OutOfCoreStreaming| DRIVER
    subgraph stream[Streaming executor — producer/consumer]
        PROD[Producer thread · reads batch k+1] --> BUF[Double buffer<br/>buffer_depth = 1]
        BUF --> CON[Consumer · update batch k → state]
        CON -->|Continue / Stop| CON
    end

    style resolve fill:#fef3c7,stroke:#d97706,color:#78350f
    style compute fill:#f0fdf4,stroke:#16a34a,color:#14532d
    style stream fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e

Reading the left branch: resolution decides parallelism from the context’s unit size and the kernel’s grain, and each kernel branches on that one number to pick its sequential or parallel iterator. Reading the right branch: a streaming plan hands the same parallelism to the driver, whose producer thread prefetches batch k+1 while the consumer computes batch k on the rayon pool — compute never blocks on input, and the reader never runs more than buffer_depth ahead.

Here is that double-buffer overlap as a timeline, showing the producer and consumer advancing in step:

sequenceDiagram
    accTitle: Double-buffered streaming timeline
    accDescr: The producer reads batches into a double buffer while the consumer computes, so reading batch one overlaps computing batch zero and the reader never runs more than buffer depth ahead.
    participant P as Producer (reader)
    participant B as Double buffer
    participant C as Consumer (compute)

    P->>B: enqueue batch 0
    B->>C: deliver batch 0
    Note over P,C: compute batch 0 overlaps read batch 1
    P->>B: enqueue batch 1
    C-->>C: update(batch 0)
    B->>C: deliver batch 1
    C-->>C: update(batch 1)
    Note over P,C: compute batch 1 overlaps read batch 2
    P->>B: enqueue batch 2
    B-->>C: ... continue

The producer and the consumer advance on different threads, so while the consumer runs update(batch k), the producer is already enqueuing batch k+1. That is the I/O ∥ CPU overlap the spec streaming-executor requires, bounded by the plan’s buffer_depth.


7. Recap

  • Parallelism is a decision, not a kernel trait. sk_resolve_execution_plan computes min(cores, ceil(unit / grain)) once, and every kernel honors the resulting parallelism with a single azip!/par_azip! branch.
  • The grain is measured, with provenance. Each kernel’s grain (minimum elements per thread) comes from a calibration benchmark on a specific machine and date — not a guessed constant — and a positive-grain test keeps the constants honest.
  • The work unit changes with the mode. In-memory parallelizes over the whole dataset, streaming over one batch, memory-mapped over arbitrary shards — but the same grain rule governs all three.
  • Reductions are parallelized race-free. Axis-0 sums use per-chunk partial accumulation, never a shared accumulator, and compare against the sequential reference within float tolerance rather than bit-identity.
  • The streaming executor overlaps I/O and compute. sk_run_streaming_driver runs a producer thread into a bounded double buffer while the consumer computes on the rayon pool, delivering ordered, owned batches and stopping early on request.

Next chapter: with the substrate in place, we build the first real algorithm on top of it — SKStandardScaler, the estimator template every later algorithm copies.

The first algorithm: SKStandardScaler

Phase 0 built the vocabulary of sciencekit — the traits, the execution planner, the kernels, the streaming executor — but nothing that a user would actually call to train a model. This chapter is about the first such thing: SKStandardScaler, the estimator that rescales every column of a dataset to have mean zero and standard deviation one. It is a deliberately simple algorithm, and that is exactly why it goes first: it is the template that every later estimator — linear models, trees, clusters — will copy, so any flaw in the template would be copied a dozen times. Along the way we meet the first real use of the builder pattern, of the backend selection, of the streaming executor, and of a brand-new kernel that computes the sum of squares.


1. The problem we were solving

Picture two columns of a dataset. One is a person’s age, ranging from 18 to 90. The other is their income in dollars, ranging from 0 to 500 000. Almost every machine-learning algorithm compares columns by distance: a difference of 10 in age is a 10, and a difference of 10 in income is also a 10 — but the first is a meaningful gap and the second is noise. The columns are on wildly different scales, so the algorithm silently decides that income matters 5 000 times more than age. Standardization fixes this: for each column, subtract its mean and divide by its standard deviation, so every column ends up with mean 0 and spread 1 and no column can shout over the others.

The arithmetic is easy; the engineering is the point. sciencekit promises three ways to fit the same model, and all three must agree:

  • Dense — the whole dataset sits in memory; one pass, done.
  • Incremental — the data arrives in batches and the model keeps learning with partial_fit, never re-reading the past.
  • Out-of-core — the data is a stream from disk, larger than memory; the model consumes it batch by batch, overlapping the disk read with the computation.

If those three paths disagree — even by a rounding error that compounds — the library is lying to the user. And there was no algorithm crate at all yet: no sciencekit_preprocessing, no estimator/model split, no place where the builder pattern, the backend parameter and the execution plan all came together. This change had to invent that shape.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Estimator and model are different typesSKStandardScaler is configuration (what the user asked for); SKStandardScalerModel<F> is learned state (what the data produced). fit turns one into the other. This matches scikit-learn’s fit → fitted estimator, gives one obvious thing to export/serialize, and makes “not yet fitted” impossible to represent.One mutable estimator with an internal “fitted?” flag — then “not fitted” is a runtime state you must check everywhere, and the export boundary is ambiguous.
Running moments are the single source of truthThe model stores sample_count, the per-column mean and the sum of squared deviations. The public mean/scale arrays are derived from them on every update. Dense, streaming and incremental fits all reduce to the same three quantities, so they converge by construction.Storing mean/scale directly and accumulating them — the incremental merge would have to un-apply the with_mean/with_std masking to recover the raw moments, and zero-variance handling would drift between regimes.
One exact merge formula in every regimeDense fit computes column sums and sums of squares, then derives the deviations with $\sum(x-\mu)^2 = \sum x^2 - 2\mu\sum x + n\mu^2$. Streaming and partial_fit compute the same per-batch moments and merge them with the Chan–Golub–LeVeque update. Because the merge is exact up to rounding and independent of batch order, all regimes agree.A two-pass dense fit (mean first, then a second pass for variance) — it would diverge from the streaming formula and read the data twice.
Out-of-core is a transport choice, not a different modelfit_streaming resolves the plan against an unbounded context so Automatic picks the streaming branch; an explicit in-memory intent collects the batches and reuses the dense path. Both branches build the same SKStandardScalerModel.A separate streaming model type — two implementations of transform that can drift, and no single export boundary.
$\Sigma x^2$ is a first-class kernelVariance needs the sum of squares. Rather than square inside the algorithm (a fresh allocation per fit), sk_axis_sum_squares mirrors sk_axis_sum exactly: same axes, same parallelism contract, same grain. Kernels stay the reusable substrate.A one-off loop inside the scaler — duplicated across every variance-based algorithm (PCA, incremental PCA, robust scalers).
The backend is carried, never dispatched, hereThe scaler’s math is reductions only, so it never needs a concrete backend. But per the backend-selection spec it still exposes backend(SKBackendKind) and records the kind in every span, so the selection surface is uniform and a future GPU scaler is a dispatch change with no signature change.Omitting the parameter because “scalers don’t use BLAS” — the selection surface would then differ per estimator, and users would learn a different API for each.

3. The concepts, taught from zero

The math: mean, standard deviation, and the z-score

For one column with values $x_1, \dots, x_n$, the mean is the average,

$$\mu = \frac{1}{n}\sum_{i=1}^{n} x_i,$$

and the variance measures how far the values spread around that mean,

$$\sigma^2 = \frac{1}{n}\sum_{i=1}^{n} (x_i - \mu)^2.$$

Its square root, $\sigma$, is the standard deviation — same units as the data. The standardized value (the z-score) of each entry is then

$$z_i = \frac{x_i - \mu}{\sigma}.$$

After this, the column has mean 0 and standard deviation 1. Two flags control it: with_mean turns the subtraction off (mean 0), and with_std turns the division off (scale 1).

Computing $\sigma^2$ by first computing $\mu$ and then looping again to subtract it would read the data twice — impossible for a stream. Instead we use the algebraic identity

$$\sum_{i=1}^{n} (x_i - \mu)^2 = \sum_{i=1}^{n} x_i^2 ;-; 2\mu\sum_{i=1}^{n} x_i ;+; n\mu^2,$$

so one pass collecting $\sum x$ and $\sum x^2$ is enough. That identity is exactly what moments_from_sums implements.

The math, part 2: merging two batches without losing accuracy

When a second batch arrives, we already know the mean and spread of the first; we want the mean and spread of both together. The naive way — recombining raw sums — loses precision on large numbers. The Chan–Golub–LeVeque update merges two moment summaries directly. If the running state has count $n_a$, mean $\mu_a$ and sum of squared deviations $M_a$, and a batch has $n_b, \mu_b, M_b$, then the combined summary is

$$n = n_a + n_b,\qquad \mu = \mu_a + \delta,\frac{n_b}{n},\qquad M = M_a + M_b + \delta^2,\frac{n_a,n_b}{n}, \qquad \delta = \mu_b - \mu_a.$$

This is exact up to floating-point rounding and, crucially, gives the same answer no matter how the data is split into batches — which is why streaming_matches_dense_fit and partial_fit_after_fit_matches_dense can assert equality.

Rust concept 1: generics and SKFloat

A generic function or type is written once and works for many types, with the type left as a placeholder. Here the placeholder is the scalar: the scaler works for f32 (32-bit floats, half the memory) and f64 (64-bit, more precision). We write impl<F: SKFloat> ... and the compiler checks that F has the operations we use — +, *, sqrt, from. SKFloat is sciencekit’s sealed bound: a small trait the library controls, so “any float” means “f32 or f64”, not “any type a user invents”. A test, fit_accepts_either_float, instantiates the same code for both.

Rust concept 2: the builder pattern

A builder is an object whose methods each set one option and return the builder again, so calls chain:

#![allow(unused)]
fn main() {
let scaler = SKStandardScaler::build()
    .with_mean(false)
    .backend(SKBackendKind::MatrixMultiply)
    .build()?;
}

The estimator’s own constructor is private, so the only way to make one is through the builder. That gives every option an explicit default (with_mean and with_std true, backend Faer, execution_mode Automatic) and makes it impossible to forget one. The build() method returns a Result, because building may validate and fail.

Rust concept 3: ndarray, Array1/Array2 and azip!

ndarray is the array library. Array2<F> is a two-dimensional grid (rows × columns); Array1<F> is a vector. The idiom for “visit every element and combine two arrays” is the macro azip!:

#![allow(unused)]
fn main() {
ndarray::azip!((value in &mut row, mean in &self.mean, scale in &self.scale) {
    *value = (*value - *mean) / *scale;
});
}

Inside, value, mean and scale are references to the corresponding elements; the macro walks all positions once. The project forbids hand-written index loops — output[i] = ... — because the macro is shorter, safer and lets the compiler see the access pattern.

Concept: SKLazySource, the streaming batch source

Out-of-core data is modelled as an SKLazySource<F>: a cursor that hands out one owned SKDataBatch at a time via next_batch() -> Result<Option<...>>. None means “no more data”. The scaler never loops over the source itself; it hands it to the Phase 0 streaming executor (chapter 7), which prefetches the next batch on a separate thread while the current one is processed.


4. Each object, explained

SKStandardScaler — the estimator

What it is — the immutable configuration produced by the builder: the two flags, the backend kind, and the execution intent. Its only constructor is SKStandardScaler::build().

Why it exists — to separate what the user asked for from what the data taught the model. It implements SKUnsupervisedFit<F>: fit reads the dense data, learns the moments, and returns a model.

What we rejected — a single mutable type holding both; see Decision 1.

SKStandardScalerBuilder — the builder

What it is — the chainable configuration object: with_mean, with_std, backend, execution_mode, then build().

Why it exists — it is the mandated construction surface (every builder exposes execution_mode, and every estimator builder exposes backend), and it is where the defaults live. build() constructs the estimator directly, without touching the data or resolving any plan — dispatch and resolution are per-operation, not per-build.

SKStandardScalerModel<F> — the fitted model

What it is — the learned state: sample_count, the running moments_mean and sum_squared_deviations, the derived public mean and scale, the two flags, the carried backend, and the execution intent. It implements SKFeatureTransformer<F> (transform) and carries the incremental partial_fit.

Why it exists — it is the export boundary (the thing you serialize) and the only object that knows the statistics. Because it stores moments rather than the masked mean/scale, the incremental update is exact.

sk_axis_sum_squares — the kernel

What it is — a free function in sciencekit_math: given a 2-D array, an axis (0 = per column, 1 = per row) and a parallelism, it returns the per-column (or per-row) sum of squares. parallelism = 1 runs a simple sequential loop; > 1 splits the rows into chunks, each chunk accumulating its own partial vector, and combines the partials once at the end.

Why it exists — variance is a sum of squares; making it a kernel keeps every variance-based algorithm from reimplementing (and re-optimizing) it. The race-free per-chunk accumulation is the same pattern chapter 7 established for sk_axis_sum.

What we rejected — squaring inside the algorithm; see Decision 5.

StreamingMoments<F> and merge_moments — the streaming state

What it is — the combinable per-column Welford state (count, mean, sum_squared_deviations) plus the machine facts (available_memory_bytes, cpu_cores) used to size parallelism. merge_moments is the Chan update above.

Why it exists — it is the piece the streaming driver mutates, batch by batch, and the same function the model’s partial_fit uses, so streaming and incremental cannot diverge.

derive_statistics and finalize_column — the masking rule

What it is — a pure function turning moments into the public masked mean/scale: a disabled mean becomes 0, a disabled or non-positive scale becomes 1.

Why it exists — masking is decided in exactly one place, so dense, streaming and incremental outputs cannot disagree on an edge column (like a constant column, whose scale must be 1, not NaN).

The backend-selection capability

What it is — a published spec (and a rule in AGENTS.md) stating that every estimator builder exposes backend(SKBackendKind) defaulting to Faer, that every operation records the configured kind in its span (never a hardcoded value), and that fit transfers the kind into the model.

Why it exists — one uniform selection surface. Even the scaler, whose math never touches heavy linear algebra, carries it, so that when a GPU or BLAS backend arrives it appears as a new enum variant with no estimator signature changes.


5. A real walk-through, using the tests

The tests are the executable truth. They live in companion *_tests.rs files beside the implementation, and share deterministic datasets from test_datasets.rs (no randomness, no files on disk — the same numbers on every machine).

Dense fit and transform. fit_learns_per_column_mean_and_scale fits [[1, 2], [3, 4]] and asserts the model reports mean [2, 3] and scale [1, 1]; transform_produces_z_scores then asserts the transformed matrix is [[-1, -1], [1, 1]]. These two tests are the whole contract in miniature.

The flags. without_mean_keeps_values_uncentered builds with with_mean(false) and checks the mean is zero and the values pass through unchanged; without_std_centers_without_scaling builds with with_std(false) and checks the values are centered but not divided. The finalize_column helper is what makes both true.

The zero-variance edge. constant_column_yields_unit_scale_and_zero_output fits a matrix whose first column is constant (5, 5). Its variance is zero, so dividing by its standard deviation would produce NaN. The test asserts the scale is 1 and the transformed column is 0 — exactly the finalize_column rule.

Errors. fit_rejects_empty_input expects a ShapeMismatch before any element is touched; fit_rejects_sparse_input expects UnsupportedRepresentation at the dense-only boundary; transform_rejects_column_count_mismatch expects a ShapeMismatch when transforming data with a different number of columns.

Backend. backend_defaults_to_faer checks the estimator and its model both report Faer; backend_override_reaches_model builds with MatrixMultiply and checks the kind reaches the estimator, the fitted model, and still produces the correct z-scores.

Streaming equals dense. streaming_matches_dense_fit chunks the small matrix into uneven batches [2, 1, 3], streams them through fit_streaming, and asserts the streamed model’s mean and scale equal the dense fit’s (and that transforming produces identical output). The large-scale companion, large_streaming_matches_dense_fit, does the same on a 100 000 × 8 matrix split [40 000, 17 500, 42 500], comparing within a relative tolerance of 1e-9 because the Chan merge reorders floating-point operations.

Incremental equals dense. partial_fit_after_fit_matches_dense fits a prefix and partial_fits the rest; partial_fit_accumulates_single_rows does it one row at a time; partial_fit_chains_updates exercises the &mut Self return so calls chain. All three assert equality with the dense fit. partial_fit_empty_batch_is_noop checks an empty batch changes nothing, and partial_fit_column_mismatch_errors checks a wrong-width batch fails without touching the model.


6. Look inside

Three ways in, one model out. Dense data is reduced in memory; a stream is accumulated batch by batch through the executor; a partial_fit merges one more batch into a live model. Every path ends at the same SKStandardScalerModel, whose moments are the single source of truth.

flowchart TD
    accTitle: Three fit regimes converge on one standard-scaler model
    accDescr: Dense fit reduces the whole matrix with sk_axis_sum and sk_axis_sum_squares. Streaming fit consumes a lazy source through the executor, merging per-batch moments with the Chan update. Partial fit merges one more batch into a live model. All three paths produce the same model, whose running moments derive the public mean and scale.
    subgraph dense[Dense fit]
        X[ArrayView2 F] --> SUM[sk_axis_sum · sk_axis_sum_squares]
        SUM --> MOM[dense moments · count, mean, sum of squared deviations]
    end
    subgraph stream[Out-of-core fit_streaming]
        SRC[SKLazySource] --> DRV[streaming executor · I/O overlap CPU]
        DRV --> BATCH[per-batch moments]
        BATCH --> CHAN[merge_moments · Chan et al.]
    end
    subgraph inc[Incremental partial_fit]
        NB[new batch] --> BATCH2[per-batch moments]
        BATCH2 --> CHAN
    end
    MOM --> MODEL[SKStandardScalerModel]
    CHAN --> MODEL
    MODEL --> DERIVE[derive_statistics · finalize_column]
    DERIVE --> OUT[mean · scale]

    style dense fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style stream fill:#fef3c7,stroke:#d97706,color:#78350f
    style inc fill:#f0fdf4,stroke:#16a34a,color:#14532d

The insight is that the model is a summary, not the data. Because the summary is combinable (the Chan merge), “fit everything at once”, “fit in batches” and “fit a bit more later” are the same operation at different granularities — and the tests prove they land on the same numbers.


7. Recap

  • Standardization rescales each column to mean 0 and standard deviation 1, so no column dominates a distance-based algorithm.
  • SKStandardScaler is configuration; SKStandardScalerModel is learned state. fit turns one into the other; the model is the export boundary.
  • Running moments are the single source of truth. mean/scale are derived, never accumulated, so the three regimes cannot drift.
  • The Chan–Golub–LeVeque merge makes batches commute. Dense, streaming and partial_fit produce the same result within float tolerance.
  • Out-of-core is a transport choice. fit_streaming resolves an unbounded plan and reuses the same model; an in-memory intent just collects the batches.
  • The backend is carried, not dispatched, by the scaler — uniform selection surface, per the backend-selection spec.
  • sk_axis_sum_squares is a reusable kernel, the variance-style companion of sk_axis_sum, with the same race-free parallelism contract.

Next chapter: with the estimator template proven on the simplest algorithm, the next Wave 1 change reuses it for the min-max and robust scalers — where the robust scaler adds an online quantile sketch (tdigest) so that even its median can be learned from a stream.

The second scaler: SKMinMaxScaler

The previous chapter built the estimator template on the simplest possible algorithm — standardization — and proved that three fit regimes (dense, incremental, out-of-core) can agree exactly. This chapter spends that template on a second, slightly different scaler: SKMinMaxScaler, which squeezes every column into a bounded range instead of a zero-mean, unit-variance one. The shift is small in code and large in consequences: the statistics are extrema rather than moments, the learned summary is a minimum and a range rather than a mean and a deviation, and the natural kernel is a brand-new extremum reduction, sk_axis_min_max. Because min and max are associative and exact, this scaler gets something the standard scaler only gets “up to floating-point rounding”: all three regimes agree bit for bit.


1. The problem we were solving

Standardization is not always the right rescaling. Some algorithms require inputs inside a fixed box. A distance metric that assumes features live in $[0, 1]$ is misled by an unbounded column; an image model that expects pixel intensities in a fixed range cannot ingest raw values; a neural-style layer with a bounded activation assumes its inputs are bounded. The common need is: map the smallest observed value in each column to one end of a target range, and the largest to the other end, linearly in between. That is the min–max scaler.

The target range is configurable — the default is [0, 1], but [-1, 1] and others are common — and it can optionally clip: values seen at transform time that fall outside what was seen at fit time can be clamped to the target range, or left to fall outside it. Clipping is a presentation choice, not a property of the data, so the design keeps it out of the learned state entirely.

The engineering promise is the same as the standard scaler’s, and stronger: the dense, incremental and out-of-core fits must produce the same model. For the standard scaler that sameness was “up to floating-point rounding”, because the streaming merge reorders float operations. For the min–max scaler it is exact, because the merge is just min and max, which do not care about order at all. This chapter is partly about why that exactness falls out for free.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Estimator and model are separate types, againSKMinMaxScaler<F> is configuration (target range, clip, backend); SKMinMaxScalerModel<F> is learned state (per-column minimum, range, and the affine scale). The template from chapter 8 transfers unchanged.Reusing SKStandardScaler’s model with a flag — the learned state is genuinely different (extrema, not moments), so a shared type would be a lie.
SKMinMaxScaler is generic over the scalar, unlike SKStandardScalerThe target range is stored as F (feature_range((F, F))), so the estimator must carry the scalar type. The scalar still arrives by inference from the data at fit time in the common case.Storing the range as f64 and converting — it would force a conversion path and break the “same scalar end to end” rule the rest of the library follows.
The kernel is a first-class extremum reductionsk_axis_min_max returns each column’s minimum and maximum in one pass, with the same parallelism contract and grain as sk_axis_sum. Every later extremum-based algorithm (outlier detection, trees) reuses it.Folding min/max into the scaler — duplicated and re-optimized in every extremum algorithm.
Running extrema are the single source of truthThe model stores the per-column minimum, maximum and data_range; the affine scale is derived from them by every constructor and every update, so an incremental update reconverges to the same parameters a batch fit would produce.Storing the derived scale directly — the incremental merge would have to undo it to recover the raw extrema.
Min/max makes all regimes exact, not approximatemin and max are associative and commutative, so merging per-batch extrema in any order gives the same answer. Dense, streaming and partial_fit produce identical arrays; the tests use assert_eq, not a tolerance.Sketching the extrema (as the robust scaler will do for quantiles) — unnecessary, since running min/max is $O(\text{columns})$ state and exact.
clip is a transform-time concernThe transform clamps to the target range only when clip is true, and flipping it never requires a refit.Baking clipping into the learned scale — coupling a presentation choice to the fitted state.
A zero-range column gets unit scaleA constant column has range 0; dividing by it would produce NaN. We treat it as having unit scale and a target-range minimum, so its transformed values are finite and equal the target minimum.Letting the division happen and cleaning up NaN later — late and easy to miss.

3. The concepts, taught from zero

The math: mapping a column onto a target range

For one column whose smallest value is $x_{\min}$ and largest is $x_{\max}$, and a configured target range $(r_{\min}, r_{\max})$, the transformed value is

$$x_{\text{scaled}} = (x - x_{\min}),\frac{r_{\max} - r_{\min}}{x_{\max} - x_{\min}} + r_{\min}.$$

Read it in three steps: shift by $-x_{\min}$ so the column starts at 0; multiply by $\frac{r_{\max}-r_{\min}}{x_{\max}-x_{\min}}$ so its width matches the target width; shift by $+r_{\min}$ so it starts at the target’s lower end. With the default range $(0, 1)$, the minimum maps to $0$, the maximum to $1$, and a midpoint to $0.5$.

We can write the same map as a single affine form,

$$x_{\text{scaled}} = (x - x_{\min}),s + r_{\min}, \qquad s = \frac{r_{\max}-r_{\min}}{x_{\max}-x_{\min}},$$

where $s$ is the scale — the one derived parameter the model stores besides the raw extrema. This is the same shape the standard scaler uses ($z=(x-\mu)/\sigma$), which is why the estimator template transfers so cleanly.

The constant column: dividing by zero, handled once

If a column never changes, $x_{\max}=x_{\min}$ and $s$ is a division by zero. The rule is simple and lives in one place (derive_scale): a non-positive range gets a unit scale, so $s=1$ and the transformed value is $(x-x_{\min})\cdot 1 + r_{\min} = r_{\min}$ for every value in the column. Finite, and exactly the target minimum — never NaN.

Rust concept: the min/max fold, and why it is order-independent

The kernel accumulates a running minimum and maximum over each row of a chunk. Both operations satisfy $a \oplus b = b \oplus a$ (commutative) and $(a \oplus b) \oplus c = a \oplus (b \oplus c)$ (associative), so splitting the rows into chunks, reducing each chunk, and combining the per-chunk results gives the same pair as reducing everything at once. There is also no “accumulator” to share: each chunk owns its partial pair, and the combine step walks the partials once. That race-free shape is the same one chapter 7 established for sk_axis_sum.


4. Each object, explained

SKMinMaxScaler<F> — the estimator

What it is — the immutable configuration produced by the builder: the target feature_minimum/feature_maximum, the clip flag, the backend kind and the execution intent. Its only constructor is SKMinMaxScaler::build().

Why it exists — same reason as the standard scaler: to separate what the user asked for from what the data taught the model. It implements SKUnsupervisedFit<F>: fit reads the dense data, reduces it to extrema, and returns a model. It also exposes feature_range(), clip() and backend() so the configuration is inspectable without reaching into fields.

SKMinMaxScalerBuilder<F> — the builder

What it is — the chainable configuration object: feature_range((F, F)), clip(bool), backend(SKBackendKind), execution_mode(...), then build(). Defaults are (0, 1), no clipping, Faer and Automatic.

Why it exists — the mandated construction surface, and the one place the defaults live. build() does no data work and resolves no plan; dispatch and resolution happen per operation.

SKMinMaxScalerModel<F> — the fitted model

What it is — the learned state: sample_count, the per-column minimum, maximum and data_range (= maximum - minimum), the derived affine scale, the configured target range, the clip flag, the carried backend and the execution intent. It implements SKFeatureTransformer<F> (transform) and carries the incremental partial_fit.

Why it exists — it is the export boundary and the only object that knows the extrema. Because it stores the raw minimum/maximum/data_range rather than the derived scale, the incremental update is exact and never has to “undo” a transformation.

sk_axis_min_max — the kernel

What it is — a free function in sciencekit_math: given a 2-D array, an axis (0 = per column, 1 = per row) and a parallelism, it returns the per-axis minima and maxima as two 1-D arrays. parallelism = 1 runs a simple sequential fold; > 1 splits the rows into chunks, each chunk producing its own partial pair, combined once at the end.

Why it exists — it is the extremum companion of sk_axis_sum, with the same axes, the same race-free parallelism contract and the same reduction grain (SK_AXIS_SUM_GRAIN), so the scaler can reuse the plan it already resolves.

What we rejected — squaring the algorithm’s inside; see Decision 3.

StreamingExtrema<F> and merge_extrema — the streaming state

What it is — the combinable per-column extrema state (count, minimum, maximum, data_range) plus the machine facts used to size parallelism. merge_extrema takes the element-wise min of the minima and max of the maxima and rewrites the range as maximum − minimum, keeping the exact extrema rather than reconstructing the maximum from the range.

Why it exists — it is the piece the streaming driver mutates, batch by batch, and the same function the model’s partial_fit uses, so streaming and incremental cannot diverge — and, because the extrema are stored directly rather than re-derived, they agree with the dense fit bit for bit.


5. A real walk-through, using the tests

The tests are the executable truth, in companion *_tests.rs files sharing deterministic datasets from test_datasets.rs. Unlike the standard scaler’s cross-regime tests, the min–max tests can assert equality.

Dense fit and transform. fit_maps_column_to_unit_range fits the single column [0, 5, 10] with the default range and asserts the minimum is 0, the range is 10, and the output is [[0], [0.5], [1]]. That one test is the whole contract in miniature.

The learned details. fit_learns_per_column_minimum_and_range fits two columns and checks the minimum, the range, and the derived scale ([0.25, 0.1]) — showing that scale is a function of the extrema, not stored independently.

The target range and clipping. feature_range_override_maps_into_target_range builds with (-1, 1) and checks the output is [[-1], [0], [1]]. clip_true_constrains_output_to_feature_range transforms a value above the fitted maximum and asserts it lands exactly on the target maximum; clip_false_allows_out_of_range_output shows the same value overshooting to 1.5 when clipping is off.

The zero-range edge. constant_column_maps_to_target_minimum fits a matrix whose first column is constant (5, 5, 5) and asserts its range is 0, its scale is 1, and its transformed column is all 0 — exactly the derive_scale rule.

Errors. fit_rejects_empty_input expects a ShapeMismatch before any element is touched; fit_rejects_sparse_input expects UnsupportedRepresentation at the dense-only boundary; transform_rejects_column_count_mismatch expects a ShapeMismatch on a width mismatch.

Backend. backend_defaults_to_faer checks both estimator and model report Faer; backend_override_reaches_model builds with MatrixMultiply and checks the kind reaches the estimator, the fitted model, and still produces correct output.

Incremental equals dense — exactly. partial_fit_after_fit_matches_dense fits a prefix and partial_fits the rest; partial_fit_accumulates_single_rows does it one row at a time; partial_fit_chains_updates exercises the &mut Self return so calls chain. All three use assert_close, and large_partial_fit_matches_dense_fit uses assert_eq on the 100 000 × 8 matrix — no tolerance, because the merge is exact. partial_fit_empty_batch_is_noop checks an empty batch changes nothing (not even the sample count), and partial_fit_column_mismatch_errors checks a wrong-width batch fails without touching the model.

Streaming equals dense — exactly. streaming_matches_dense_fit chunks the small matrix into [2, 1, 3], streams it, and asserts the streamed model’s extrema equal the dense fit’s and that transforming produces identical output; large_streaming_matches_dense_fit does the same at scale. streaming_explicit_in_process_collects_batches pins the in-memory branch, while an Automatic intent takes the true streaming driver. streaming_empty_source_errors and streaming_column_mismatch_errors cover the failure paths.


6. Look inside

Three ways in, one model out — and this time every path lands on the same numbers, because the merge is min/max.

flowchart TD
    accTitle: Three fit regimes converge exactly on one min/max model
    accDescr: Dense fit reduces the whole matrix with sk_axis_min_max. Streaming fit consumes a lazy source through the executor, merging per-batch extrema with element-wise min and max. Partial fit merges one more batch into a live model. All three paths produce the same model, whose running extrema derive the affine scale and drive the transform, optionally clipping to the target range.
    subgraph dense[Dense fit]
        X[ArrayView2 F] --> K[sk_axis_min_max · per-column min and max]
        K --> EXT[dense extrema · minimum, data_range]
    end
    subgraph stream[Out-of-core fit_streaming]
        SRC[SKLazySource] --> DRV[streaming executor · I/O overlap CPU]
        DRV --> BATCH[per-batch min and max]
        BATCH --> MERGE[merge_extrema · element-wise min and max]
    end
    subgraph inc[Incremental partial_fit]
        NB[new batch] --> BATCH2[per-batch min and max]
        BATCH2 --> MERGE
    end
    EXT --> MODEL[SKMinMaxScalerModel]
    MERGE --> MODEL
    MODEL --> DERIVE[derive_range · derive_scale]
    DERIVE --> OUT["transform: (x - min) * scale + r_min"]
    OUT --> CLIP{clip?}
    CLIP -->|yes| CLAMP[clamp to feature_range]
    CLIP -->|no| PASS[leave as is]

    style dense fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style stream fill:#fef3c7,stroke:#d97706,color:#78350f
    style inc fill:#f0fdf4,stroke:#16a34a,color:#14532d

The insight is the same as chapter 8 — the model is a summary, not the data — but the summary here is extrema, and extrema commute. That is why the three regimes do not merely “agree within tolerance”; they agree exactly.


7. Recap

  • Min–max scaling maps each column linearly onto a configurable target range, so bounded inputs are guaranteed for algorithms that need them.
  • SKMinMaxScaler is configuration; SKMinMaxScalerModel is learned state. fit turns one into the other; the model is the export boundary.
  • Running extrema are the single source of truth. scale is derived from minimum, maximum and data_range, never accumulated, so the regimes cannot drift.
  • Min/max make the regimes exact. Dense, streaming and partial_fit produce identical arrays; the tests use assert_eq, not a tolerance.
  • A zero-range column gets unit scale, so constant columns stay finite instead of NaN.
  • clip is a transform-time concern, so flipping it never requires a refit.
  • sk_axis_min_max is a reusable kernel, the extremum companion of the sum reductions, with the same race-free parallelism contract.

Next chapter: the robust scaler takes the same template in a harder direction — centering and scaling on quantiles (median and interquartile range) so outliers stop dominating the scale, and learning those quantiles from a stream through an online sketch, something scikit-learn’s RobustScaler cannot do at all.

The third scaler: SKRobustScaler

The min/max scaler proved that the estimator template scales to a second algorithm whose statistics are extrema. This chapter pushes the same template into its hardest case yet: SKRobustScaler, which centers and scales every column on quantile statistics — the median and the interquartile range — so a handful of extreme values can no longer drag the scale. Quantiles are the first statistic in this book that cannot be computed in a single associative pass, and that is the point: scikit-learn’s RobustScaler must see a whole column in memory, while sciencekit learns the quantiles from a stream through an online sketch. It is the out-of-core differentiator applied to a transformer scikit-learn cannot stream at all.


1. The problem we were solving

Standardization and min–max scaling both compute statistics that every value influences. A single entry of a million — a mistyped income, a sensor spike — moves the mean and widens the range, so the whole column is rescaled around a number the outlier chose. The result is a scaler that is accurate but not robust: correct statistics over a contaminated sample.

The robust answer is to summarize a column by order statistics instead of sums. The median (the 50th percentile) is the value in the middle of the sorted column, and the interquartile range (IQR) is the distance from the 25th to the 75th percentile — the width of the middle half of the data. Both are famously insensitive to outliers: dragging the largest value to infinity does not move the median or the IQR at all. Centering on the median and scaling by the IQR gives an outlier-resistant rescaling that matches scikit-learn.

The engineering problem is subtler than the arithmetic. Median and IQR are selection statistics: to know the middle value you must order the column, and ordering needs the whole column at once. That is exactly what a stream does not give you. The chapter’s central idea is how to keep the dense result exact (for scikit-learn parity) while learning an approximate version from an unbounded stream — and to be honest in the tests about which is which.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Dense fit is exact; the stream sketchesDense fit computes the median and IQR exactly from the sorted column, matching scikit-learn. partial_fit and fit_streaming maintain a per-column tdigest sketch and read the quantiles from it. Exact where exactness is cheap and expected; approximate only where the stream forces it.Always using the sketch — dense results would be approximate and surprising, breaking parity. Always using exact quantiles — impossible in one streaming pass without buffering the whole column, the very capability we are adding.
One sketch per column, compression fixed internallyThe model holds a Vec<tdigest::TDigest>, one per column, each fed per batch. Memory is columns × compression, independent of the row count — the out-of-core property. The compression parameter stays an internal constant, not a builder option, so the public surface stays focused.Exposing compression as a knob — more surface for a setting almost nobody needs; it can be promoted later.
unit_variance uses a probit approximationunit_variance = true divides the scale by the standard-normal interquartile span of the same quantile_range. That span is Φ⁻¹(high) − Φ⁻¹(low), computed by Acklam’s rational approximation of the inverse normal CDF — accurate to ~1e-9 for one constant per range.Pulling in statrs/libm for a single closed-form constant — dependency weight for a ten-line approximation.
The model stores only center and scaleBy the time the model exists, the masking flags and the unit-variance divisor have already been applied. The transform is a plain (x − center) / scale, and a non-positive scale becomes 1 so a zero-spread column stays finite.Branching on the flags inside transform — more runtime state and a second place the masking rule could drift.
sk_axis_min_max is not reused hereThe min/max scaler’s kernel is an associative reduction; quantiles are not, so SKRobustScaler needs its own exact-quantile helper and its own sketch. Sharing a kernel would have hidden the fact that the two scalers’ statistics are fundamentally different.Fitting quantiles into the reduction family — they would have to buffer, defeating the streaming shape.
The backend is still carried, not dispatchedAs in the other two scalers, the math is selection and reduction only, so no concrete SKMathBackend is needed — but the estimator still exposes backend(SKBackendKind) and records the kind in every span, per the backend-selection spec.Omitting it — a non-uniform selection surface.

3. The concepts, taught from zero

The math: median and interquartile range

Sort a column into $x_{(1)} \le x_{(2)} \le \dots \le x_{(n)}$. The quantile at probability $p \in [0,1]$ is the value at position $p,(n-1)$ in that sorted order; when the position falls between two integers we interpolate linearly:

$$\text{quantile}(p) = x_{(\lfloor i \rfloor)} + \bigl(x_{(\lceil i \rceil)} - x_{(\lfloor i \rfloor)}\bigr),(i - \lfloor i \rfloor), \qquad i = p,(n-1).$$

This is the NumPy / scikit-learn convention, and exact_quantile implements exactly it. With it, the median is $\text{quantile}(0.5)$ and the interquartile range is $\text{quantile}(0.75) - \text{quantile}(0.25)$. For the column [1, 2, 3, 4, 5] the median is $3$ and the IQR is $4 - 2 = 2$ — the number the test fit_learns_median_and_interquartile_range pins.

The transform is then the familiar affine shape:

$$z_i = \frac{x_i - \text{center}}{\text{scale}},$$

with $\text{center} = \text{median}$ and $\text{scale} = \text{IQR}$. Two flags mask each half — with_centering and with_scaling — and a non-positive scale is replaced by $1$, so a column with zero spread transforms to finite zeros instead of dividing by zero.

The concept: an online quantile sketch

Exact quantiles need the whole sorted column. A sketch is a fixed-size summary that answers quantile queries approximately while seeing each value only once. The one we use is the t-digest: it keeps a small set of “centroids” that stand in for clusters of nearby values, merging them as data arrives so that the count of centroids never exceeds the configured compression. Feeding a batch is just pushing its values; querying a quantile walks the centroids. Memory is bounded by the compression, not the data, which is precisely the out-of-core property.

The trade-off is explicit and testable. Because the sketch is approximate, the online path is not bit-identical to the dense path; the cross-regime tests assert agreement within a documented relative tolerance (5% here), the same contract the standard scaler’s assert_close_with_tolerance uses — just a looser number, because the sketch is a genuinely different kind of summary.

The concept: the probit and unit variance

If the data are normal, the IQR is a fixed multiple of the standard deviation — specifically the distance between the 75th and 25th percentiles of a standard normal, about 1.34898. When unit_variance is true we divide the IQR by that constant so a normally distributed column ends up with unit variance, matching scikit-learn’s RobustScaler(unit_variance=True). The constant comes from the probit — the inverse of the normal CDF — computed by Acklam’s rational approximation in probit, and summed into the span by standard_normal_interquantile_span. A dedicated test pins the 25–75 span at its well-known value.


4. Each object, explained

SKRobustScaler<F> — the estimator

What it is — the immutable configuration: with_centering, with_scaling, quantile_range, unit_variance, the backend kind and the execution intent. Its only constructor is SKRobustScaler::build().

Why it exists — the template, unchanged: configuration separate from learned state. It implements SKUnsupervisedFit<F>, and its fit learns the exact center and scale and seeds the sketches a later partial_fit will extend.

SKRobustScalerBuilder<F> — the builder

What it is — the chainable surface: with_centering, with_scaling, quantile_range((F, F)), unit_variance, backend, execution_mode, then build(). Defaults are center and scale on (25, 75), no unit variance, Faer and Automatic.

SKRobustScalerModel<F> — the fitted model

What it is — the learned state: sample_count, the per-column center and scale (already masked), the Vec<tdigest::TDigest> sketches, the configuration, the backend and the execution intent. It implements SKFeatureTransformer<F> and carries the incremental partial_fit.

Why it exists — the export boundary, and the only object that both transforms and keeps learning. Storing the sketches is what makes partial_fit able to keep approximating the statistics over all the data a model has seen.

column_quantile_statistics, exact_quantile and standard_normal_interquantile_span — the dense quantile helpers

What it is — exact_quantile is the interpolated order-statistic quantile above; column_quantile_statistics sorts each column and reads the median and IQR; standard_normal_interquantile_span wraps probit.

Why they exist — they isolate the exact quantile convention (parity with scikit-learn) and the probit approximation in one testable place, away from the estimator.

new_sketches, extend_sketches and sketch_statistics — the online sketch helpers

What it is — new_sketches builds one tdigest per column at a fixed compression; extend_sketches feeds a batch into every column sketch and compresses them; sketch_statistics reads the median and IQR back out.

Why they exist — they are the single implementation of “learn quantiles from a stream”, used by both partial_fit and the streaming driver, so the two online paths cannot diverge.

StreamingSketches — the streaming state

What it is — the row count, the column count, the per-column sketches and a parked error, mutated batch by batch by the streaming driver.

Why it exists — the streaming counterpart of the model’s sketches; the driver feeds it, and the finalize step reads the quantiles and applies the same masking the dense path applies.


5. A real walk-through, using the tests

Dense fit and transform. fit_learns_median_and_interquartile_range fits [1, 2, 3, 4, 5] and asserts center 3 and scale 2; transform_centers_and_scales checks the output is [[-1], [-0.5], [0], [0.5], [1]] — the median at 0 and the IQR at 1.

The options. quantile_range_override_changes_scale widens the range to (0, 100) and checks the scale becomes the full spread 4; without_centering_keeps_values_uncentered and without_scaling_centers_without_scaling check the two masks; unit_variance_divides_scale_by_standard_normal_span checks the IQR 2 becomes 2 / 1.34898….

The zero-spread edge. zero_spread_column_gets_unit_scale_and_finite_output fits a constant column and asserts its scale is 1 and its output is finite — the non-positive-scale rule.

The probit. standard_normal_span_matches_known_value pins standard_normal_interquantile_span(25.0, 75.0) to 1.3489795003921634 within 1e-9, and exact_quantile_matches_hand_computed_values pins the interpolation against hand-computed quantiles.

Errors and backend. fit_rejects_empty_input, fit_rejects_sparse_input and transform_rejects_column_count_mismatch cover the error taxonomy; backend_defaults_to_faer and backend_override_reaches_model cover the carried backend.

Incremental approximates dense. partial_fit_after_fit_approximates_dense fits a prefix of the 100 000 × 8 matrix, partial_fits the rest, and asserts the center and scale track the exact dense fit within SKETCH_RELATIVE_TOLERANCE; partial_fit_accumulates_sample_count checks the count, partial_fit_empty_batch_is_noop the no-op, and partial_fit_column_mismatch_errors the mismatch.

Streaming approximates dense. streaming_approximates_dense_fit streams uneven batches and asserts the same tolerance; streaming_explicit_in_process_collects_batches pins the in-memory branch (which is exactly the dense fit, because it collects and reuses it); streaming_respects_builder_flags checks the flags survive an online fit; streaming_empty_source_errors and streaming_column_mismatch_errors cover the failures.


6. Look inside

Dense fitting is exact and seeds the sketches; both online paths feed the same per-column sketches and finalize through one masking step. The tests pin how close the approximate path is allowed to be.

flowchart TD
    accTitle: Exact dense and approximate streaming paths of the robust scaler
    accDescr: Dense fit sorts each column and reads exact quantiles, then seeds one tdigest sketch per column. Partial fit and the streaming driver both extend the per-column sketches, read the median and interquartile range back, and apply the with_centering, with_scaling and unit_variance rules through one shared finalizer. The sketches keep memory bounded by columns times compression.
    subgraph dense[Exact dense fit]
        X[ArrayView2 F] --> SORT[sort each column]
        SORT --> Q["exact_quantile · median and IQR"]
        Q --> FINAL[finalize · masks and unit_variance]
        SORT --> SEED["new_sketches · extend_sketches"]
    end
    subgraph online[Online: partial_fit and streaming]
        BATCH[batches] --> EXT["extend_sketches · tdigest per column"]
        EXT --> STAT["sketch_statistics · approximate median and IQR"]
        STAT --> FINAL
    end
    FINAL --> MODEL[SKRobustScalerModel]
    SEED --> MODEL
    MODEL --> OUT["transform: (x - center) / scale"]

    style dense fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    style online fill:#fef3c7,stroke:#d97706,color:#78350f

The insight is that robustness and streaming are different axes. Robustness comes from which statistic we summarize (order statistics, not sums). Streaming comes from how we summarize it (a bounded sketch instead of the whole column). The design keeps the two honest: exact when the data is in memory, approximate — within a number the tests enforce — when it is not.


7. Recap

  • Robust scaling centers on the median and scales by the interquartile range, so outliers cannot dominate the scale the way they dominate a mean and standard deviation.
  • SKRobustScaler is configuration; SKRobustScalerModel is learned state, and the model is the export boundary.
  • Dense fit is exact — interpolated order statistics, matching scikit-learn.
  • The online path sketches — one tdigest per column, memory bounded by columns × compression, so the scaler streams where scikit-learn cannot.
  • The two paths differ by a documented tolerance (5%), asserted explicitly rather than hidden; the in-memory branch is exactly dense because it reuses the dense path.
  • unit_variance divides the IQR by the standard-normal interquantile span, computed by a self-contained Acklam probit pinned at 1.34898 for (25, 75).
  • A zero-spread column gets unit scale, and the backend kind is carried into the model and every span.

Encoders: the categorical boundary, SKOneHotEncoder and SKPolynomialFeatures

The three scalers taught the estimator template to standardize, bound and de-outlier numeric columns — but every one of them assumed the data already was numbers. This chapter crosses a line the book has not crossed yet: it adds a second kind of feature data to the library. Categorical features — names, colours, small integer codes — are not numbers, and no amount of scaling makes them numbers. Turning them into numbers is the job of the one-hot encoder; the companion task of growing numbers into their products is the job of the polynomial expander. Together they are the two feature-engineering transformers Wave 1 promised last.

flowchart LR
  accTitle: Two encoders over three input shapes
  accDescr: Nominal text and integer codes enter the one-hot encoder, which produces a fitted model that outputs either a dense array or a CSR sparse matrix. A numeric matrix enters the polynomial-features encoder, whose fitted model also outputs dense or CSR.
  subgraph Input["Feature data"]
    N["nominal text<br/>[[&quot;a&quot;,&quot;x&quot;],[&quot;b&quot;,&quot;y&quot;]]"]
    I["integer codes<br/>[[0,-1],[2,1]]"]
    D["numeric matrix<br/>[[2.0, 3.0]]"]
  end
  N --> CV["SKCategoricalView"]
  I --> CV
  CV --> OHE["SKOneHotEncoder.fit"]
  OHE --> M1["SKOneHotEncoderModel"]
  M1 --> OD["dense Array2"]
  M1 --> OS["sparse CsMat (CSR)"]
  D --> DV["SKDataView (dense)"]
  DV --> PF["SKPolynomialFeatures.fit"]
  PF --> M2["SKPolynomialFeaturesModel"]
  M2 --> PD["dense Array2"]
  M2 --> PS["sparse CsMat (CSR)"]

1. The problem we were solving

Every estimator so far accepted one thing: an SKDataView, the numeric feature boundary — a dense matrix or a sparse CSR matrix of numbers. That boundary is generic over a scalar F: SKFloat, and it is deliberately numeric: a distance, a mean, a dot product only make sense on numbers. But real tabular data is full of columns that are labels. A city column holding "Lisbon", "Porto", "Braga" is not a number, and if you force it into a float you have either invented a fake ordering (Lisbon < Porto?) or thrown the information away.

The standard solution is the one-hot encoding: give each distinct category its own output column and put a 1 in the column the row belongs to, 0 elsewhere. Three cities become three indicator columns; a row in "Porto" becomes [0, 1, 0]. Now every numeric estimator works.

The second transformer answers a different need. A linear model can only see straight combinations of its inputs: it can learn $w_0 + w_1 x_0 + w_2 x_1$, but never the curve $x_0 \times x_1$ or the bend $x_0^2$. Polynomial features manufacture those terms — the squares, cubes and pairwise products — and hand them to the linear model as if they were independent inputs. A linear model on the expanded matrix fits a curved surface, without leaving the linear family.

The engineering problem was not the arithmetic — an indicator and a product are trivial — but the boundary. Categorical data had no representation in the library at all. Either the encoder quietly forks its own private input type, or the boundary grows a proper categorical counterpart that every future encoder, imputer and codec can share. We chose the second, and that choice is half of this chapter.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
A categorical boundary, sibling to SKDataViewsciencekit_common gains SKNominalMatrixView (row-major borrowed labels) and the non-exhaustive SKCategoricalView enum (Nominal text columns / Integer ArrayView2<i64> codes), entered through the same fallible TryInto seam. Categorical data is a first-class citizen of the same boundary every estimator uses.Widening SKDataView with a categorical variant — it is generic over F: SKFloat; a text or i64 column is not an F, and forcing it through would make the type parameter a lie and break every as_dense consumer. Accepting &[&[&str]] directly on the encoder — a private seam instead of the shared one.
A documented missing sentinel -1Integer-coded columns have no NaN; -1 (scikit-learn’s convention) marks a missing entry. It is never registered as a category and always encodes to an all-zero block, so encoders and imputers agree.Using i64::MIN — a valid, if unlikely, code that would collide. Inventing a second missing mechanism — two ways to say “absent”.
Per-column tables: SKLabelTable for text, a code table for integersNominal columns reuse the existing SKLabelTable interning (first-occurrence order, reversible, exportable). Integer columns get a tiny SKIntegerCategoryTable (index → code, code → index) so the code stays exact.Stringifying integer codes into one SKLabelTable — label_of would return "3" and force a parse to recover the code.
Dense and sparse output, chosen by the builderBoth expansions are overwhelmingly sparse, so both emit a dense Array2 or a sprs CSR matrix; sparse_output picks the default and transform_dense / transform_sparse are always available. The CSR build is two-pass and parallel across rows with CsMat::new_from_unsorted.Dense only — losing the zero-copy sparse path the library bets on. A generic output type — the transformer trait is bound to numeric SKDataView input, which categorical data cannot satisfy, so a concrete non-exhaustive enum is both simpler and future-proof.
No runtime phf perfect hashThe wave plan phrased the table as “interned string table, perfect-hash”. A runtime perfect-hash builder does not exist in phf (it is compile-time codegen); an ordered HashMap-backed interning table already gives average O(1) with no extra dependency and no unsafe. The plan’s intent — a deterministic, compact, ordered table — is met.Adding phf for a property it does not provide at runtime.
fit learns scalar-independent state; transforms are generic over FThe learned tables and the exponent list do not depend on the output scalar, so the fitted models are not generic over F — only transform_dense/transform_sparse are.A PhantomData<F> on the model — a type parameter that tracks nothing.
Polynomial order: bias, then degree, then lexicographicTerms are combinations of feature indices, laid out bias-first, then by increasing total degree, then lexicographically: for two features at degree two that is $1, x_0, x_1, x_0^2, x_0x_1, x_1^2$. This is exactly scikit-learn’s column order.Reverse-lexicographic exponent tuples — a different, surprising order that would break parity.
The backend is still carried, not dispatchedAs in the scalers, the math is interning and products, not heavy dense algebra — but both estimators still expose backend(SKBackendKind) and record the kind in every span, per backend-selection.Omitting it — a non-uniform selection surface.

3. The concepts, taught from zero

The categorical view

SKNominalMatrixView is a borrowed row-major matrix of labels: the outer slice indexes rows, each inner slice holds that row’s column labels, and every label is a &str borrowed from the caller — no text is copied. The non-exhaustive SKCategoricalView is the enum that either wraps it (Nominal) or wraps an integer-coded matrix (Integer(ArrayView2<i64>)). Like the numeric boundary, it is entered through TryInto<SKCategoricalView, Error = SKError>, so a native slice or view converts infallibly and a third party can plug in a fallible conversion whose error flows into the operation’s Result.

Interning: the label table

To encode a column you need a fixed mapping from label to index. During fit the encoder walks the column in order and assigns index 0 to the first label it sees, 1 to the next new one, and so on — first-occurrence order — building an SKLabelTable. The order is deterministic: the same data always yields the same table, which is what makes the export boundary and the tests stable. The test first_occurrence_order_and_determinism pins that ["b","a","b","c"] maps b→0, a→1, c→2 and that two fits agree.

The one-hot transform

Learn the tables of each column, then remember how many categories each has. The output width is their sum, and each column owns a contiguous block of output columns starting at an offset. Encoding a row is, per input column, a table lookup to a local index, then a 1 at offset + local:

$$\text{output}[r,\ \text{offset}_c + \text{index}c(x{r,c})] = 1.$$

For [["a"],["b"],["a"]] the table is a→0, b→1 and the output is [[1,0],[0,1],[1,0]] — the test text_column_encodes_to_indicators.

Unknown categories and the missing sentinel

A category seen at transform time but not at fit time is unknown. The handle_unknown policy decides: Reject (the default) fails with a structured error before writing anything; Ignore leaves that column’s block all zeros. An integer entry equal to the sentinel -1 is missing, not unknown: it is skipped during fit (never becomes a category) and encodes to an all-zero block regardless of policy. integer_codes_skip_missing_sentinel walks a column [0, -1, 2] and shows the sentinel both staying out of the table and encoding to zeros.

Sparse output without copying zeros

One-hot matrices are mostly zeros — with a hundred cities, every row stores exactly one 1 per column. Storing the zeros would waste most of the memory. sprs’ CSR format stores only the nonzeros, row by row: an indptr array of row boundaries, an indices array of column positions, and a data array of values. We build it in two passes: first, in parallel across rows, compute each row’s output indices (which is also where an unknown category surfaces as an error); then lay them into indptr/indices/data and hand the arrays to CsMat::new_from_unsorted, which validates and — if needed — sorts them. The test sparse_matches_dense densifies the sparse result and asserts it equals the dense one exactly.

Polynomial expansion

A term is a sorted list of feature indices; its value is the product of the input values at those indices, and the empty list is the constant 1. For two features at degree two the non-interaction terms are [], [0], [1], [0,0], [0,1], [1,1], whose values on the row [2, 3] are 1, 2, 3, 4, 6, 9 — the test hand_checkable_expansion. interaction_only forbids repeated indices, dropping the pure powers [0,0] and [1,1]; include_bias drops the empty term. The terms are cheap metadata (index lists); the values are computed row by row during transform, never materialized as a blow-up of owned arrays.


4. The public objects

  • SKCategoricalView<'a> (sciencekit_common) — the non-exhaustive categorical feature view: Nominal(SKNominalMatrixView<'a>) or Integer(ArrayView2<'a, i64>).
  • SKNominalMatrixView<'a> — the borrowed label matrix: shape, value(row, column), row, is_empty.
  • SK_CATEGORICAL_MISSING_CODE: i64 = -1 — the documented missing sentinel.
  • SKOneHotEncoder — builder-only configured encoder. Builder: sparse_output(bool) (default true), handle_unknown(SKUnknownPolicy) (default Reject), backend, execution_mode.
  • SKOneHotEncoderModel — the fitted tables plus output offsets; transform_dense, transform_sparse, transform (returns SKEncodedOutput), and accessors (column_categories, number_of_output_features, backend, …).
  • SKExpandedOutput<F> / SKEncodedOutput<F> — the non-exhaustive Dense/Sparse output enums.
  • SKPolynomialFeatures — builder-only configured expander. Builder: degree(usize) (default 2), interaction_only(bool), include_bias(bool), sparse_output(bool) (default false), backend, execution_mode.
  • SKPolynomialFeaturesModel — the term list plus input/output counts; transform_dense, transform_sparse, transform, terms, backend.

5. A walk through the real tests

Both estimators’ companion test modules are the executable specification. A few worth reading in full:

  • text_column_encodes_to_indicators — the tracer bullet: one text column, the exact indicator matrix, the output width. It proves the whole path (view → intern → encode) end to end.
  • output_width_is_sum_of_category_counts — two columns of two categories each give four output columns, pinning the offset arithmetic.
  • unknown_category_rejected_by_default / unknown_category_ignored_encodes_zeros — the two faces of the handle_unknown policy.
  • builder_selects_default_output — the encoder defaults to sparse, the expander to dense, and each builder flips its default.
  • streaming_uneven_batches_equal_dense (both) — three rows fed in batches of two-then-one produce exactly the dense result, the out-of-core promise.
  • hand_checkable_expansion — the row [2, 3] expands to [1, 2, 3, 4, 6, 9], the scikit-learn column order.
  • documented_column_order_is_stable — the term list itself is asserted, so the order can never drift silently.
  • sparse_matches_dense (both) — the densified CSR equals the dense matrix, the guarantee that the two output paths agree.

6. What it cost, and what it unlocked

The whole change is additive: SKDataView and every existing estimator are untouched; the categorical view is a new sibling, non-exhaustive so it can grow. The one non-obvious recurring cost is the borrow choreography — lifetimes through TryInto, &[&[&str]] into a view into a table — which is exactly why the boundary, and not each encoder, owns the conversion impls.

What it unlocked is larger than two transformers. Every future categorical consumer — the SKKNNImputer that imputes per column, the codecs that move labelled data, the pipelines that chain a transformer’s sparse output into the next stage — now has a boundary to speak through. And the sparse output path is shared: the same two-pass CSR build will serve PCA, truncated SVD and the kernel machines still to come.


7. Recap

  • Categorical features get a boundary, not a private input: SKCategoricalView with a documented missing sentinel.
  • SKOneHotEncoder interns labels into deterministic per-column tables and emits dense or sparse indicators; handle_unknown and the missing sentinel define the edges.
  • SKPolynomialFeatures enumerates exponent terms lazily in a stable scikit-learn order and emits dense or sparse expansions.
  • Both are builder-only, carry their backend, stream out-of-core, and expose their learned state as the export boundary.

Next chapter: with features now encodable, the book turns to the first supervised models — starting with SKLinearRegression — where these encoders and expanders finally become inputs to a model that learns.

Chapters are added in the order the pull requests landed. The linear-model chapter will be registered in SUMMARY.md when it lands.

Imputation: SKSimpleImputer and SKMissingIndicator

The encoders crossed the categorical boundary. This chapter crosses a boundary of a different kind: every estimator so far assumed the matrix was complete. Real tabular data is not. Sensors drop readings, joins leave holes, surveys skip questions — and a mean, a distance or a dot product that meets a hole either produces a NaN that poisons everything downstream or silently pretends the row does not exist. Wave 1’s last preprocessing family is the answer: one estimator fills the holes, another reports them, and a builder flag lets the first stack the second after its own output.

flowchart LR
  accTitle: How the simple imputer turns a feature matrix into an imputed output
  accDescr: A dense or sparse feature matrix becomes a data view. The missing-value check finds the observed entries per column, a statistic such as mean, median, mode or constant is computed, and the fitted model transforms the data into dense or sparse imputed output. An optional missing indicator model is stacked last.
  subgraph Input["One feature matrix"]
    D["dense Array2<br/>[[1.0, NaN, 10.0], ...]"]
    S["sparse CsMat (CSR)<br/>explicit entries + implicit zeros"]
  end
  D --> V["SKDataView"]
  S --> V
  V --> M{"sk_is_missing(value, marker)"}
  M --> O["observed set per column"]
  O --> ST["statistic<br/>mean · median · mode · constant"]
  ST --> MODEL["SKSimpleImputerModel<br/>statistics · dropped columns · state"]
  V --> MODEL
  MODEL --> T["transform"]
  T --> OUT["SKImputedOutput<br/>Dense or Sparse"]
  MODEL -. "add_indicator" .-> IND["SKMissingIndicatorModel<br/>scope · mask"]
  IND -. "stacked last" .-> OUT

  classDef input fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
  classDef marker fill:#fef3c7,stroke:#d97706,color:#78350f
  classDef observed fill:#d1fae5,stroke:#059669,color:#064e3b
  classDef model fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
  classDef output fill:#ffe4e6,stroke:#e11d48,color:#881337
  class D,S input
  class M marker
  class O,ST observed
  class MODEL,IND model
  class T,OUT output

1. The problem we were solving

A missing cell is not a small inconvenience. Suppose you want the mean of a column that holds [1, NaN, 3]. Three answers are tempting and only one is correct: treat NaN as zero (4/3 = 1.33, wrong), drop the row ([1, 3] → 2, right here but wrong when other columns are fine), or skip the missing cell ((1+3)/2 = 2, right). The third is what scikit-learn’s SimpleImputer does, and it is what we wanted: learn a statistic over the observed cells and fill only the missing ones.

That introduces three genuinely new problems.

  1. What counts as missing? NaN is the obvious marker, but real files encode missingness as -1, -999, or sometimes 0. The marker has to be configurable, and it has to mean the same thing in a dense matrix and in a sparse one — where a value can be absent from storage entirely.
  2. What happens at the edges? A column that is missing in every row has no mean and no median. Do we drop it? Keep it as zero? And what if a cell that was complete at fit time is missing at transform time — is that an error, or just another fill?
  3. Can the information be kept? Filling a hole with the mean destroys the fact that the value was ever absent. For a downstream model that fact is often a signal. scikit-learn answers with MissingIndicator: a 0/1 mask of the cells that were missing. We wanted both the imputer and the mask, composable.

The engineering problem, as with the encoders, was the seam: the marker and the “observed set” logic must be identical in dense and sparse paths, in the batch fit and in the streaming fit, and in the imputer and the indicator. Solving it once, in one crate, is half of this chapter.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
A new crate, sciencekit_imputeThe PRD’s crate tree reserves imputation for Phase 1, item 6. It owns the missing-data estimators and depends on sciencekit_common and sciencekit_math, exactly like sciencekit_preprocessing.Adding the imputer to sciencekit_preprocessing — a different concern and a different wave, and it would blur the crate boundary the PRD draws.
One marker rule for both representationsDense: NaN marker means is_nan, any other marker means ==. Sparse: explicit entries follow the same rule, and the 0.0 marker additionally claims the implicit zeros (the cells CSR does not store). One predicate, sk_is_missing, and one companion, sk_sparse_marks_implicit_zeros.A separate “sparse marker” — two subtly different behaviors for the same option. Treating implicit zeros as always observed — wrong for data where 0 is the missing code.
A generic estimator, SKSimpleImputer<F>The configuration carries values of the scalar: missing_values and fill_value are F. Carrying them in the type keeps the builder honest and mirrors SKRobustScaler<F>.A non-generic estimator over f64 — the library is generic over SKFloat and f32 must work.
Mean via a compensated sumA plain running sum loses low-order bits on long columns. Neumaier compensation keeps an error term per column, so the statistic is stable even with thousands of small values and one huge one.Plain sum() — fast, but the tests compare against hand-checked values and the streaming path must match the batch path.
Median as an order statistic; ties in the mode to the smallest valueThe median sorts the observed values (midpoint of the middle pair on an even count); the mode sorts and scans runs, replacing only on a strictly larger count, so a tie always resolves to the smallest value. Both are deterministic.Hash-based mode — SKFloat has no Hash, and hash iteration order would make ties unpredictable.
All-missing column → NaN statistic, recorded as droppedA column with no observed cell has no statistic. The model stores NaN in statistics (one entry per input column) and lists the column in dropped_columns unless keep_empty_features(true), which retains it filled with 0.0.Dropping silently — the export boundary must tell the caller which columns vanished. Inventing a statistic — every invented value is a lie.
partial_fit and fit_streaming from day oneThe project’s iterative mandate forbids skipping the incremental/out-of-core stage. The model carries a SKImputationState with per-column counts, compensated sums, value counts and a tdigest sketch, so one more batch extends the same state.Batch-only — a Wave 1 estimator that cannot stream would be re-opened in Wave 2.
The median sketch stores only explicit values; structural zeros are a separate multiplicityIn CSR, the implicit zeros are not stored, so a sketch cannot see them. The state keeps their count per column and inverts the combined CDF: $(\text{explicit} \cdot F_{\text{explicit}} + \text{zeros} \cdot [v \ge 0]) / \text{total}$. This is exact for a single batch and within tolerance across batches.Weighting the zero centroid in the sketch — tdigest interpolates between centroid means, and the test [0,0,0,0,10,12] returned 4.0 instead of 0.0.
The mask is typed on F, not boolSKIndicatorOutput<F> emits 0.0/1.0 in the scalar type so a stacked output is one matrix of one scalar, ready for the next pipeline stage.A bool mask — scikit-learn’s choice; it would introduce a second scalar type through every downstream pipeline. The deviation is recorded in the ADR and pinned by tests.
add_indicator composes, it does not special-caseThe imputer fits a real SKMissingIndicator on the same batch (same marker, same backend, error_on_new(false)) and stores the fitted model. The transform runs the imputation, then stacks the mask in a second pass.A private mask routine — duplicated logic that would drift from the standalone indicator.
error_on_new defaults to trueMissingness in a feature that was complete at fit is suspicious: the training distribution changed. The default fails with a precise SKError::UnexpectedMissingness { column }; error_on_new(false) tolerates it and leaves the cell unmarked.Silently masking the new column — it has no mask column, so the information would be lost invisibly.
The backend kind is still carriedThe math is reductions and order statistics, not heavy algebra, but both estimators expose backend(SKBackendKind) and record it in every span — the selection surface stays uniform (spec backend-selection).Omitting it — an inconsistency every other estimator would expose.

3. The concepts, taught from zero

The marker and the observed set

sk_is_missing(value, marker) is the single predicate the whole crate shares:

$$\text{missing}(v, m) = \begin{cases} v \ne v & m \text{ is } \texttt{NaN} \ v = m & \text{otherwise} \end{cases}$$

The $v \neq v$ trick is the standard way to ask “is this a NaN” without naming the type. The second branch is plain equality — which is why the 0.0 marker has a special consequence in sparse data. sk_sparse_marks_implicit_zeros(marker) answers “does the marker claim the cells CSR does not store?”, and it is true only for 0.0: a NaN marker leaves structural zeros observed, while a 0.0 marker makes every structural zero missing.

The observed set of a column is everything the marker does not claim. The dense path visits every cell; the sparse path visits the explicit entries and adds the structural zeros as a multiplicity. The SKObservedColumn<F> type in simple_imputer/statistics/ materializes that set exactly once, and both representations build it, so “sparse agrees with dense” is true by construction rather than by a second implementation.

The four strategies

With the observed values in hand, each strategy is a one-line definition:

  • Mean — the compensated sum divided by the count. The Neumaier compensation is a second accumulator holding the rounding error; adding it back at the end recovers the bits a naive sum loses. Test: mean_over_the_observed_values.
  • Median — sort the observed values; take the middle one, or the average of the middle pair when the count is even. Tests: median_of_an_odd_observed_count, median_of_an_even_observed_count_averages_the_middle_pair.
  • Most frequent — sort, scan runs of equal values, and replace the winner only when a run is strictly longer. Ties therefore resolve to the smallest value. Test: most_frequent_tie_breaks_toward_the_smallest.
  • Constant — ignore the observed set and fill with fill_value, default 0.0. A fill_value(Some(NaN)) is rejected at build time with InvalidHyperparameter, because filling missing cells with a missing value would be a no-op pretending to be an imputation. Test: fill_value_of_nan_under_constant_is_rejected.

The model stores one statistic per input column. A column that has no observed value gets NaN there, and — unless keep_empty_features is on — its index is recorded in dropped_columns. number_of_output_features() is therefore number_of_input_columns - dropped_columns.len(), and the transform knows both the width and which source columns to skip. Tests: all_missing_column_gets_a_nan_statistic_and_is_reported, all_missing_column_is_dropped_by_default, keep_empty_features_retains_the_column_as_zero.

A NaN statistic is not by itself proof that a column is empty, and the two cases must not be confused. Under a marker other than NaN, a NaN cell is an observed value: a column such as [NaN, 1.0] with missing_values(0.0) has observed data whose mean happens to be NaN. The column is therefore kept, and its missing cells are filled with that NaN statistic — only a column with no observed cell at all falls back to the 0.0 of a retained empty column. Tests: a_nan_value_under_a_zero_marker_is_observed_so_the_column_stays, a_nan_statistic_over_observed_data_fills_with_that_statistic, a_retained_empty_column_still_fills_with_zero.

The incremental state and the three regimes

SKImputationState<F> is what makes the estimator iterative. Per column it keeps:

  • a count of observed values;
  • a compensated sum and its compensation;
  • a value_counts map keyed by the bit pattern of the value (normalizing -0.0 to 0.0, since SKFloat has no Hash), so the mode can be extended without re-reading old batches;
  • a tdigest sketch of the explicit values, for the online median;
  • the count of implicit zeros, kept apart from the sketch.

fit seeds this state with the batch, then derives the exact statistics: the mean, mode and constant come straight from the state, and the median takes the exact order statistic of the batch (the sketch is still seeded so partial_fit can continue from it). The state also tracks the columns that carried at least one missing cell, so the composed indicator can be rebuilt from it. partial_fit extends the state and refreshes the statistics, the empty-column policy and the indicator scope — a missing column first seen in a later batch becomes a mask column, exactly as if the batches had been concatenated. The tests split_batches_equal_the_whole_for_mean and split_batches_equal_the_whole_for_most_frequent assert that two halves and the concatenation produce the same model; median_stays_within_the_sketch_tolerance_of_the_dense_fit states the one documented approximation.

flowchart TB
  accTitle: Three fitting regimes that share one simple-imputer model
  accDescr: A single batch seeds the state and computes exact statistics. Partial fit extends the same state and refreshes the statistics. Streaming either collects batches for an in-process fit or drives one batch at a time, taking the median from a sketch. All three regimes produce the same model.
  subgraph Batch["fit — one batch"]
    B1["seed the state<br/>counts · sums · value_counts · sketch"] --> B2["exact statistics<br/>mean/mode/constant from the state<br/>median from the order statistic"]
  end
  subgraph Incremental["partial_fit — one more batch"]
    I1["extend the same state"] --> I2["refresh the statistics"]
  end
  subgraph Stream["fit_streaming — a lazy source"]
    S1{"execution intent<br/>in-process?"}
    S1 -->|yes| S2["collect the batches<br/>run the dense fit"]
    S1 -->|no| S3["driver: one batch at a time<br/>each a PartialFit span"]
    S3 --> S4["mean · mode · constant exact<br/>median from the sketch"]
  end
  Batch --> Model["SKSimpleImputerModel"]
  Incremental --> Model
  S2 --> Model
  S4 --> Model

  classDef batch fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
  classDef incremental fill:#d1fae5,stroke:#059669,color:#064e3b
  classDef stream fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
  classDef model fill:#ffe4e6,stroke:#e11d48,color:#881337
  class B1,B2,S1 batch
  class I1,I2 incremental
  class S2,S3,S4 stream
  class Model model

The streaming driver is the same sk_run_streaming_driver the scalers use. Its state validates the column count, parks the error and stops the pipeline on a mismatch, skips empty batches, and instruments each batch as PartialFit with the configured backend. The in-process branch collects the batches and reuses the dense path, so its result is exactly the concatenated fit — the test in_process_streaming_matches_the_dense_fit_exactly pins that.

Why the median needs a CDF inversion

tdigest summarizes a distribution as centroids and estimates quantiles by interpolation. For explicit values that is exactly what we want. The problem is the structural zeros: they are not in the sketch, and pushing a synthetic zero centroid corrupts the interpolation between neighbouring centroids. The state therefore keeps the zeros as a multiplicity and inverts the combined CDF instead:

$$q(p) = \begin{cases} -\infty \text{ direction: } 0 & \text{if } p \cdot \text{total} \le z \ \text{explicit quantile} & \text{otherwise} \end{cases}$$

where z is the number of structural zeros and total = explicit + z. In words: if the target rank falls inside the zero block, the answer is zero; otherwise it falls in the explicit mass and the sketch answers. The test median_places_the_implicit_zeros_in_their_rank_block walks [0,0,0,0,10,12] and shows the median landing at 0 — the case the weighted-centroid approach got wrong.

The missingness mask

SKMissingIndicator is a second, independent transformer. fit scans the matrix and records the scope: under MissingOnly (the default) the columns with at least one missing cell, under All every column. transform emits a 0.0/1.0 matrix with one column per scoped feature, in ascending column order. A dense input yields a dense mask unless sparse_output(true) asks for CSR; a sparse input always yields CSR, with stored entries exactly at the missing cells. Tests: mask_marks_the_missing_cells, dense_input_yields_a_dense_mask_in_scope_order, sparse_input_yields_a_sparse_mask.

The interesting edge is missingness that fit never saw. With error_on_new(true) (the default) the transform fails before writing anything, naming the offending column: SKError::UnexpectedMissingness { column: 0 }. With error_on_new(false) the cell is tolerated and simply not masked — the mask only covers the scope learned at fit. Tests: new_missingness_is_rejected_by_default, new_missingness_is_tolerated_on_request.

flowchart TB
  accTitle: How the missing indicator model decides which columns to mask
  accDescr: Fit scans every column and selects either the columns with at least one missing cell or all columns. Transform rejects a missing cell outside the scope when configured to error; otherwise it emits a zero-or-one mask, dense or CSR, which the imputer stacks after the imputed features when add_indicator is set.
  F["fit: scan every column"] --> SC{"scope"}
  SC -->|MissingOnly| MO["columns with ≥1 missing cell"]
  SC -->|All| AL["every column"]
  MO --> MODEL["SKMissingIndicatorModel<br/>scope · input width · marker · backend"]
  AL --> MODEL
  MODEL --> T["transform"]
  T --> C{"missing cell outside the scope<br/>and error_on_new?"}
  C -->|yes| E["SKError::UnexpectedMissingness<br/>naming the column"]
  C -->|no| MASK["0.0 / 1.0 mask<br/>dense, or CSR"]
  MASK --> STACK["add_indicator:<br/>stacked after the imputed features"]

  classDef fit fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
  classDef model fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
  classDef error fill:#ffe4e6,stroke:#e11d48,color:#881337
  classDef mask fill:#d1fae5,stroke:#059669,color:#064e3b
  class F,SC,MO,AL fit
  class MODEL model
  class E error
  class T,C,MASK,STACK mask

Stacking the mask after the features

add_indicator(true) makes the imputer compose the indicator instead of duplicating it. At fit, an indicator is built with the imputer’s marker, error_on_new(false) (so a transform the imputer can handle is never failed by the mask) and the same backend kind; its fitted model is stored in SKSimpleImputerModel::indicator(). The scope is not frozen at the first batch: the state records the missing columns batch by batch, and partial_fit rebuilds the indicator from it, so an incrementally fitted model answers like one fitted on the whole. At transform, the imputation runs first — dropping the empty columns — and the mask is concatenated along the column axis. For a dense result that is an ndarray concatenation; for CSR it is a triplet rebuild that shifts the mask columns past the feature columns. The output width is therefore

$$\text{width} = \text{retained features} + \text{mask columns}.$$

The test stacking_appends_one_column_per_missing_feature fits a 3-column matrix missing only in its second column, which is dropped as empty: the output is [[2.5, 4.5, 1.0]] — two features, then one mask — and sparse_stacking_appends_the_mask_columns asserts the same shape for CSR. a_retained_empty_column_keeps_its_indicator_column shows the other policy: with keep_empty_features(true) the column stays as 0.0 and keeps its mask column.


4. The public objects

  • SKSimpleImputer<F> — builder-only configured imputer. Builder: strategy, missing_values(F) (default NaN), fill_value(Option<F>) (default None, meaning 0.0 under Constant), keep_empty_features(bool) (default false), add_indicator(bool) (default false), backend, execution_mode.
  • SKImputationStrategy — Mean, Median, MostFrequent, Constant.
  • SKImputedOutput<F> — the non-exhaustive result: Dense(Array2<F>) or Sparse(CsMat<F>).
  • SKSimpleImputerModel<F> — the fitted state: statistics(), dropped_columns(), number_of_input_columns(), number_of_output_features(), strategy(), missing_values(), indicator(), backend(), execution_intent(), plus partial_fit.
  • SKMissingIndicator<F> — builder-only mask. Builder: features(SKMissingFeatureScope) (default MissingOnly), error_on_new(bool) (default true), sparse_output(bool) (default false), missing_values(F), backend, execution_mode.
  • SKMissingFeatureScope — MissingOnly or All.
  • SKMissingIndicatorModel<F> — the learned scope: scope(), number_of_input_columns(), number_of_output_columns(), features(), error_on_new(), sparse_output(), backend().
  • SKIndicatorOutput<F> — the non-exhaustive mask result: Dense(Array2<F>) or Sparse(CsMat<F>).
  • sk_is_missing / sk_sparse_marks_implicit_zeros — the shared marker predicates in sciencekit_impute::missingness.

5. A walk through the real tests

The companion modules are the executable specification; these are the ones worth reading in full:

  • the_tiny_matrix_is_hand_checkable_end_to_end (acceptance) — the tracer bullet: [[1, NaN, 10], [3, 4, NaN], [5, 6, 30]] imputed with the mean and with the median, both hand-computed to the same [[1,5,10],[3,4,20],[5,6,30]].
  • sparse_mean_counts_the_implicit_zeros_as_observed and sparse_zero_marker_makes_the_implicit_zeros_missing — the two faces of sparse marker semantics, pinned in the fit tests.
  • observed_cells_stay_bit_identical — the transform changes only the missing cells; every observed value is copied bit for bit.
  • zero_marker_fills_the_implicit_zeros — with a 0.0 marker the CSR rebuild also materializes the cells that storage never held.
  • a_retained_empty_sparse_column_stores_no_explicit_zeros — the CSR rebuild never writes a filled 0.0, because 0.0 is exactly what the format leaves implicit: the retained empty column is still there in the dense view, but it costs no stored entry.
  • split_batches_equal_the_whole_for_mean — two partial_fit halves equal one fit, the incremental promise.
  • streaming_driver_mean_is_exact / streaming_driver_median_stays_within_the_sketch_tolerance — what the out-of-core driver guarantees exactly and what it approximates.
  • median_places_the_implicit_zeros_in_their_rank_block — the CDF inversion that fixed the structural-zero median.
  • a_large_generated_matrix_streams_like_the_concatenated_fit (acceptance) — 4,000 rows in eight chunks match the in-memory fit column by column.
  • missing_only_scope_is_exactly_the_missing_columns and the_scope_is_deterministic_across_fits — the indicator’s scope is learned, exact and stable.
  • new_missingness_is_rejected_by_default — the error names the column, and the remedy is in the message.
  • incremental_batches_extend_the_indicator_scope_like_the_whole — a missing column introduced by the second batch lands in the mask of a model learned with partial_fit, matching the concatenated fit.
  • one_fitted_model_transforms_concurrently (acceptance) — one model, eight threads, identical results: the model is Send + Sync by construction.

6. What it cost, and what it unlocked

The cost is state discipline. The estimator is cheap; the model is not: it carries the exact statistics, the dropped-column list, the incremental state (including a tdigest per column) and the optional indicator model. That is what makes partial_fit possible and what makes the model the single export boundary — every learned fact is behind an accessor, never recomputed.

The other cost is two representations. Dense and sparse paths must agree, and the tests hold them to it: the same statistics (dense_and_sparse_inputs_produce_equal_outputs), the same imputation, the same mask. The observed-set abstraction paid for itself here — the marker rules live once, and the strategies consume the same type in both paths.

What it unlocked is the rest of the roadmap. Every model that follows — the linear models, the neighbors, the trees — can now assume complete numeric input, or ask for the mask and learn from the missingness itself. SKKNNImputer, the multivariate imputer of the next wave, has both the crate and the marker semantics to build on.


7. Recap

  • Missing values are defined by a marker, configurable per estimator, with one shared predicate for dense and sparse — and structural zeros are missing only under the 0.0 marker.
  • SKSimpleImputer fills each column with a mean, median, most frequent or constant statistic, drops all-missing columns by default (or keeps them at 0.0), and stacks a missingness mask when add_indicator is on.
  • SKMissingIndicator learns the scope at fit and emits a 0.0/1.0 mask, rejecting missingness it never saw unless error_on_new(false).
  • Both run as a batch fit, an incremental partial_fit, and an out-of-core fit_streaming; the mean, mode and constant stay exact, the median stays within a documented sketch tolerance.
  • Both are builder-only, carry their backend, and expose their learned state through accessors — the export boundary.

Next chapter: with imputation in place, the book turns to the first supervised models, where complete, encoded feature matrices finally become inputs to a model that learns — see Linear models: SKLinearRegression.

Chapters are added in the order the pull requests landed. The linear-model chapter is registered in SUMMARY.md.

Linear models: SKLinearRegression

The imputation chapter closed Wave 1 by making feature matrices complete. This chapter opens Wave 2 and crosses a different boundary: for the first time an estimator learns from targets. Every object before it — the scalers, the encoders, the imputers — transformed features and never looked at an answer. SKLinearRegression is the library’s first supervised estimator, and it is the template every regressor and classifier after it copies.

Ordinary least squares also looks deceptively simple: “draw the best line through the points”. The whole chapter is about the two places that simplicity lies. The first is which decomposition carries the solve — the obvious one is a numerical trap. The second is what a streaming version of a dense linear system even means, and the honest price of it.

flowchart TB
  accTitle: One linear-regression plan with dense and streaming regimes
  accDescr: The execution plan chooses between an in-memory dense solve by SVD pseudoinverse and an out-of-core streaming path that accumulates the Gram matrix and cross-product per batch, then solves once at stream end. Both produce the same fitted model, which predicts as X times coefficients plus intercept.
  subgraph Plan["One plan, three regimes"]
    Q{"sk_resolve_execution_plan(Automatic)"}
  end
  Q -->|"fits in RAM"| D["design A = [1 ‖ X]<br/>backend.lstsq → SVD pseudoinverse<br/>rank + singular values surfaced"]
  Q -->|"larger than RAM"| S["per batch:<br/>G += BᵀB  ·  c += Bᵀy<br/>row_count += rows"]
  S --> E["solve(G, c) at stream end<br/>⚠ condition number squared — stated trade-off"]
  D --> M["SKLinearRegressionModel<br/>coefficients · intercept · rank"]
  E --> M
  M --> P["predict: X·coefficients + intercept"]
  M -. "partial_fit" .-> S

  classDef planNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
  classDef denseNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
  classDef modelNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
  class Q planNode
  class D denseNode
  class S,E streamNode
  class M,P modelNode

1. The problem we were solving

We have rows of features $x_i \in \mathbb{R}^p$ and a numeric answer $y_i \in \mathbb{R}$ for each. We want a vector of coefficients $\beta$ and an intercept $b_0$ so that $x_i \cdot \beta + b_0 \approx y_i$. “Best” means least squares: choose $\beta, b_0$ to minimize $\sum_i (y_i - x_i \cdot \beta - b_0)^2$. Written as one matrix equation, with the design matrix $A = [1 ,\Vert, X]$ (a column of ones prepended to the features), it is:

$$\min_{\beta} \lVert A \beta - y \rVert_2$$

Three problems sit under that innocent line.

  1. Which solver? There are three standard roads to $\beta$, and the difference between them is not style — it is how many correct digits survive. The textbook one-liner (the normal equations) is a trap, and the trap is exactly the situation practitioners meet most.
  2. What if the columns are redundant? Two features that co-move make the design rank-deficient. A naive solve returns an answer that claims to be the answer. We wanted the answer to admit it is degenerate.
  3. What does streaming mean? Every estimator in the library must also run out-of-core (PRD §4.4). But a dense linear system has no obvious “one batch at a time” form. The choice of streaming formulation is a real decision with a real price.

Solving all three once, honestly, is what this chapter records.


2. The decisions — and the roads not taken

DecisionChosenRoads not taken — and why they are traps
Dense solverSVD least squares through the backend’s lstsq (the pseudoinverse path)Normal equations ($\operatorname{solve}(A^{\mathsf T}A, A^{\mathsf T}y)$) square the condition number: $\kappa(A^{\mathsf T}A) = \kappa(A)^2$. For even moderately ill-conditioned real data that is the difference between ~13 and ~7 trustworthy digits, silently wrong exactly where correlated features live. QR is stable and cheaper but does not report rank for free — deferred as a profile-driven escape hatch.
InterceptDesign-matrix augmentation: prepend a column of ones, solve $b_0$ jointly with $\beta$Center-then-solve (subtract the means, solve, recover the intercept) collapses rank prematurely on rank-deficient designs and complicates the streaming accumulator. The augmented matrix is the same object the streaming path accumulates.
StreamingGram accumulation: carry $A^{\mathsf T}A$ and $A^{\mathsf T}y$ per batch, solve once at the endSolve per batch and average the coefficients — a weighted average hides how the rows were distributed and per-batch ranks do not compose. The Gram form composes exactly. It re-introduces the squared condition number — accepted and documented, not hidden.
Rank deficiencySurface rank and singular_values on the model; return the minimum-norm solutionSilently computing with a rank-deficient matrix and returning “the” answer is a subtraction bug in plain sight. SVD hands rank and singular values for free.
Scalar genericityEstimator not generic (its config carries no scalar); model generic over FMaking the estimator generic when nothing in its configuration is scalar would add a phantom type parameter — against backend-selection.

3. The concepts, taught from zero

3.1 Three roads to the least-squares solution

Set the gradient of $\lVert A\beta - y \rVert_2^2$ to zero and you get the normal equations: $A^{\mathsf T}A \beta = A^{\mathsf T}y$. When rows $\gg$ columns, $A^{\mathsf T}A$ is a small $p \times p$ object (instead of the tall $n \times p$ design), which made this the pedagogical favourite for decades. The catch is measurable:

$\kappa(A^{\mathsf T}A) = \kappa(A)^2$ — the condition number squares.

The condition number is the factor by which a linear solve can amplify rounding. Doubling its exponent means doubling the digits you lose. If $A$ has condition $10^7$, $A^{\mathsf T}A$ has $10^{14}$, and a 64-bit float has about 16 digits — with the normal equations the solve is allowed roughly two digits of trust, on exactly the gritty, correlated-feature data we are asked to process.

QR orthogonalizes $A = QR$ and solves $\beta = R^{-1}Q^{\mathsf T}y$. Because $Q$ is perfectly conditioned, $\kappa(QR) = \kappa(A)$ — the condition is not squared. Stable and $O(np^2)$.

SVD factors $A = U\Sigma V^{\mathsf T}$, so $\beta = \sum_{\sigma_i \neq 0} (u_i \cdot y / \sigma_i), v_i$ — the pseudoinverse solution. It costs more than QR and does something QR does not: it shows you the rank. Singular values near zero declare exactly which features make the problem degenerate, and the pseudoinverse path degrades gracefully when A is not full-rank, returning both the minimum-norm solution and the information that it did so.

We chose SVD, exposed as the backend’s lstsq. The algorithm never sees faer or ndarray-linalg — the backend is injectable and the solver is a dispatch-level truth.

3.2 The design matrix and the intercept

Instead of treating the intercept as a special case, we prepend a column of ones:

$$A = [,1 \mid X,], \qquad \beta = [,b_0 \mid \beta_{\text{features}},]^{\mathsf T}$$

The intercept becomes one more coefficient, solved by the same call. The payoff appears in §3.3: the streaming path accumulates $A^{\mathsf T}A$ for this matrix, so the intercept rides along with no separate pass.

3.3 The streaming road — and its honest price

The tempting streaming idea — solve least squares per batch and average the $\beta$ — is almost never right: a weighted average hides how the covered rows were distributed, and per-batch ranks do not compose. What composes is the raw material of the normal equations:

$$G := A^{\mathsf T}A \quad (p \times p,\ \text{symmetric}), \qquad c := A^{\mathsf T}y \quad (p,\ \text{the right-hand side})$$

Each batch $B$ adds a rank-$\lvert B \rvert$ contribution: $G := G + B^{\mathsf T}B$, $c := c + B^{\mathsf T}y_{\text{batch}}$. At the end, one solve of $G\beta = c$ yields the coefficients. Exactly one extra fact must be said out loud: we computed $A^{\mathsf T}A$, so we are square-conditioning again. The streaming trade-off is:

in-memory SVDstreaming Gram
Trustworthy digits at $\kappa(A)=10^7$~9~3–5 (the squared condition eats the rest)
Memory per stream step$O(np)$$O(p^2)$ — the entire point
Rank at stream endnativeonly via $G$’s own singular values ($\approx \sigma_i^2$ of $A$)

We keep the dense path on SVD and the streaming path on the Gram. They are not “the same computation”; they are two honest points on a trade-off, and the tests below pin where they agree.

3.4 The state that combines

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/linear_regression/gram.rs
pub(crate) struct SKGramState<F> {
    pub(super) design_width: usize,
    pub(super) gram: Array2<F>,   // AᵀA
    pub(super) rhs: Array1<F>,    // Aᵀy
    pub(super) row_count: u64,
}
}

The single source of truth for the incremental and streaming regimes: the coefficients are a pure function of these three quantities, so batch order and sizes do not change the result. The dense fit records the same state too, so a densely-fitted model can keep learning through partial_fit.

3.5 A supervised streaming block

Wave 1’s streaming executor carries features only (SKDataBatch). A supervised out-of-core fit needs the targets alongside them. Rather than stuff a target column into the feature matrix or duplicate the prefetch machinery, this change adds the supervised pair to sciencekit_common:

#![allow(unused)]
fn main() {
// crates/sciencekit_common/src/batching/
pub struct SKSupervisedBatch<F> { features: Array2<F>, targets: Array1<F>, /* position, is_final */ }
pub trait SKSupervisedLazySource<F> { fn next_supervised_batch(&mut self) -> Result<Option<SKSupervisedBatch<F>>, Self::Error>; }
}

and generalizes the prefetch driver so both source kinds share one engine (sk_run_supervised_streaming_driver alongside the unchanged sk_run_streaming_driver).


4. Each object, explained

SKLinearRegression — the estimator

Builder-only configuration with no scalar field, so it is not generic:

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/linear_regression/core_implementation.rs
#[derive(Debug, Clone, Copy)]
pub struct SKLinearRegression {
    pub(super) plan: SKBuilderState,
    pub(super) include_intercept: bool,
    pub(super) backend: SKBackendKind,
}
}

SKLinearRegression::build() exposes include_intercept(bool) (default true), backend(SKBackendKind) (default Faer) and execution_mode(SKExecutionMode) (default Automatic). The direct constructor is private. fit builds the design matrix, records the Gram state, and solves through the backend’s lstsq under a Fit span:

#![allow(unused)]
fn main() {
let design = build_design(&dense, self.include_intercept);
let gram = gram_of(&design, &target, plan.parallelism);
let solution = solve_least_squares(self.backend, design.view(), target.view())?;
SKLinearRegressionModel::from_solution(solution, gram, self.include_intercept, self.backend, self.execution_intent())
}

SKLinearRegressionModel — the fitted model

The learned state and the export boundary, generic over F: SKFloat:

#![allow(unused)]
fn main() {
pub struct SKLinearRegressionModel<F> {
    pub(super) coefficients: Array1<F>,
    pub(super) intercept: F,
    pub(super) rank: usize,
    pub(super) singular_values: Vec<F>,
    pub(super) gram: SKGramState<F>,
    /* include_intercept, backend, execution_intent */
}
}

Accessors: coefficients(), intercept(), rank(), singular_values(), row_count(), backend(). Prediction is SKRegressorPredictor<F>:

#![allow(unused)]
fn main() {
fn predict<'a, X>(&self, features: X) -> Result<Array1<F>, Self::Error> {
    let dense = features.try_into()?.as_dense()?;
    if dense.ncols() != self.coefficients.len() { /* ShapeMismatch */ }
    // ... span ...
    Ok(dense.dot(&self.coefficients).mapv(|value| value + self.intercept))
}
}

Prediction exists only on the model — the estimator has no predict, so predict-without-fit does not compile.

solve_least_squares — the per-operation dispatch

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/linear_regression/solving.rs
pub(super) fn solve_least_squares<F: SKFloat>(kind: SKBackendKind, design: ArrayView2<F>, target: ArrayView1<F>)
    -> Result<SKLeastSquaresSolution<F>, SKError>
{
    let rhs = target.insert_axis(Axis(1));
    match kind {
        SKBackendKind::Faer => SKFaerBackend::new().lstsq(design, rhs),
        SKBackendKind::MatrixMultiply => SKMatrixMultiplyBackend::new().lstsq(design, rhs),
        SKBackendKind::NdArrayLinalg => sk_default_math_backend::<F>().lstsq(design, rhs),
    }
}
}

The configured kind is resolved to a concrete backend at operation time, never in build() — the backend-selection rule.

partial_fit and fit_streaming — the extra regimes

partial_fit merges one batch into the model’s Gram state and re-solves:

#![allow(unused)]
fn main() {
self.gram.accumulate(&design.view(), &target.view(), parallelism);
let solution = solve_least_squares(backend, self.gram.gram.view(), self.gram.rhs.view())?;
let (intercept, coefficients) = split_solution(&solution.solution, include_intercept);
}

fit_streaming resolves the plan against an unbounded context (so Automatic takes the streaming branch), drives the supervised prefetch pipeline with update_gram, and builds the same model type at the end. An in-memory intent instead collects the batches and reuses the dense path — out-of-core is a transport choice, not a different model.


5. Walk-through of the real tests

The executable source of truth is crates/sciencekit_linear_model/src/linear_regression/*_tests.rs, with shared fixtures in test_datasets.rs. The small fixture is a hand-checkable line: X = [[1,0],[0,1],[1,1],[2,1]] with $y = 3x_0 - 2x_1 + 0.5$.

  • Exact recovery (recovers_exact_coefficients_and_intercept): the SVD fit returns coefficients [3, −2] and intercept 0.5 to 1e-9.
  • Rank surfaced (surfaces_rank_and_singular_values): the augmented design is full rank 3, with three non-increasing singular values.
  • Rank deficiency is a feature (rank_deficiency_yields_a_minimum_norm_solution): a design whose second column is exactly twice the first still fits; the reported rank drops below the design width and the predictions still reproduce the targets.
  • Intercept off (intercept_can_be_disabled): include_intercept(false) reports a zero intercept and fits the best line through the origin.
  • Errors before work (rejects_empty_input, rejects_sparse_input, rejects_target_length_mismatch, rejects_prediction_shape_mismatch): each raises the right central SKError before touching the backend.
  • Backend carried (default_backend_is_faer, backend_override_reaches_the_model): the configured kind reaches the model.
  • Concurrency (model_serves_concurrent_predictions): one Arc<model> serves eight threads with identical predictions.
  • Streaming ≡ dense (streaming_matches_the_dense_fit_on_large_data): a 50 000 × 6 design streamed in uneven batches agrees with the dense fit to 1e-6 — the cross-regime tolerance that admits the Gram’s squared condition.
  • Incremental ≡ dense (incremental_matches_the_concatenated_fit, row_by_row_accumulation_matches_the_dense_fit): splitting the data and accumulating with partial_fit — even one row at a time — converges to the concatenated fit.
  • Supervised streaming contract (in sciencekit_common): supervised_driver_pairs_features_and_targets pins that each update step receives that block’s features and targets, in order.

6. Acceptance and what it unlocked

Acceptance criterion (PRD §8.7 / §10.3)Where it lands
Lots and little datathe four-row fixture and the $50,000 \times 6$ one
Under concurrencymodel_serves_concurrent_predictions + Send + Sync assertion
Model exportthe model is the distinct, backend-carrying export boundary (Safetensors/JSON deferred to Phase 7)
Metricsthe SKSupervisedScorer contract is ready; the metrics suite (W6.3) exercises $R^2$ against these models

The change also paid two debts forward. The Gram kernels (sk_gram_matrix, sk_gram_vector) are reusable substrate — ridge and PCA’s covariance accumulator will consume the same cross-products. And the supervised streaming contract means every supervised algorithm of Wave 2+ (ridge, lasso, logistic, SGD) fits out-of-core without reinventing a target-carrying batch.


7. Recap

  • SKLinearRegression is the library’s first supervised estimator: a builder-only, scalar-free estimator and a distinct, generic fitted model.
  • The dense fit goes through the backend’s SVD least-squares kernel, never the normal equations, and surfaces rank and singular_values.
  • The intercept is a design-matrix column, solved jointly.
  • partial_fit and fit_streaming accumulate the Gram state ($A^{\mathsf T}A$, $A^{\mathsf T}y$) and solve once — with the squared-condition trade-off stated, not hidden.
  • A new supervised streaming contract in sciencekit_common carries features and targets through the shared prefetch driver.

Next chapter: the family where streaming is not an adaptation but the home — gradient descent, state-as-accumulator, and why in-memory training is just “the batch of everything”.

Regularized linear models: SKRidge

The linear-regression chapter left Wave 2 with one supervised estimator and a deliberately narrow toolkit: it fit the unregularized least-squares line, learned from dense input, and streamed via the Gram accumulator. SKRidge is the second Wave 2 algorithm, and it is the first whose linear system is regularized. Inheriting the estimator/model split, the per-operation backend dispatch and the Gram streaming path from SKLinearRegression, it adds the four things that fit deliberately left out: a penalty parameter that is a configuration scalar (so the estimator becomes generic over F), a portfolio of solvers with different numerical personalities, sparse input that never densifies, and a model that carries one solution per alpha.

Ridge also needs a piece of numerical machinery that did not exist yet — iterative solvers. That substrate lives in sciencekit_math, because PCA’s covariance solves and the regularized models after ridge will want it too. This chapter tells the story of both.

flowchart TB
  accTitle: One ridge estimator with dense, sparse and streaming regimes
  accDescr: The execution plan selects a centered-Gram Cholesky solve for dense in-memory data, a conjugate-gradient solve over a borrowed CSR view for sparse data, or a streaming path that accumulates the Gram state and solves once at the end. All paths produce the same multi-alpha model.
  subgraph Plan["One estimator, four regimes"]
    Q{"sk_resolve_execution_plan(Automatic)"}
  end
  Q -->|"fits in RAM · dense"| D["centered Gram Ĉ = XᵀX − n·x̄x̄ᵀ<br/>Cholesky: (Ĉ + αI)β = ĉ<br/>fallback → SVD: β = V diag(σ/(σ²+α)) Uᵀ ỹ"]
  Q -->|"fits in RAM · sparse"| S["SparseCg over a borrowed CSR view<br/>DᵀD·v applied in place — XᵀX never formed"]
  Q -->|"larger than RAM"| G["per batch: gram += BᵀB · cross += Bᵀy<br/>sums += Σx · row_count += rows"]
  G --> E["solve_from_gram once at the end<br/>(Ĉ + αI)β = ĉ through Cholesky"]
  D --> M["SKRidgeModel<br/>coefficients n_alphas × n_features · intercepts"]
  E --> M
  S --> M
  M --> P["predict_with_alpha_index:<br/>X·β_k + β₀_k"]
  M -. "partial_fit" .-> G

  classDef planNode fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
  classDef denseNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef sparseNode fill:#ecfeff,stroke:#0891b2,color:#164e63,stroke-width:2px
  classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
  classDef modelNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
  class Q planNode
  class D denseNode
  class S sparseNode
  class G,E streamNode
  class M,P modelNode

1. The problem we were solving

Lesson one of ordinary least squares is “draw the best line through the points”. Lesson two is that the best line can be wildly unstable. When two features carry almost the same information — height in centimetres and height in inches, two thermometers on the same wall — the least-squares solve has to decide how to split the credit between them, and an arbitrarily tiny change in one target value can fling the coefficients to enormous, opposite-signed values. The line still fits the training data; it has simply stopped being a sensible description of anything.

Ridge regression answers this by adding a penalty on the size of the coefficients. Instead of minimizing only the squared error, it minimizes

$$\lVert X\beta + \beta_0 - y \rVert_2^2 + \alpha \lVert \beta \rVert_2^2$$

The second term charges for every unit of coefficient magnitude. The penalty strength $\alpha$ (alpha) is the dial: $\alpha = 0$ is ordinary least squares; larger $\alpha$ invites smaller, more stable coefficients at the price of a little training error. This is the classic bias–variance trade-off arriving as one number.

Ridge inherits four hard constraints from the library’s design rules, and every one of them is a decision this chapter has to walk through:

  1. The intercept must not be penalized. Shrinking $\beta_0$ would make the fit depend on where the target’s origin happens to sit — a statistically meaningless, and damaging, penalty.
  2. Sparse input must stay sparse. A matrix with a million columns and three non-zeros per row must never be converted into a dense million-wide block.
  3. One alpha is not enough. Practitioners fit a whole grid of penalties and inspect the coefficient paths. Doing that naively means refactorizing once per alpha; ridge is worth supporting because it can share the expensive work across the whole grid.
  4. Every estimator also runs incrementally and out-of-core. partial_fit and fit_streaming must converge to exactly the same model as the dense fit, regardless of how the rows are chopped into batches.

The rest of the chapter is the story of how those four constraints turned into the code.


2. The decisions — and the roads not taken

DecisionChosenRoads not taken — and why they are traps
Unpenalized interceptTwo algebraically identical spellings: the Gram and SVD solvers center the data and recover $\beta_0 = \bar{y} - \bar{x}^{\mathsf T}\beta$; the CG solver solves the augmented system $(D^{\mathsf T}D + \alpha P)\beta = D^{\mathsf T}y$ with $D = [1 ,\Vert, X]$ and $P = \operatorname{diag}(0, 1, \ldots, 1)$.W2.1’s plain $[1 ,\Vert, X]$ augmentation — it would divide the penalty into the intercept column, shrinking $\beta_0$. One spelling for all solvers — centering densifies a sparse matrix, so it is only usable by the solvers that form the dense $p \times p$ Gram anyway; the augmented form is the sparse-friendly one, so both exist and are cross-tested.
Dense exact pathCholesky on the centered normal equations $(\hat{C} + \alpha I)\beta = \hat{c}$, one solve per alpha.Normal equations on the raw design is the W2.1 trap ($\kappa(A^{\mathsf T}A) = \kappa(A)^2$). Ridge accepts the squared condition deliberately — the design is centered first, and the users who care about conditioning have the SVD solver (below). What ridge refuses is densifying sparse input to get there.
Robust dense pathSVD: one decomposition of the centered design, then $\beta = V \operatorname{diag}(\sigma/(\sigma^2+\alpha)) U^{\mathsf T}\tilde{y}$ per alpha. The decomposition is amortized across the whole grid.SVD per alpha — recomputing the factorization for every penalty wastes the one thing that makes a grid cheap. QR — stable but does not report rank for free, and rank deficiency with $\alpha = 0$ is exactly the case SVD exists for.
Sparse pathConjugate gradient over a zero-copy operator on the borrowed CSR view: $D^{\mathsf T}D \cdot v$ is applied in place, so $X^{\mathsf T}X$ is never formed and the design is never densified.Densify then solve — defeats the entire point of accepting sparse input. Preconditioned (Jacobi) CG — plain CG first, per the “iterative evolution, no skipped steps” rule; Jacobi is a recorded follow-up. Per-batch CG for streaming — the operator would have to be rebuilt cumulatively and the result would depend on batch boundaries.
Solver resolutionAutomatic resolves by representation: dense → Cholesky, sparse → SparseCg. Cholesky falls back to Svd when every alpha is zero or the factor fails.Hiding the solver choice — silently swapping a factorization for an iterative solve changes cost and accuracy characteristics a consumer should be able to see, so the fitted model exposes the solver actually used.
Multi-alpha modelOne coefficient row and one intercept per alpha, in configuration order; coefficients() is $n_{\text{alphas}} \times n_{\text{features}}$.One estimator per alpha — it would refactorize for every penalty and make the natural “inspect the path” workflow clunky; a grid is the unit ridge reasons in.
Predictionpredict is defined only for a single alpha; a multi-alpha model returns a structured error and directs the consumer to predict_with_alpha_index.Guessing an alpha — the coefficient vector is ambiguous once several were configured, and silently picking one is a correctness bug; this mirrors scikit-learn, which raises on a multi-alpha Ridge.
Extra regimesOne SKCenteredGramState (running $X^{\mathsf T}X$, $X^{\mathsf T}y$, $\sum x$, $\sum y$, row count) drives both partial_fit and fit_streaming, then one solve_from_gram at the end.Reusing W2.1’s SKGramState — OLS augments with the intercept column while ridge centers; the two are different formulations of Decision 1, so sharing one type would force one estimator into the other’s spelling.

3. The concepts, taught from zero

3.1 What regularization does, in one picture

Think of the two thermometers again. Least squares asks: “split the credit between the two columns however fits best”. Since the columns are nearly identical, many splits fit almost equally well, and the algorithm returns whichever one rounding noise happens to favour — typically two large coefficients of opposite sign that cancel on the training data. On new data they stop cancelling and the prediction explodes.

Ridge changes the question to: “split the credit however fits best, but prefer small coefficients”. The $\alpha \lVert \beta \rVert_2^2$ term makes large coefficients cost something, so among the many near-perfect splits the solver picks the one with the smallest magnitude. The condition number that was a cliff becomes a gentle slope, and the coefficients stop swinging.

Setting the gradient of $\lVert X\beta + \beta_0 - y \rVert_2^2 + \alpha \lVert \beta \rVert_2^2$ to zero gives ridge’s normal equations:

$$(X^{\mathsf T}X + \alpha I)\beta = X^{\mathsf T}y$$

Everything else in this chapter is about computing that $\beta$, and its friends across a whole grid of $\alpha$, safely and cheaply.

3.2 Why the intercept must be left out of the penalty

The penalty charges for coefficient magnitude. If we penalized $\beta_0$ too, then a target that happens to average 1000 instead of 0 would need a huge $\beta_0$, and ridge would dutifully shrink it toward zero — dragging the whole line down. The answer would depend on the units and origin of the target, which is statistically absurd: predicting a temperature in Celsius versus Kelvin would give different slopes.

The fix is mechanical. Centering: subtract each feature’s mean $\bar{x}$ and the target’s mean $\bar{y}$; solve the penalized problem on the zero-mean data (where no intercept is needed, and where $X^{\mathsf T}X$ and $X^{\mathsf T}y$ become their centered versions $\hat{C} = X^{\mathsf T}X - n\bar{x}\bar{x}^{\mathsf T}$ and $\hat{c} = X^{\mathsf T}y - n\bar{x}\bar{y}$); finally recover $\beta_0 = \bar{y} - \bar{x}^{\mathsf T}\beta$. The intercept is computed after the penalized step, so the penalty never touches it.

The CG path writes the same estimator a second way, as one augmented system: stack a column of ones onto the design ($D = [1 ,\Vert, X]$) but give the penalty a diagonal $P$ whose first entry is $0$ and the rest $1$. Then $(D^{\mathsf T}D + \alpha P)\beta = D^{\mathsf T}y$ penalizes every coefficient except the intercept. Centering and the unpenalized augmentation are the same estimator in different clothes; the tests in §5 pin that they agree, so they cannot quietly drift apart.

3.3 A solver portfolio, and what “resolution” means

Ridge offers four settings: Automatic, Cholesky, Svd, SparseCg. Automatic is a small rule, not a separate algorithm: dense input → Cholesky, sparse input → SparseCg. An explicit choice is honored verbatim, with two guard rails: Cholesky silently falls back to Svd when every alpha is zero (no penalty means the centered Gram can be singular) or when the factorization fails; and Svd rejects sparse input with a structured error pointing at Cholesky/SparseCg.

The rule that matters is that the model always reports which solver actually ran. “Which solver ran” is observable behaviour — cost and accuracy depend on it — so the model exposes it rather than hiding it.

3.4 The centered Gram — the state that combines

The only incident of $X^{\mathsf T}X$ in ridge’s dense and streaming paths is the centered Gram state:

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/ridge/gram.rs
pub(crate) struct SKCenteredGramState<F> {
    pub(super) features_count: usize,
    pub(super) gram: Array2<F>,        // XᵀX
    pub(super) cross: Array1<F>,       // Xᵀy
    pub(super) column_sums: Array1<F>, // Σx
    pub(super) target_sum: F,          // Σy
    pub(super) row_count: u64,
}
}

Every quantity ridge needs is a pure function of these sums. centered() derives Ĉ and ĉ without an index loop:

#![allow(unused)]
fn main() {
centered_gram[(i, j)] = gram[(i, j)] - row_count * feature_means[i] * feature_means[j];
centered_cross[i]     = cross[i]      - column_sums[i] * target_mean;
}

Because the coefficients depend only on the sums, batch order and size cannot change the result. That single fact is why partial_fit (incremental, dense or sparse) and fit_streaming (out-of-core) agree with the dense fit by construction, not by luck.

3.5 The zero-copy operator and conjugate gradient

For sparse input, forming $X^{\mathsf T}X$ means turning a sparse matrix into a dense $p \times p$ block. When p is a million, that is precisely the memory blow-up we are trying to avoid. So ridge never forms it. Instead, the CG solver only ever needs to apply $D^{\mathsf T}D$ to a vector, and that can be done by walking the sparse structure twice: a forward $D v$ and a backward $D^{\mathsf T} w$.

That is exactly what the SKLinearOperator trait abstracts:

#![allow(unused)]
fn main() {
// crates/sciencekit_math/src/solvers/linear_operator.rs
pub trait SKLinearOperator<F: SKFloat>: Send + Sync {
    fn dimension(&self) -> usize;
    fn apply_into(&self, input: ArrayView1<F>, output: ArrayViewMut1<F>);
    fn apply(&self, input: ArrayView1<F>) -> Array1<F> { /* allocating convenience */ }
}
}

The operator holds its matrix by reference and writes the product into a caller-provided buffer — no ownership transfer, no copy. SKCsrNormalEquationOperator is the sparse instance: apply_into computes A v from the CSR rows, then scatters each stored entry into $A^{\mathsf T} w$, yielding $A^{\mathsf T}A \cdot v$ while $A^{\mathsf T}A$ itself is never materialized.

Conjugate gradient is the iterative method that drives this. Starting from a zero guess, it walks a sequence of search directions chosen so that each step is optimal along its direction and the directions stay mutually independent; for a symmetric positive-definite system of dimension p it reaches the exact solution in at most p steps in exact arithmetic, and usually far fewer. Its loop is a sequential recurrence — the parallel work is inside the operator’s application. Crucially, the solve is honest about failure: if the iteration budget is exhausted before the residual norm falls to tolerance, it returns SKError::NotConverged { iterations } — it never hands back a stale vector pretending to have converged.

Ridge wraps both into one augmented operator, SKRidgeSparseNormalEquationOperator, which adds the $\alpha P$ diagonal and the intercept’s constant column to the borrowed SKCsrNormalEquationOperator without ever densifying anything.

3.6 Multi-alpha amortization

Why does ridge bother storing a whole grid? Because the expensive part — factorizing the system — can be shared. The SVD solver decomposes the centered design once and then each alpha is a cheap elementwise rescale:

$$\beta(\alpha) = V \operatorname{diag}!\left(\frac{\sigma_i}{\sigma_i^2 + \alpha}\right) U^{\mathsf T}\tilde{y}$$

Only the $\sigma_i / (\sigma_i^2 + \alpha)$ factor changes between penalties. Fit a 100-value grid and you pay for one decomposition, not a hundred. The Cholesky path cannot amortize across alpha (each penalty changes the matrix, so each needs its own triangular solve), but its solves are cheap, and the model shape is identical either way.


4. Each object, explained

SKRidge<F> — the estimator

Builder-only configuration, and — unlike the scalar-free SKLinearRegression — generic over F because its configuration carries scalars (alpha, tolerance):

#![allow(unused)]
fn main() {
// crates/sciencekit_linear_model/src/ridge/core_implementation.rs
pub struct SKRidge<F> {
    pub(super) plan: SKBuilderState,
    pub(super) alphas: Vec<F>,
    pub(super) include_intercept: bool,
    pub(super) solver: SKRidgeSolver,
    pub(super) tolerance: F,
    pub(super) maximum_number_of_iterations: usize,
    pub(super) backend: SKBackendKind,
}
}

The learned state lives only on the distinct SKRidgeModel, so “not yet fitted” is unrepresentable and predict cannot be called before fit (the estimator has no predict). fit is the SKSupervisedFit implementation; it resolves the plan against the data, opens the Fit span with the configured backend, and routes to the dense or sparse path.

SKRidgeBuilder<F> — the only construction surface

SKRidge::build() returns this. Defaults: alpha = 1.0, intercept included, Automatic solver, tolerance = 1e-6, maximum_number_of_iterations = 1000, SKBackendKind::Faer, Automatic execution intent. Its alpha setter is generic over SKIntoRidgeAlphas, so alpha(1.0), alpha(vec![..]), alpha(array![..]), alpha(&[..]) and alpha([..]) all work. build() validates the hyperparameters — the alpha sequence must be non-empty and non-negative, tolerance positive, iteration budget at least 1 — each rejection a structured SKError::InvalidHyperparameter naming the offending field.

SKRidgeSolver — the portfolio

#![allow(unused)]
fn main() {
pub enum SKRidgeSolver { Automatic, Cholesky, Svd, SparseCg }
}

A plain enum (not a type parameter), because the selection is a runtime value the estimator carries, not a compile-time choice. This is also why the solver can be resolved — Automatic picks per representation, and Cholesky can fall back — with the resolved value recorded on the model.

SKRidgeModel<F> — the fitted model and export boundary

#![allow(unused)]
fn main() {
pub struct SKRidgeModel<F> {
    pub(super) alphas: Vec<F>,
    pub(super) coefficients: Array2<F>, // n_alphas × n_features
    pub(super) intercepts: Array1<F>,   // one per alpha
    pub(super) include_intercept: bool,
    pub(super) solver: SKRidgeSolver,   // the solver actually used
    pub(super) rank: usize,
    pub(super) singular_values: Vec<F>,
    pub(super) backend: SKBackendKind,
    pub(super) execution_intent: SKExecutionMode,
    pub(super) gram: SKCenteredGramState<F>,
}
}

Accessors: alphas(), coefficients(), intercepts(), solver(), include_intercept(), backend(), rank(), singular_values(), feature_count(), row_count(), coefficient_for(index), intercept_for(index). It is Send + Sync by construction, so one model serves concurrent predictions. Prediction goes through SKRegressorPredictor<F> (single-alpha) or predict_with_alpha_index (explicit), and both accept dense and sparse features — a sparse prediction multiplies the CSR view by the chosen coefficient column without densifying the design.

SKLinearOperator, sk_conjugate_gradient, SKCsrNormalEquationOperator — the substrate

These three live in sciencekit_math under their own iterative-linear-solvers capability, not inside ridge, because they are general symmetric-positive-definite machinery: SKTruncatedSVD, PCA and the next regularized models all consume them.

  • SKLinearOperator<F> — the zero-copy operator abstraction (§3.5).
  • sk_conjugate_gradient — the SPD solve; returns the solution once the residual norm is at or below tolerance, else SKError::NotConverged { iterations }.
  • SKCsrNormalEquationOperator<'a, F> — the zero-copy $A^{\mathsf T}A$ operator over a borrowed CSR view.

Ridge’s SKRidgeSparseNormalEquationOperator composes the last of these, adding $\alpha$ and the unpenalized intercept, and is the thing SparseCg actually drives.


5. Walk-through of the real tests

The executable source of truth is crates/sciencekit_linear_model/src/ridge/*_tests.rs (and crates/sciencekit_math/src/solvers/*_tests.rs for the substrate). The hand-checkable fixture is a single feature with $y = 2x$: $X = [[1],[2],[3]]$, so $\sum xy = 28$, $\sum x^2 = 14$, and with $\alpha = 2$ and no intercept the closed-form slope is $28 / 16 = 1.75$.

Dense fit and multi-alpha shape — ridge_tests.rs

  • Hand-checkable closed form (hand_checkable_ridge_solution_without_intercept): fits the $y = 2x$ fixture with $\alpha = 2$, no intercept, and asserts the coefficient is exactly $1.75$ and the intercept is $0$. This is ridge’s definition pinned against arithmetic a human can verify.
  • Scalar vs sequence (scalar_alpha_yields_one_solution, alpha_sequence_yields_one_solution_per_value): a scalar yields one coefficient row and one intercept; [0.0, 1.0, 4.0] yields three, in the configured order, and — a fact worth seeing — the slope shrinks monotonically as the penalty grows.
  • The intercept is not penalized (intercept_is_not_penalized): on a design whose feature has zero mean and whose best line has intercept $5$, growing $\alpha$ from $10^{-9}$ to $10$ shrinks the slope’s magnitude while the intercept stays at $5$. This is §3.2 as an assertion.
  • Intercept can be turned off (intercept_can_be_disabled) and prediction on new rows (predicts_fitted_line) evaluates the learned line.
  • Ambiguity is refused (plain_predict_refuses_multiple_alphas): a two-alpha model’s predict returns InvalidHyperparameter { name: "alpha", .. }; predict_with_alpha_index_selects_a_row shows the explicit path yielding different responses for the exact ($\alpha = 0$) and shrunk ($\alpha = 10$) rows.
  • Resolution and carry-through (default_solver_resolves_to_cholesky, non_default_backend_reaches_model, fits_both_supported_floats, default_configuration, model_is_send_and_sync): Automatic lands on Cholesky for dense input, a non-default backend reaches the model, both f32 and f64 fit, and the defaults are the documented ones.

Solver agreement and resolution — solver_tests.rs

  • Cholesky matches the closed form (cholesky_matches_the_closed_form): on a two-feature design with no intercept, the Cholesky path reproduces the explicit $(X^{\mathsf T}X + \alpha I)^{-1}X^{\mathsf T}y$ computation.
  • SVD agrees with Cholesky (svd_agrees_with_cholesky): the two exact dense solvers return the same coefficients and intercept on a well-conditioned design — the cross-solver pin of §3.3.
  • Rank deficiency is a feature (rank_deficient_svd_reports_reduced_rank): a design whose second column is twice the first, with $\alpha = 0$, still fits; the reported rank drops below the feature count and the singular values are surfaced.
  • The fallback is real (automatic_falls_back_to_svd_for_zero_penalty): under Automatic, a rank-deficient design with $\alpha = 0$ records Svd — because zero penalty leaves the centered Gram singular. cholesky_surfaces_no_singular_values shows the Cholesky path reporting full rank and no singular values.

The sparse path — sparse_tests.rs, sparse_prediction_tests.rs

  • CG matches dense Cholesky (sparse_cg_matches_dense_cholesky): the same design as a CSR matrix fitted with SparseCg agrees with the dense Cholesky reference within a documented relative tolerance. This is the bridge between the two spellings of the intercept.
  • Representation dispatch (sparse_automatic_resolves_to_sparse_cg, sparse_cholesky_accepts_sparse_input): Automatic picks SparseCg for sparse input, while an explicit Cholesky builds the sparse Gram and solves it — both routes stay sparse.
  • SVD refuses sparse (sparse_svd_is_rejected, svd_rejects_sparse_input): a structured UnsupportedRepresentation { representation: "csr", .. } pointing at Cholesky/SparseCg.
  • Non-convergence is structured (sparse_zero_iteration_budget_fails_to_converge): a zero iteration budget returns SKError::NotConverged { iterations: 0 } — never a silent answer.
  • Sparse prediction stays sparse (sparse_prediction_matches_dense): predicting from the CSR view equals predicting from the dense matrix.

Incremental and streaming — partial_fit_tests.rs, streaming_tests.rs

  • Split equals whole (incremental_after_a_dense_fit_matches_the_dense_fit, single_row_accumulation_matches_the_dense_fit): fitting [0..2] then partial_fit-ing [2..] — even one row at a time — converges to the concatenated fit, and row_count() counts every row.
  • Batch hygiene (empty_batch_is_a_noop, partial_fit_rejects_a_column_mismatch, partial_fit_chains_several_batches): an empty batch changes nothing, a wrong column count is a ShapeMismatch, and partial_fit returns the model so calls chain.
  • Sparse batches mix with dense (sparse_batches_accumulate_like_dense_batches): sparse batches accumulate into the same centered Gram.
  • Streaming equals dense (uneven_batches_match_the_dense_fit, single_batch_matches_the_dense_fit, multi_alpha_streaming_matches_the_dense_fit, streaming_matches_the_dense_fit_on_large_data): uneven chunks, a single batch, a three-value alpha grid and a large dataset all agree with the dense fit within tolerance — because they share one Gram state.
  • Branch behaviour (in_memory_intent_collects_and_matches_the_dense_fit, sparse_cg_intent_falls_back_to_the_gram_solve): an in-memory intent collects batches and reuses the dense path; a SparseCg intent met while streaming falls back to the Gram solve and records Cholesky, since a single-pass source cannot drive a per-batch operator.

Structured errors — error_tests.rs

rejects_empty_design, rejects_target_length_mismatch, rejects_negative_alpha, rejects_empty_alpha_sequence, rejects_zero_tolerance, rejects_zero_iteration_budget and rejects_prediction_shape_mismatch each raise the right central SKError before any element is processed.

The substrate — sciencekit_math/src/solvers/*_tests.rs

  • dense_operator_reports_dimension_and_writes_product pins that apply_into writes the product and leaves both the input and the operator’s borrowed data untouched.
  • conjugate_gradient_solves_hand_checkable_system solves [[4,1],[1,3]]x = [1,2] (exact solution [1/11, 7/11]); conjugate_gradient_drives_the_residual_below_tolerance checks the stopping rule directly; zero_iteration_budget_fails_immediately and unreachable_tolerance_reports_the_budget pin the honest-failure contract.
  • normal_equation_operator_matches_explicit_gram_product applies the operator and compares it to an explicitly formed $A^{\mathsf T}A \cdot v$, while normal_equation_operator_borrows_the_view_in_place asserts repeated applications are identical and the source matrix is untouched.

6. Look inside

The whole change collapses to one picture: a single estimator definition, four ways to reach it, and one invariant — every route must produce the same coefficients.

flowchart LR
  accTitle: Four regimes of ridge and the numerical core they share
  accDescr: Dense Cholesky and SVD share the centered Gram. Sparse CG borrows the CSR view and never forms the Gram. Incremental partial_fit and streaming accumulate the same centered Gram state. All four produce one model with a solution per alpha.
  subgraph Core["The centered Gram — one source of truth"]
    CG["Ĉ = XᵀX − n·x̄x̄ᵀ<br/>ĉ = Xᵀy − n·x̄·ȳ"]
  end
  DC["dense · Cholesky<br/>(Ĉ + αI)β = ĉ"] --> CG
  DS["dense · Svd<br/>V diag(σ/(σ²+α)) Uᵀ ỹ"] --> CG
  SP["sparse · SparseCg<br/>DᵀD·v in place"] -. "never forms Ĉ" .-> CG
  INC["partial_fit<br/>accumulate + re-solve"] --> CG
  STR["fit_streaming<br/>accumulate + solve once"] --> CG
  CG --> M["SKRidgeModel<br/>one β and β₀ per alpha"]
  M --> PR["predict_with_alpha_index"]

  classDef coreNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
  classDef denseNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef sparseNode fill:#ecfeff,stroke:#0891b2,color:#164e63,stroke-width:2px
  classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
  classDef modelNode fill:#fef2f2,stroke:#e11d48,color:#881337,stroke-width:2px
  class CG coreNode
  class DC,DS denseNode
  class SP sparseNode
  class INC,STR streamNode
  class M,PR modelNode

The strong insight: regularization does not add a second estimator — it adds one diagonal to a system you already know how to solve, and the library’s job is to expose that one system through every input shape and every execution regime, without ever lying about which solver ran or about how far an iterative solve actually got.


7. Recap

  • SKRidge<F> is a builder-only, generic estimator (its configuration carries scalars) with a distinct, Send + Sync fitted model that is the export boundary.
  • The intercept is never penalized: the Gram and SVD solvers center and recover $\beta_0 = \bar{y} - \bar{x}^{\mathsf T}\beta$; the CG solver uses the algebraically identical unpenalized augmentation — and a cross-solver test keeps the two spellings from drifting.
  • The solver portfolio is Automatic, Cholesky, Svd, SparseCg; Automatic resolves by representation, Cholesky falls back to Svd on a zero penalty or a failed factor, and the model always reports the solver actually used.
  • Sparse stays sparse: conjugate gradient drives a zero-copy operator over the borrowed CSR view, so $X^{\mathsf T}X$ is never formed and the design is never densified.
  • One solution per alpha, with the SVD decomposition amortized across the whole grid; the ambiguous multi-alpha predict is refused in favour of predict_with_alpha_index.
  • One centered Gram accumulator drives partial_fit and fit_streaming, so incremental, streaming and dense fits agree by construction.
  • The iterative substrate — SKLinearOperator, sk_conjugate_gradient, SKCsrNormalEquationOperator — lives in sciencekit_math and is reused by later sparse and decomposition algorithms.

Next: the family where the penalty becomes a selection — SKLasso’s L1 norm drives coefficients to exactly zero, turning a regressor into a feature selector, and the follow-up changes ridge’s Jacobi preconditioning and its RidgeCV grid search.

L1-regularized linear models: SKLasso and SKElasticNet

The ridge chapter ended with the family “where the penalty becomes a selection”. This is that family. SKLasso and SKElasticNet are the third pair of Wave 2 algorithms, and they are the first whose penalty is not a smooth function. Ridge’s penalty is an L2 ball, differentiable everywhere, so its normal equations are one linear solve. The L1 penalty $\lVert\beta\rVert_1$ has a kink at the origin, and that kink is exactly what makes a coefficient become exactly zero — the regressor turns into a feature selector.

No closed form survives the kink. Ridge could be solved by a factorization; Lasso cannot. It needs a solver that respects the non-differentiability, and the field settled on coordinate descent — Friedman, Hastie and Tibshirani’s glmnet (2010), the reference algorithm this change follows, building on Tibshirani’s original Lasso (1996) and Zou and Hastie’s ElasticNet (2005). Two more constraints come along with it: a sparse design must stay sparse through the solve, and the incremental and streaming regimes cannot reuse ridge’s Gram accumulator, because the L1 objective is not a function of $X^\top X$ alone.

flowchart TB
  accTitle: One coordinate-descent substrate serving two L1-regularized estimators
  accDescr: SKLasso and SKElasticNet share one coordinate-descent solver. Dense and sparse designs run the same coordinate loop; a sparse design never densifies. Screening drops provably-zero coordinates and a KKT reactivation pass makes the screened answer identical to the unscreened one. Incremental and streaming fits retain the design and re-solve. Each fit yields one solution per alpha.
  L["SKLasso<br/>rho = 1"] --> CD["SKCoordinateDescentConfig<br/>soft-threshold coordinate loop"]
  E["SKElasticNet<br/>rho = l1_ratio"] --> CD
  CD --> DN["dense: ArrayView2 columns"]
  CD --> SP["sparse: borrowed CsMatView<br/>never densified"]
  DN --> SOLVE["solve per alpha (rayon)"]
  SP --> SOLVE
  SOLVE --> SCR["gap-safe screening + KKT reactivation<br/>screened ≡ unscreened"]
  SCR --> M["SKLassoModel / SKElasticNetModel<br/>coefficients n_alphas x n_features"]
  M --> PR["predict_with_alpha_index"]
  M -. "partial_fit / fit_streaming" .-> STATE["retained design accumulator<br/>re-solve at read time"]
  STATE --> SOLVE

  classDef estNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef coreNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
  classDef repNode fill:#ecfeff,stroke:#0891b2,color:#164e63,stroke-width:2px
  classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
  classDef modelNode fill:#fef2f2,stroke:#e11d48,color:#881337,stroke-width:2px
  class L,E estNode
  class CD,SCR coreNode
  class DN,SP,SOLVE repNode
  class STATE streamNode
  class M,PR modelNode

1. The problem we were solving

Suppose we hand a regression problem a hundred features, of which three actually matter. Ridge will not say so: it will keep every coefficient a little bit alive, because shrinking a coefficient to zero and keeping it tiny cost almost the same under a smooth penalty. We want a model that refuses the irrelevant features. That is what the L1 norm buys.

The objective for ElasticNet is

$$\min_{\beta,\ \beta_0}\ \frac{1}{2n}\lVert y - X\beta - \beta_0\mathbf{1}\rVert_2^2 ;+; \alpha\rho\lVert\beta\rVert_1 ;+; \frac{\alpha(1-\rho)}{2}\lVert\beta\rVert_2^2,$$

and Lasso is the special case $\rho = 1$. The three constants are the dials the estimators expose: $\alpha$ (alpha) sets the overall penalty strength, and $\rho$ (l1_ratio) mixes the two penalties. At $\rho = 1$ the model is a pure feature selector; at $\rho = 0$ it is ridge; in between it is ElasticNet, which keeps the selection behaviour while adding the L2 term’s stability when features are correlated.

Three constraints shape the whole implementation:

  1. The kink forbids a closed form. The subgradient at $\beta_j = 0$ is a set, not a number, so we cannot invert a matrix. We need an iteration that reduces to a soft-threshold at each coordinate.
  2. Sparse stays sparse. A text-classification design with a million columns and a handful of non-zeros per row must never be densified — not to center it, not to form $X^\top X$.
  3. The Gram is not enough. Ridge’s partial_fit and fit_streaming accumulated $X^\top X$ and $X^\top y$ and solved once. The L1 objective cannot be reconstructed from those sums, so those two regimes must keep the design and re-solve. That is a real memory cost, and the chapter is honest about it.

The rest of the chapter is how those constraints became code.


2. The decisions — and the roads not taken

DecisionChosenRoads not taken — and why they are traps
One body, two namesA shared coordinate_descent substrate; SKLasso and SKElasticNet are thin builder-configured estimators over it, with distinct fitted models.One public estimator with an l1_ratio — scikit-learn ships two names for two statistically distinct models, and the wave plan names both. Duplicating the solver — Lasso is the l1_ratio = 1 case of the same objective, so two solvers would drift.
The solverCoordinate descent: sweep the coordinates and update each by a soft-threshold of the partial residual, $w_j \leftarrow S(x_j^{\mathsf T}r/n + a_j w_j, \alpha\rho) / (a_j + \alpha(1-\rho))$.Proximal gradient / FISTA — plain coordinate descent first, per the “iterative evolution, no skipped steps” rule. A second-order QP solver — heavier and not the field’s reference for Lasso.
ConvergenceThe maximum coordinate change across a sweep, against tolerance, bounded by maximum_number_of_iterations; exhaustion raises SKError::NotConverged { iterations }.A fixed iteration count — silent truncation dressed up as a solution. A residual norm alone — it does not measure the coordinate-wise step that actually drives L1.
The interceptAn unpenalized coordinate: every sweep, $\beta_0 \leftarrow \beta_0 + \operatorname{mean}(r)$ and the residual is recentered — algebraically identical to centering the design, but it never densifies a sparse column.Center-then-solve — centering $x_j - \bar{x}_j$ is dense even for a sparse column, exactly the ridge trap applied to L1. Penalizing the intercept — makes the fit depend on the target’s origin.
ScreeningA strong initial active set, a gap-safe safe-screening test derived from the primal–dual gap, and a KKT reactivation pass that adds back any violating coordinate. The final answer equals the unscreened solve by construction.Screening without reactivation — a heuristic that can silently return a suboptimal answer. No screening — leaves the sparse-solution win on the table.
Sparse pathDense and sparse share one coordinate loop through a column-access abstraction; a sparse design’s column entries are gathered as (row, value) lists and the design is never densified.A separate sparse solver — doubles the iteration, the screening and the convergence logic, and lets them drift. Densify then solve — defeats accepting sparse input.
Incremental / streamingA shared retained-design accumulator: dense batches appended, sparse batches stacked, re-solved at read time; independent of batch order and size.Reusing ridge’s Gram accumulator — the L1 objective is not a function of $X^\top X$. Per-batch online coordinate descent — the result would depend on batch boundaries, breaking “incremental ≡ dense”.
ParallelismRayon across the independent per-alpha solves; the result is independent of the thread count.Parallel coordinate updates inside one solve — the residual is shared mutable state; not this change. Multi-output target matrices — scikit-learn ships MultiTaskLasso/MultiTaskElasticNet as separate estimators; deferred.
Predictionpredict is defined only for a single alpha; a multi-alpha model returns a structured error and directs the consumer to predict_with_alpha_index.Guessing an alpha — the coefficient vector is ambiguous; silently picking one is a correctness bug.

3. The concepts, taught from zero

3.1 The soft-threshold — a penalty turned into a decision

Minimize, over a single coordinate $w_j$ with everything else fixed,

$$\frac{1}{2n}\lVert r_+ - x_j w_j\rVert_2^2 ;+; \lambda\lvert w_j\rvert,$$

where $r_+$ is the residual including coordinate $j$’s current contribution. Setting the (sub)gradient to zero gives the closed-form minimizer

$$w_j = \frac{S(x_j^\top r_+ / n,\ \lambda)}{\lVert x_j\rVert_2^2 / n},\qquad S(z, \lambda) = \operatorname{sign}(z),\max(\lvert z\rvert - \lambda, 0).$$

$S$ is the soft-threshold: it shifts the correlation toward zero by $\lambda$ and clamps anything inside the band to exactly zero. This is the entire source of Lasso’s sparsity — a feature whose partial correlation is weaker than the penalty is not shrunk, it is removed. The ElasticNet variant simply adds the L2 denominator: the update becomes $S(\cdot,\alpha\rho) / (a_j + \alpha(1-\rho))$ with $a_j = \lVert x_j\rVert_2^2/n$.

3.2 Coordinate descent, and why it converges

If we cannot solve all coordinates at once, we solve them one at a time: fix every $w_k$ for $k \ne j$, solve exactly for $w_j$ with the soft-threshold, update the residual by $r \mathrel{-}= x_j,\Delta w_j$, and move on. A sweep visits every coordinate once. Because the objective is convex and each coordinate step strictly decreases it, the iteration converges to the global optimum; the only question is how fast, and that is what tolerance, maximum_number_of_iterations and selection (cyclic or a deterministic random order) control.

Convergence is declared when the largest coordinate change over a whole sweep falls to tolerance or below. This is the criterion glmnet uses, and it measures precisely the quantity that matters: how much the coefficients are still moving.

3.3 The intercept is just another coordinate

Shrinking the intercept would make the fit depend on where the target’s origin happens to sit — statistically wrong. Turning the intercept into a coordinate makes the rule beautiful: its exact update is $\beta_0 \leftarrow \beta_0 + \operatorname{mean}(r)$, i.e. recenter the residual and push the removed mean into the intercept. After every sweep the residual has mean zero, so the feature gradients $x_j^\top r / n$ equal the centered gradients $x̃_j^\top r / n$ for free — no dense centering of the design required. This is why the sparse path can stay sparse.

This is algebraically the same estimator as “center the design, solve, recover $\beta_0 = \bar{y} - \bar{x}^\top\beta$” — the two are pinned together by the closed-form tests.

3.4 Gap-safe screening, correct by construction

Lasso’s solution is sparse: most coordinates are exactly zero at the optimum. Screening skips those coordinates so the solver never even visits them. The danger is skipping a coordinate that should be active, which would silently return a wrong answer. The change makes that impossible.

The pure-L1 problem has a firm primal–dual bound. For any dual-feasible point $z$ (satisfying $\lVert X^\top z\rVert_\infty \le \alpha$) and the dual optimum $z^{*}$, the primal–dual gap $G$ bounds the distance

$$\lVert z^{*} - z\rVert_2 ;\le; R = \sqrt{2G/n}.$$

A coordinate is then provably zero when

$$\lvert x_j^\top z\rvert + \lVert x_j\rVert_2,R ;<; \alpha,$$

because $\lvert x_j^\top z^{*}\rvert < \alpha$ contradicts complementary slackness for $\beta_j \ne 0$. The solver builds $z$ from the current residual, computes the gap, and screens. Then — and this is the safety net — after the screened active set converges it checks the full gradient on every coordinate and reactivates any violator, re-solving until none remain. Screening can only change how much work is done, never the answer; a dedicated test forces a coordinate out of the active set and asserts the reactivation recovers the exact unscreened solution.

3.5 The retained design — the price of L1

Ridge’s extra regimes carried a fixed $O(p^2)$ Gram state and solved at the end. L1 cannot: the soft-threshold needs the actual columns, not their cross-products. So partial_fit and fit_streaming accumulate the design — dense rows appended, or CSR batches stacked — plus the targets, and re-solve the whole thing at read time. Memory grows with the data; that is the documented price of an out-of-core L1 fit, and it buys an order-independent result: any chopping of the rows into batches yields the same model as one dense fit.

3.6 One solve per alpha, in parallel

Each alpha is an independent L1-regularized problem. When several are configured, the coordinate_descent::solver runs them over the rayon pool (alphas.par_iter()), so a grid of penalties costs little more than one solve on a multi-core machine. The result is deterministic: a test asserts the parallel rows equal the sequential single-alpha solves.


4. Each object, explained

SKLasso<F> and SKElasticNet<F> — the estimators

Builder-configured, immutable, and generic over F because their configuration carries scalars (alpha, tolerance, and l1_ratio). Like ridge, the learned state does not live here: the estimator is configuration, the model is the fit. SKElasticNet stores its coordinate-descent configuration as a SKCoordinateDescentConfig<F>; SKLasso fixes the mixing ratio at one.

SKLassoBuilder<F> and SKElasticNetBuilder<F> — the only construction surface

Both expose alpha (a scalar or a sequence through SKIntoAlphas), include_intercept, positive, selection, screening, tolerance, maximum_number_of_iterations, backend (default Faer) and execution_mode (default Automatic); ElasticNet adds l1_ratio (default 0.5, validated to $[0, 1]$). build validates the whole surface with sk_validate_coordinate_descent_hyperparameters and returns the central SKError, never a panic.

SKSelection — the sweep order

Cyclic visits coordinates in index order; Random visits a deterministic Fisher–Yates permutation over an xorshift stream, so the “random” order is reproducible. Both converge to the same solution, which a test pins.

SKCoordinateDescentConfig<F> — the internal objective configuration

A crate-internal struct carrying tolerance, maximum_number_of_iterations, positive, selection and screening. It is deliberately internal — the public surface is the builders — but it is the seam through which both estimators hand the solver one identical configuration.

SKCoordinateDescentModelCore<F> — the shared learned state

The single implementation behind both fitted models: the $n_{\text{alphas}} \times n_{\text{features}}$ coefficients, the per-alpha intercepts, the l1_ratio, the backend kind, the screening count, the configuration and the retained design. predict_with_alpha_index and partial_fit live here so the two public model types cannot diverge.

SKLassoModel<F> and SKElasticNetModel<F> — the fitted models

Distinct, Send + Sync public types wrapping the core, with alphas(), coefficients(), intercepts(), l1_ratio() (ElasticNet), backend(), include_intercept(), positive(), row_count(), screened_count(), per-alpha accessors, predict_with_alpha_index and the SKRegressorPredictor<F> impl. They are the export boundary a later interop change will extend.


5. Walk-through of the real tests

The executable source of truth lives beside the implementation, in the *_tests.rs modules. This section walks the ones that matter.

Closed forms — coordinate_descent/solver_tests.rs

The substrate’s tests use an orthogonal mean-zero design (a Hadamard-like matrix) whose columns have squared norm four and whose targets are $X\cdot[2,-1,0]$. Because the columns are orthogonal, the Lasso solution is exactly $w_j = S(\beta_j, \alpha)$ and the intercept is zero — hand-checkable for any penalty. orthogonal_design_matches_the_closed_form checks $[1.5, -0.5, 0]$; zero_penalty_recovers_least_squares checks that $\alpha = 0$ recovers the ordinary least-squares solution; large_penalty_zeroes_every_coefficient checks that a penalty above every gradient magnitude zeroes the whole vector. sparse_matches_dense runs the same one-feature problem through the CSR path and asserts the two agree.

Sparsity and optimality — lasso/lasso_tests.rs

irrelevant_feature_is_exactly_zero asserts that the third coefficient is 0.0 — not “small”, exactly zero, the whole point of the L1 norm. kkt_conditions_hold recomputes the gradient $x^\top r / n$ at the solution and asserts the Lasso KKT conditions: active coordinates have $\lvert g_j\rvert = \alpha$, inactive ones have $\lvert g_j\rvert \le \alpha$.

The mixing ratio — elastic_net/elastic_net_tests.rs

l1_ratio_one_reproduces_lasso fits the same data with SKLasso and with SKElasticNet at l1_ratio = 1.0 and asserts the coefficients agree; l1_ratio_zero_reproduces_the_pure_l2_closed_form checks the other end of the dial against $\beta_j/(1+\alpha)$; kkt_conditions_hold checks the ElasticNet subgradient $g_j = \alpha(1-\rho)\beta_j + \alpha\rho,\operatorname{sign}(\beta_j)$ on the active set.

Screening — coordinate_descent/screening_tests.rs

screening_matches_unscreened fits with screening on and off and asserts the solutions are identical while the screened run reports at least one excluded coordinate. kkt_reactivation_recovers_a_screened_coordinate calls the inner solver with a deliberately truncated active set (only the first of three coordinates) and asserts the reactivation pass recovers the exact unscreened answer [1.5, -0.5, 0.0]. The remaining tests check the gap-safe radius, the dual-feasible scaling, the safe-zero test and the KKT violation detector directly.

Incremental and streaming — lasso/streaming_tests.rs, elastic_net/streaming_tests.rs

uneven_batches_match_the_dense_fit streams [1, 2, 1] and [1, 2, 1]-shaped chunks and compares to one dense fit; partial_fit_split_batches_equal_the_whole accumulates two batches into a fitted model and compares; partial_fit_sparse_batch_matches_dense accumulates a CSR batch into a dense fit; empty_source_is_rejected and column_mismatch_is_rejected pin the error paths. streaming_matches_the_dense_fit_on_large_data runs the check at 12 000 rows.

Concurrency — lasso/thread_tests.rs, elastic_net/thread_tests.rs

model_serves_concurrent_predictions shares one fitted model across eight threads through an Arc and asserts every prediction equals the single-threaded result — the model is Send + Sync by construction.


6. Look inside

The whole change is one idea: a kink needs an iteration, and that iteration must give the same answer through every input shape and every regime.

flowchart LR
  accTitle: One coordinate descent, two estimators, four regimes, one answer
  accDescr: SKLasso and SKElasticNet feed one coordinate-descent loop. A dense or borrowed sparse design runs the same soft-threshold updates. Screening drops provably-zero coordinates and KKT reactivation guarantees the answer. Incremental and streaming fits retain the design and re-solve. Every route yields one model with a solution per alpha.
  L["SKLasso (rho=1)"] --> CD
  E["SKElasticNet (rho=l1_ratio)"] --> CD
  CD["soft-threshold coordinate loop<br/>w_j = S(corr, alpha*rho) / (a_j + alpha*(1-rho))"]
  CD --> D["dense columns"]
  CD --> S["borrowed CSR columns<br/>never densified"]
  D --> SOLVE["solve per alpha (rayon)"]
  S --> SOLVE
  SOLVE --> SCR["screen + reactivate<br/>screened = unscreened"]
  SCR --> M["SKLassoModel / SKElasticNetModel"]
  M --> PR["predict_with_alpha_index"]
  INC["partial_fit / fit_streaming"] --> STATE["retained design"]
  STATE --> SOLVE

  classDef estNode fill:#f0fdf4,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef coreNode fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
  classDef repNode fill:#ecfeff,stroke:#0891b2,color:#164e63,stroke-width:2px
  classDef streamNode fill:#fff7ed,stroke:#ea580c,color:#7c2d12,stroke-width:2px
  classDef modelNode fill:#fef2f2,stroke:#e11d48,color:#881337,stroke-width:2px
  class L,E estNode
  class CD,SCR coreNode
  class D,S,SOLVE repNode
  class STATE,INC streamNode
  class M,PR modelNode

The strong insight: the L1 penalty does not change the estimator’s shape — it changes the solver from a factorization to a coordinate-wise iteration, and the library’s job is to expose the same estimator through dense and sparse input, through incremental and out-of-core fits, and to never lie about how far the iteration got or about which coordinates it skipped.


7. Recap

  • SKLasso<F> and SKElasticNet<F> are builder-only, generic estimators with distinct, Send + Sync fitted models that are the export boundary.
  • One shared coordinate-descent substrate serves both: soft-threshold updates, an unpenalized residual-mean intercept, cyclic/deterministic-random sweeps and convergence on the maximum coordinate change, with a structured NotConverged on budget exhaustion.
  • The L1 penalty produces exact zeros; a test asserts a coefficient is 0.0, and the KKT conditions hold at the solution.
  • Sparse stays sparse: dense and sparse share one coordinate loop through a column-access abstraction, and the design is never densified.
  • Gap-safe screening drops provably-zero coordinates, and a KKT reactivation pass makes the screened solution equal to the unscreened one by construction.
  • The design is retained for partial_fit and fit_streaming, because the L1 objective is not a function of the Gram; the result is independent of batch order and size.
  • One solve per alpha, run in parallel over the compute pool, exposed through a model that refuses an ambiguous multi-alpha predict in favour of predict_with_alpha_index.

Next: the penalty family turns to classification. SKLogisticRegression reuses this coordinate-descent substrate for its L1 penalty, adds SAGA for the large-scale path, and extends the select-then-predict story from regression to classification.

The first classifier: SKLogisticRegression

Chapter 16 of the Development Explained book. Prerequisites: the supervised estimator shape from chapter 13, the solver portfolio from chapter 14 and the coordinate-descent substrate from chapter 15. This chapter explains the why behind the Wave 2.4 change, from zero.

1. The problem we were solving

Every linear model so far — SKLinearRegression, SKRidge, SKLasso, SKElasticNet — is a regressor: it predicts a number, and its loss is a quadratic whose minimum is a linear system. SKLogisticRegression is the library’s first classifier, and that changes three things at once.

  1. The loss is nonlinear. We predict the probability that a row belongs to a class with the logistic function; the loss is the negative log-likelihood, and its gradient is a nonlinear function of the coefficients. There is no normal-equation, SVD or Cholesky solve.
  2. The output is different. A classifier returns a label and a probability per class, not a number. In this library those live behind SKClassifierPredictor<F>: predict_labels returns canonical i64 indices, predict_probabilities returns one column per class.
  3. The model is multi-headed. With more than two classes the model carries one coefficient vector per class, not one vector overall.

scikit-learn’s LogisticRegression is the richest estimator in its linear family, so the wave plan scoped this change for full parity: every penalty, a portfolio of solvers, and both one-vs-rest and multinomial classification.

flowchart LR
  accTitle: The logistic-regression training loop
  accDescr: Features feed a linear predictor. Binary problems apply a sigmoid and multinomial problems apply a softmax to obtain probabilities, whose argmax gives the label. Labels and the linear predictor feed the penalized logistic loss, whose gradient drives L-BFGS-B, SAGA or LIBLINEAR to update the weights, which feed the predictor again.
  X["features X"] --> Z["linear predictor<br/>z = X·w + b"]
  Z -->|binary| S["sigmoid σ(z)"]
  Z -->|multinomial| M["softmax"]
  S --> P["probabilities"]
  M --> P
  P --> L["argmax → label"]
  Y["labels y"] --> O["penalized logistic loss"]
  Z --> O
  O -->|gradient| SOLV["L-BFGS-B · SAGA · LIBLINEAR"]
  SOLV --> W["weights w, b"]
  W --> Z

2. The decisions — and the roads not taken

  • Three solvers, not one. A single gradient solver cannot handle the non-smooth L1 penalty and is slow on sparse designs. We chose L-BFGS-B (with an orthant-wise step for the L1 component) for the smooth L2/none path, SAGA — a variance-reduced incremental-gradient method — for L1/ElasticNet/none and the sparse path, and a LIBLINEAR-style coordinate-descent solver for the L1/L2 one-vs-rest path. Road not taken: adding newton-cg/newton-cholesky (dense Hessians that fight the sparse goal) and sag (a near-duplicate of SAGA without L1).
  • Both C and alpha. scikit-learn parameterizes by C = 1/alpha; our other linear models use alpha. The builder accepts both — the last setter wins, and using both emits a warning — so a reader porting scikit-learn code and a reader used to SKRidge are both at home. Road not taken: a single RegularizationStrength enum (heavier for no observable gain).
  • warm_start as an explicit source. scikit-learn stores the last solution on the estimator. Our estimators are immutable and shared across threads, so instead warm_start_from(&model) seeds the optimizer from a supplied solution; the estimator stays stateless. This is a deliberate, documented deviation.
  • auto multi-class resolution. auto picks multinomial for the smooth solvers on more than two classes and one-vs-rest for LIBLINEAR (which is one-vs-rest by construction) and for binary problems; ovr/multinomial force the strategy, and LIBLINEAR with multinomial is a structured error.

3. The concepts, taught from zero

3.1 The sigmoid and the softmax

For two classes the model computes a score $z = x \cdot w + b$ and turns it into a probability with the sigmoid $\sigma(z) = 1 / (1 + e^{-z})$, which is always between 0 and 1 and equals $0.5$ at $z = 0$. For several classes it computes one score per class and uses the softmax, which normalizes the exponentiated scores into a probability distribution that sums to one. Both are implemented to be stable in the tails (logistic/objective.rs): the sigmoid never overflows, and the softmax subtracts the row maximum before exponentiating.

3.2 The objective

The fit minimizes the penalized negative log-likelihood. With a per-sample weight $c_i$ and the regularization strength $\alpha = 1/C$:

$$F(w, b) = \frac{1}{n}\sum_i c_i \cdot \operatorname{loss}(x_i, y_i; w, b) + P(w)$$

where loss is $\log(1 + e^{-y z})$ for two classes and $-\log \operatorname{softmax}$ for several, and $P(w)$ is $(\alpha/2)\lVert w \rVert^2$ (L2), $\alpha\lVert w \rVert_1$ (L1), $\alpha \cdot (\text{l1_ratio} \cdot \lVert w \rVert_1 + (1-\text{l1_ratio})/2 \cdot \lVert w \rVert^2)$ (ElasticNet) or $0$ (none). The intercept is never penalized — shrinking it would make the fit depend on the origin of the data.

3.3 L-BFGS-B: a smarter gradient descent

Plain gradient descent crawls along the gradient. L-BFGS-B keeps a short history of recent steps and how the gradient changed, and uses that history to estimate the curvature of the loss, taking a much better step each iteration (the “two-loop recursion” in solver/lbfgs.rs). It is exact for smooth objectives, which is why it is the default for L2 and none.

3.4 SAGA: variance-reduced gradients

The L1 penalty is non-smooth at zero, so a plain gradient method stalls. SAGA looks at one sample at a time but remembers each sample’s last gradient in a table; it then uses the difference between the fresh and remembered gradient plus the running average to form a low-variance estimate of the true gradient. A soft-threshold step then turns the L1 penalty into an exact zero when a coefficient is small enough — the same “decision” as in chapter 15, which is why SAGA yields sparse solutions.

3.5 LIBLINEAR: coordinate descent

The third solver walks one coordinate at a time. For L2 it works on the dual problem (a reformulation with one variable per sample), solving each coordinate with a few Newton steps bounded inside a box; for L1 it works on the primal with a soft-threshold step. Both keep a sparse design sparse, because they only ever read one row or one column at a time.

3.6 One interface, dense and sparse

The solvers never see a matrix. They see a SKLogisticDesign trait (logistic/design.rs) with just three moves: the dot of one row with the weights, adding a scaled row into a vector, and the dot of one column with a vector. A dense design and a borrowed CSR design implement it, so a sparse design is never turned into a dense one — the only dense object kept is the $O(\text{rows} \times \text{classes})$ score matrix.

3.7 Labels become indices

A classifier must map arbitrary labels ("cat", "dog", or the integers 7, 3) to compact indices 0, 1, …. We reuse SKLabelTable and sk_canonicalize_labels: labels are recorded in first-occurrence order and the fitted model keeps the table, so predictions map back to the original labels. Continuous targets are rejected.

3.8 The retained design, again

The logistic objective, like the L1 objective, is not a function of the Gram matrix $X^{\mathsf T}X$. So the incremental (partial_fit) and out-of-core (fit_streaming) regimes cannot keep cross-products: they retain the design in a SKLogisticState and re-solve at read time. This is the same trade-off the L1 pair made, and it is documented.

4. Each object, explained

SKLogisticRegression<F> — the estimator

Immutable configuration. SKLogisticRegression::<f64>::build() returns a builder; .build() returns the estimator; fit/fit_streaming produce a model. It carries backend, execution_mode, the penalty, the solver and the multi-class choice.

SKLogisticRegressionBuilder<F> — the only construction surface

Chainable setters: penalty, l1_ratio, C, alpha, solver, multi_class, class_weight, warm_start, warm_start_from, include_intercept, tolerance, maximum_number_of_iterations, backend, execution_mode. Defaults: L2, alpha = 1.0, Lbfgs, Auto, no class weight, intercept on, tolerance = 1e-4, 100 iterations, Faer, Automatic. The direct constructor is private.

SKLogisticRegressionModel<F> — the fitted model

Holds the coefficients (heads × features), the intercepts, the class table, the backend kind and the retained design. Implements SKClassifierPredictor<F> (predict_labels, predict_probabilities), exposes decision_function, and is Send + Sync by construction. partial_fit continues learning.

SKLogisticPenalty, SKLogisticSolver, SKMultiClass, SKClassWeight<F>

The four public enums that name the configuration surface: the penalty, the solver, the multi-class strategy and the class-weighting policy (None, Balanced, Explicit).

5. Walk-through of the real tests

The tests are the executable source of truth.

The solvers — logistic/solver/solver_tests.rs

lbfgs_binary_separates_the_classes fits a separable design and checks every row lands on the right side of the decision boundary. saga_l1_drives_the_zero_column_to_exact_zero asserts an irrelevant feature is driven to exactly zero — the soft-threshold in action. saga_and_lbfgs_agree_under_l2 and liblinear_l2_matches_lbfgs_without_intercept cross-check two different algorithms on the same optimum. sparse_and_dense_agree fits the same design densely and as CSR and compares. a_tiny_budget_reports_non_convergence checks the structured NotConverged error.

The estimator — logistic_regression/logistic_regression_tests.rs

builder_defaults_are_documented pins the surface; c_and_alpha_are_reciprocal checks the C/alpha duality; binary_fit_predicts_labels_and_probabilities and multinomial_fits_three_classes check labels and that probabilities sum to one; nominal_labels_round_trip checks the class table; balanced_class_weight_fits_an_imbalanced_design, warm_start_reaches_the_same_optimum, partial_fit_equals_the_dense_fit and a_shared_model_serves_concurrent_predictions round out the acceptance criteria.

Streaming — logistic_regression/streaming_tests.rs

streaming_equals_the_dense_fit feeds the data in two batches and checks the result matches the dense fit; an_empty_source_is_rejected checks the structured error.

6. Look inside

PathWhat it holds
logistic/config.rsthe enums, the objective configuration, the validation
logistic/resolution.rsthe penalty/solver matrix and multi-class resolution
logistic/class_weight.rsthe per-sample weight expansion
logistic/objective.rssigmoid, softmax, loss and gradient primitives
logistic/design.rsthe dense/CSR design abstraction
logistic/solver/L-BFGS-B, SAGA, LIBLINEAR and the orchestration
logistic/accumulator.rsthe retained design for incremental/streaming fits
logistic_regression/the estimator, the fitted model and the streaming fit

7. Recap

  • The first classifier: a nonlinear, multi-headed loss with a label/probability surface.
  • Three solvers behind one design abstraction; dense and CSR share every path.
  • C and alpha both accepted, last setter wins; warm_start is an explicit source.
  • Targets canonicalize through SKLabelTable; the model is a distinct, backend-carrying export boundary.

Next, Wave 2 continues with SKSGDClassifier/SKSGDRegressor, which reuse the SAGA idea for a fully streaming, out-of-core pair.

Stochastic gradient: SKSGDClassifier & SKSGDRegressor

Chapter 17 of the Development Explained book. Prerequisites: the supervised estimator shape from chapter 13, the regularized solvers from chapters 14 and 15, and the classifier surface from chapter 16. This chapter explains the why behind Wave 2.5, from zero.

1. The problem we were solving

Every linear model before this one touches the whole design. SKLinearRegression and SKRidge build a Gram matrix or a decomposition; SKLasso, SKElasticNet and SKLogisticRegression keep a retained design that grows with the stream. Their fits are exact, and their memory is a function of the dataset.

SKSGDClassifier and SKSGDRegressor are the library’s first truly streaming supervised estimators: each update consumes one sample, so nothing about the cost depends on the dataset living in memory. That is the architectural point of the change — and the reason the PRD puts it in the out-of-core differentiator, not in the “another linear model” list.

flowchart LR
  accTitle: Memory profiles of exact solvers and of stochastic gradient descent
  accDescr: Three dataset paths compare memory use: the Gram matrix keeps a p-by-p matrix, the retained-design solver keeps the whole feature matrix, and stochastic gradient descent keeps only one sample at a time while updating a parameter vector of p times k numbers.
  classDef mem fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px
  classDef sgd fill:#dcfce7,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef io fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px

  D1["dataset"]:::io --> G1["Gram matrix<br/>XᵀX (p×p)"]:::mem
  D2["dataset"]:::io --> R1["retained design<br/>the whole X"]:::mem
  D3["dataset"]:::io --> S1["one sample →<br/>one update"]:::sgd
  S1 --> W["θ (p·k numbers)"]:::sgd

The second reason is mathematical. The logistic loss has no closed form; the coordinate descent family solves that with a full pass per sweep. SGD instead takes a noisy estimate of the gradient from one sample and moves. Nobody promises the last step is at the optimum — the promise is that the sequence converges, and that the cost per step is O(p).

2. The decisions — and the roads not taken

DecisionChosenRoad not taken — and why
Update granularityone sample per update, with an epoch loop around itMini-batch updates would vectorize better, but they change the convergence theory and the schedule semantics; scikit-learn’s SGD is per-sample, and parity is the goal.
Where the algebra livesa separate sgd substrate (loss/, learning_rate/, penalty.rs, shuffle.rs, averaging.rs, update.rs, epoch/)Putting it inside each estimator would duplicate the loss catalogue and the schedules — and Wave 3’s linear SVM and Wave 5’s mini-batch k-means reuse this loop.
Loss cataloguetwo public enums, one per task family, behind a sealed traitOne enum forces a runtime family check in the hot loop and lets a regressor loss reach the classifier.
L1 penaltyproximal soft-threshold after the gradient stepAdding an L1 subgradient to the step does not produce exact zeros; the soft-threshold does, which is the whole point of L1.
Averagingoptional running mean of visited iterates (ASGD)Keeping the last iterate is cheaper but noisier; storing the trajectory would defeat the memory guarantee, so the mean is updated incrementally.
Shufflinga self-contained SplitMix64 generator seeded on the builderAdding rand/rand_xoshiro would be a dependency for ~40 lines; seeding by default at 0 makes experiments reproducible (a deliberate deviation from scikit-learn’s None).
ConvergenceStrict (error) or Permissive (model + converged() == false)scikit-learn always warns and returns the model; the library’s other iterative solvers error, so Strict is the default and Permissive is the documented escape hatch.
One-shot streamingone pass, reported as epochs_taken() == 1, never a NotConvergedA source cannot rewind; a later change (streaming-source-provider) adds reopenable providers so the epoch budget applies to streams too.
Multi-classone-vs-rest headsscikit-learn’s SGD is OvR; a multinomial softmax step would need a full softmax per sample and diverge from parity.
Random generator homeinside sgd/shuffle.rsPromoting it to sciencekit_common now would freeze a shape Wave 4’s forests may not want; the module boundary makes the move mechanical later.

3. The concepts, taught from zero

3.1 The update rule

For a sample with features $x$, target $y$ and weight $c$, the model predicts the linear score $f = x^{\mathsf T}w + b$. The loss $\ell(f, y)$ measures how wrong that is, and its slope with respect to $f$ tells us which way to move:

$$\begin{aligned} g &= c \cdot \ell’(f, y) \cdot x \ w &\leftarrow w - \eta \cdot (g + \alpha \cdot (1 - \text{l1_ratio}) \cdot w) \ b &\leftarrow b - \eta \cdot g_{\text{intercept}} && \text{the intercept is never penalized} \ w &\leftarrow \operatorname{soft_threshold}(w, \eta \cdot \alpha \cdot \text{l1_ratio}) && \text{only when the L1 component is active} \end{aligned}$$

The learning rate $\eta$ decides how far each step goes. The data term is the mean loss (like scikit-learn), so alpha keeps exactly the meaning a scikit-learn user expects.

3.2 Schedules

ScheduleStep sizeIntuition
Constant$\eta_0$the simplest baseline
InverseScaling$\eta_0 / (1 + t)^p$big early steps, careful late ones
Optimal$1 / (\alpha \cdot (t + t_0))$the classical $1/t$ form, with $t_0$ estimated from the first batch’s slope scale
Adaptive$\eta$ halved on a non-improving epochreacts to a plateau without a schedule formula

The counter t is monotone across fit, fit_streaming and partial_fit: an incremental continuation does not restart the clock, which is what makes the fits agree.

3.3 Exact zeros and the soft-threshold

The L1 penalty is not differentiable at zero. Instead of pretending it is, the update takes a gradient step and then projects each coordinate:

$$\operatorname{soft_threshold}(v, \lambda) = \operatorname{sign}(v) \cdot \max(\lvert v \rvert - \lambda, 0)$$

Any coordinate whose step does not clear $\lambda$ lands exactly on zero — and stays there. This is why an L1 fit can be used as a feature selector, and why the tests assert == 0.0, not ≈ 0.0.

3.4 Averaging

With average(true) the model reports the running mean of the iterates it visited:

$$\bar{w} \leftarrow \bar{w} + \frac{w - \bar{w}}{t}$$

One vector of extra state, no trajectory stored. Averaging trades a little bias for a large variance reduction at the end of training — the ASGD trick.

3.5 Convergence, honestly

After each epoch the driver knows the average loss it observed. A fit converges when that number improves by no more than tolerance for number_of_epochs_without_improvement consecutive epochs. Otherwise, if the whole budget ran:

  • Strict → SKError::NotConverged { iterations } (the library’s convention);
  • Permissive → the iterate, with converged() == false and a warning.

And a provider-limited fit — a one-shot stream that yielded fewer passes than the budget — never raises: the model reports epochs_taken() and converged() == false. An SGD budget is a compute knob, not a feasibility test.

3.6 One-vs-rest and probabilities

With $k$ classes the classifier fits $k$ independent heads, each against the rest with $\pm 1$ targets, and predicts the arg-max of the heads’ scores (ties go to the lowest canonical index). Probabilities are available only for the two probabilistic losses:

  • log_loss → the logistic sigmoid;
  • modified_huber → the clipped affine $(f + 1) / 2$ in $[0, 1]$.

Asking for probabilities under hinge returns SKError::UnsupportedOperation { operation: "predict_probabilities", … } rather than inventing a number.

flowchart TB
  accTitle: One-vs-rest heads and the losses each supports
  accDescr: The feature matrix feeds one binary head per class. The heads combine through argmax to produce a label, and through sigmoid or modified Huber to produce probabilities when the loss is probabilistic. Hinge, squared hinge and perceptron losses are rejected with UnsupportedOperation.
  classDef cls fill:#ede9fe,stroke:#7c3aed,color:#3b0764,stroke-width:2px
  classDef prob fill:#fef9c3,stroke:#ca8a04,color:#713f12,stroke-width:2px
  classDef ref fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px

  X["X"]:::cls --> H1["head: class 0 vs rest"]:::cls
  X --> H2["head: class 1 vs rest"]:::cls
  X --> H3["head: class k−1 vs rest"]:::cls
  H1 --> A["arg-max → label"]:::prob
  H2 --> A
  H3 --> A
  H1 --> P["sigmoid / modified-huber<br/>(only probabilistic losses)"]:::prob
  H2 --> P
  H3 --> P
  P -.->|hinge · squared_hinge · perceptron| E["UnsupportedOperation"]:::ref

4. The public objects

Each estimator follows the same builder-only shape as its siblings:

ItemRole
SKSGDClassifier / SKSGDRegressorthe immutable estimator; fit, fit_streaming
SKSGDClassifierBuilder / SKSGDRegressorBuilderevery knob, with the documented defaults
SKSGDClassifierModel / SKSGDRegressorModelthe fitted model: predict, predict_labels, predict_probabilities, decision_function, partial_fit, converged(), epochs_taken()
SKSGDClassifierLoss / SKSGDRegressorLossthe loss catalogue, split by task family
SKSGDLearningRateConstant, Optimal, InverseScaling, Adaptive
SKSGDPenaltyL2, L1, ElasticNet, None
SKConvergencePolicyStrict (default) or Permissive
SKSGDClassifierCoefficients / SKSGDRegressorCoefficientsthe explicit warm-start source

The estimator never predicts; the model does. fit transfers the configured SKBackendKind into the model, and every operation records it in its span, even though the loop performs no heavy linear algebra — the selection surface is uniform across the library.

5. Walking the real tests

The executable source of truth is the companion *_tests.rs modules under crates/sciencekit_linear_model/src/sgd_classifier/ and …/sgd_regressor/.

  • The update rule, checked exactly. one_update_equals_the_closed_form_squared_error_step compares one step against the hand-computed formula; a_sparse_fit_supports_both_floats repeats the sparse path on f32 and f64.
  • The schedules. constant_rate, partial_fit_continues_the_schedule_counter and partial_fit_continues_the_average pin the counter and the running mean across calls.
  • Losses. hinge_and_perceptron_are_exact_on_a_separable_design proves the pair reaches zero training error; squared_hinge_and_modified_huber_converge covers the smooth ones; log_loss_is_calibrated_and_normalized checks the rows sum to one; a_large_epsilon_huber_matches_squared_error and the_insensitive_band_keeps_the_start pin the epsilon semantics.
  • Penalties. the_intercept_is_not_penalized, elastic_net_limits_match_the_pure_penalties and squared_error_converges_to_the_ols_solution connect the new family back to SKRidge and SKLinearRegression.
  • Representations. dense_and_csr_fits_agree_across_losses_and_penalties and sparse_prediction_matches_dense are the never-densify guarantee.
  • Streaming. one_streaming_pass_equals_one_in_memory_epoch states the honest contract; early_stopping_over_a_stream_is_refused pins the explicit refusal.
  • Order. the_same_seed_produces_the_same_order and the_seeded_order_applies_identically_to_dense_and_sparse_designs prove the seed alone decides the visiting sequence, while disabled_shuffle_follows_the_input_row_order pins the opposite contract: with shuffling off, rows are visited in input order, checked against a hand-computed coefficient trail.
  • Convergence. a_converged_fit_reports_its_epochs, permissive_single_epoch and a_seeded_refit_never_regresses_within_the_same_budget; the policy warnings are observed rather than assumed — permissive_exhaustion_emits_a_warning, a_provider_limited_fit_emits_a_warning and a_converged_fit_emits_no_warning capture the tracing events with a test subscriber.
  • Classifier surface. three_classes_produce_three_heads, ties_resolve_to_the_lowest_canonical_index, probabilities_are_refused_for_non_probabilistic_losses, balanced_improves_the_minority_class, nominal_labels_round_trip, an_unseen_class_is_rejected.

If you change the loop, these are the tests that should fail first.

6. Streaming today, epochs tomorrow

A one-shot SKSupervisedLazySource is a fallible iterator: it yields batches and ends. It cannot rewind, so fit_streaming runs exactly one epoch and says so:

sequenceDiagram
  accTitle: One epoch of stochastic gradient descent over a lazy source
  accDescr: The estimator requests supervised batches from the source and applies one update per row to the learning state. When the source returns no more batches, the epoch ends with one epoch taken and the converged flag false.
  participant E as SKSGDClassifier
  participant S as SKSupervisedLazySource
  participant W as learning state
  E->>S: next_supervised_batch()
  S-->>E: batch
  E->>W: one update per row
  E->>S: next_supervised_batch()
  S-->>E: None
  Note over E,W: epochs_taken = 1<br/>converged = false

The follow-up change streaming-source-provider introduces a provider seam that can reopen a source, so the same epoch budget will apply to streams. Nothing in the estimator’s public surface has to change for that: the model already reports epochs_taken() and converged().

7. Recap

  • SGD is the first supervised estimator whose cost per update is independent of the dataset; that is why it is a separate family, not a solver option.
  • The substrate owns the losses, schedules, penalty, averaging, shuffling and the epoch loop; the estimators own only their target semantics and prediction surface.
  • Exact zeros come from the proximal step, variance reduction from averaging, and honesty from converged()/epochs_taken() plus the convergence policy.
  • One-vs-rest, two probabilistic losses and a strict refusal everywhere else keep the classifier’s surface predictable.

Next, the book moves to Wave 3: neighbors and the kernel machines that reuse this loop.

Source providers: multi-epoch out-of-core fits

Chapter 18 of the Development Explained book. Prerequisites: the streaming executor from chapter 7 and the stochastic-gradient family from chapter 17. This chapter explains the why behind the streaming-source-provider change, from zero.

1. The problem: a stream cannot rewind

Every out-of-core fit consumed a one-shot source: a fallible iterator that yields batches and then ends. That is exactly right for an exact accumulator — a Gram matrix, a running mean, a category table — because reading the data twice would double-count it.

It is wrong for a stochastic estimator. SKSGDClassifier and SKSGDRegressor learn one sample at a time; one pass over the stream is one epoch, and one epoch of SGD usually underfits. The in-memory fit runs up to a thousand epochs; the streamed fit ran one. The PRD promised out-of-core SGD, not out-of-core one-epoch SGD.

flowchart LR
  accTitle: One-shot sources compared with reopenable providers
  accDescr: A one-shot source yields batch zero, one and two, then reaches end of file and cannot rewind, so it stops. A reopenable provider opens the source again for each pass, replaying the same batches on pass zero, one and two.
  classDef once fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px
  classDef re fill:#dcfce7,stroke:#16a34a,color:#14532d,stroke-width:2px
  classDef io fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px

  subgraph OneShot["one-shot source"]
    O0["batch 0"]:::io --> O1["batch 1"]:::io --> O2["batch 2"]:::io --> OE["EOF"]:::once
    OE -.->|"cannot rewind"| OX["stop"]:::once
  end

  subgraph Reopen["reopenable provider"]
    P0["pass 0: open() → b0 b1 b2 → EOF"]:::re
    P1["pass 1: open() → b0 b1 b2 → EOF"]:::re
    P2["pass 2: open() → b0 b1 b2 → EOF"]:::re
    P0 --> P1 --> P2
  end

2. Why not Into<Source>?

The obvious reach — accept “anything convertible into a source” — does not work in Rust:

#![allow(unused)]
fn main() {
fn fit_streaming<S>(&self, source: impl Into<S>)
where S: SKSupervisedLazySource<F>   // E0283: cannot infer S from the argument
}
  1. S appears only in the bound, so the compiler has no target for the conversion.
  2. impl<T> From<T> for T already makes every concrete source Into<itself>; a factory conversion would need a per-type impl, and the orphan rule forbids it for foreign types.
  3. A closure has an unnameable type, so nobody can implement From/Into for it.

The working seam is a dedicated trait, implemented for a reference to a concrete source and for a wrapper around a factory. No dyn, no allocation, no new dependency.

3. The provider contract

#![allow(unused)]
fn main() {
pub trait SKSupervisedSourceProvider<F> {
    type Source<'pass>: SKSupervisedLazySource<F> + Send where Self: 'pass;
    const IS_REOPENABLE: bool;
    fn open(&mut self) -> Result<Self::Source<'_>, SKError>;
}
}

The generic associated type is the key: it lets one trait return a borrow for a concrete source and an owned source for a factory, under the same signature.

ArgumentImplementationPasses
&mut sourceresidual impl for &mut S1
`SKReopenableSource::new(open_file(path))`

The residual implementation is what keeps every existing call compiling:

#![allow(unused)]
fn main() {
impl<F, S: SKSupervisedLazySource<F> + Send> SKSupervisedSourceProvider<F> for &mut S {
    type Source<'pass> = &'pass mut S where Self: 'pass;
    const IS_REOPENABLE: bool = false;
    fn open(&mut self) -> Result<Self::Source<'_>, SKError> { Ok(&mut **self) }
}
}

The reopenable wrapper stores a FnMut() -> Result<S, SKError> and calls it once per pass, so each epoch sees the same data in the same order — the property that makes a streamed fit reproducible.

classDiagram
  accTitle: The source-provider trait and its two implementations
  accDescr: SKSupervisedSourceProvider is a trait with an associated source type, a reopenable flag and an open method. ConcreteSource implements it for a mutable source used in one pass, and SKReopenableSource implements it with a factory that yields N passes.
  class SKSupervisedSourceProvider {
    <<trait>>
    +Source~pass~ Source
    +bool IS_REOPENABLE
    +open() Result
  }
  class ConcreteSource {
    +next_supervised_batch() Option
  }
  class SKReopenableSource {
    -factory FnMut
    +IS_REOPENABLE = true
  }
  SKSupervisedSourceProvider <|.. ConcreteSource : "&mut S, one pass"
  SKSupervisedSourceProvider <|.. SKReopenableSource : "factory, N passes"

4. One rule, classified by estimator

The executor does not guess. SKStreamingPassPolicy says how many passes are allowed:

ClassEstimatorsPass policy
Exact accumulatorscalers, polynomial features, simple imputer, OLS, ridge, lasso, elastic net, logistic regressionSinglePass — reading twice would double-count $n$, $\Sigma x$, $X^{\mathsf T}X$
IterativeSKSGDClassifier, SKSGDRegressor (and later mini-batch k-means, incremental PCA)Iterative { maximum_number_of_passes } — one epoch per pass

A one-shot provider with a budget above one takes one pass and emits a tracing::warn!; the model reports epochs_taken() == 1 so the clamp is observable without logs. Silently pretending the budget was honoured would be worse than the warning.

SKOneHotEncoder is the declared exception: its streaming seam consumes categorical views (IntoIterator<Item = SKCategoricalView>), not numeric blocks, so it stays outside the provider trait until an owned categorical block exists. Every numeric estimator in the library uses the seam.

5. Multi-epoch SGD, pass by pass

Each pass opens a source, runs one epoch over its batches with the same learning state, and merges the epoch objective into the convergence tracker:

sequenceDiagram
  accTitle: Epoch loop over a reopenable provider
  accDescr: For each pass in the epoch budget the estimator opens the provider, receives a source, and reads batches until exhaustion, applying one update per row. At the end of each pass it merges the epoch objective and updates the convergence tracker.
  participant E as SKSGDRegressor
  participant P as provider
  participant S as source
  participant W as learning state
  loop pass in 0..budget
    E->>P: open()
    P-->>E: source
    loop each batch
      E->>S: next_supervised_batch()
      S-->>E: batch
      E->>W: one update per row
    end
    E->>E: merge the epoch objective, update the tracker
  end
  Note over E: epochs_taken = passes<br/>converged = plateau?

The schedule counter and the averaged iterate live in the state, so they continue across passes exactly as they do across partial_fit. The convergence policy is unchanged:

  • Strict raises NotConverged only when the full requested budget executed without a plateau;
  • Permissive returns the model with converged() == false;
  • a provider-limited fit (one-shot, fewer passes than the budget) returns the model with converged() == false and never raises.

Early stopping over a stream is still refused with UnsupportedOperation: it needs a held-out validation slice the provider does not promise to retain. The refusal is explicit, not a silent no-op.

6. Walking the real tests

  • sciencekit_common/src/batching/provider/*_tests.rs: a concrete source reports itself as not reopenable and yields once; the factory is invoked once per pass; a factory error aborts; the feature-only and supervised families agree on passes and order.
  • sciencekit_common/src/execution/streaming_driver/provider_entry_points_tests.rs: a one-shot provider runs one pass despite a budget of five; a reopenable provider runs the budget.
  • Scalers, polynomial features and the imputer: a reopenable provider with a larger budget still takes one pass and the model equals the dense fit.
  • OLS, ridge, lasso, elastic net and logistic: the same one-pass rule, with the accumulator compared against the dense fit.
  • SGD: a reopenable multi-epoch stream equals the in-memory fit under a fixed seed, with the schedule counter and the average carried across passes; a one-shot provider takes one pass and does not raise; Strict raises only after the full budget.

7. Recap

  • A source provider is the seam that lets one method accept a concrete source and a factory, because Into cannot express it in Rust.
  • The GAT returns a borrow or an owned source; IS_REOPENABLE is a compile-time fact.
  • The number of passes follows the estimator class: exact accumulators take one, iterative estimators take the epoch budget from a reopenable provider.
  • The one-shot call shape survives, the clamp is reported by epochs_taken(), and the convergence policy decides what an unconverged streamed fit does.

Next: the batch contract itself becomes representation-generic, so sparse data can stream without ever being densified.

Sparse out-of-core: the owned feature block

Chapter 19 of the Development Explained book. Prerequisites: the streaming executor from chapter 7 and the source providers from chapter 18. This chapter explains the why behind the sparse-streaming-batches change, from zero.

1. The problem: sparse data had to become dense to travel

The in-memory boundary has always known two representations — SKDataView::Dense and SKDataView::Sparse — and every estimator dispatches on them once. The streaming block did not: SKDataBatch and SKSupervisedBatch owned an Array2<F> and nothing else.

So a sparse design could not enter a stream. The only way to fit it out-of-core was to densify it first — allocating rows × columns numbers to feed a pipeline whose whole point is that it never holds the dataset in memory. Text features, recommendation matrices and one-hot-encoded columns are exactly the data that is sparse and large.

2. The owned block mirrors the borrowed view

SKDataView is a borrowed enum over ArrayView2 and CsMatView. The streaming twin is an owned enum with the same two variants:

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub enum SKFeatureBlock<F> {
    Dense(Array2<F>),
    Sparse(CsMat<F>),
}
}
classDiagram
  accTitle: Borrowed data views and owned feature blocks
  accDescr: SKDataView is a borrowed enum that holds either a dense array view or a sparse CSR view. SKFeatureBlock is the owned counterpart that holds either a dense array or a CSR matrix, and its view method borrows it as a data view.
  class SKDataView {
    <<enum, borrowed>>
    Dense ArrayView2
    Sparse CsMatView
  }
  class SKFeatureBlock {
    <<enum, owned>>
    Dense Array2
    Sparse CsMat
  }
  SKFeatureBlock --> SKDataView : view() borrows

view() returns the existing borrowed enum with no copy and no conversion, so the estimator dispatch code reads identically in both regimes:

#![allow(unused)]
fn main() {
match batch.view() {
    SKDataView::Dense(dense) => fit_dense(dense),
    SKDataView::Sparse(sparse) => fit_sparse(sparse),
}
}

The enum is #[non_exhaustive]: a third representation (say, a bit-packed categorical block) can arrive later without breaking a match.

3. The batches carry the block

Both batches now own a block instead of a matrix:

BeforeAfter
SKDataBatch::data() -> ArrayView2view() -> SKDataView, number_of_rows(), number_of_columns(), is_sparse()
SKSupervisedBatch::features()the same block accessors, plus targets()
SKSupervisedBatch::new(features, targets, …)new_dense / new_sparse, both fallible

The supervised constructors return Result<Self, SKError> because they now enforce an invariant the old shape could not: the target count must equal the block’s rows. The breaking change is deliberate — the compiler catches every old call site, which is far better than a runtime densification or a silent mispairing.

Position and the final-block flag are unchanged, and the block is still fully owned, so the prefetch driver can move it to another thread exactly as before.

4. The memory guard tells the truth

The execution plan refuses a streaming batch whose double-buffered size exceeds available memory. With a dense-only pipeline the hint was rows × columns × size_of::<F>(). A sparse batch must be measured by what it actually stores:

dense:  rows · columns · size_of<F>()
sparse: data.len() · size_of<F>()
       + indices.len() · size_of::<usize>()
       + indptr.len() · size_of::<usize>()

SKFeatureBlock::byte_size implements exactly that. The plan carries available_memory_bytes, and the executor checks each batch when it is read, before it is processed: two resident batches must fit, or the read fails with BatchBufferOversize. A 10⁶ × 10⁶ matrix with one nonzero per row passes a guard that the dense figure would reject — correctly, because the block really is that small. The optional SKExecutionContext::batch_byte_size_hint remains available when a source knows the size before opening.

5. The subtle part: implicit zeros

A CSR matrix stores only the non-zeros. Every other entry is zero, and the statistics must count it:

  • Mean and moments: a column with e explicit values in n rows has n − e implicit zeros. $\Sigma x$ and $\Sigma x^2$ include nothing for them (they contribute zero), but the count is $n$, so the mean is $\Sigma x / n$, not $\Sigma x / e$.
  • Min and max: zero participates unless a column is explicitly present in every row. The accumulator therefore tracks a per-column explicit count.
  • Quantiles: the robust scaler’s sketch receives the explicit values plus one weighted zero centroid per column, with multiplicity n − e; the in-process sparse branch computes exact order statistics by treating the zeros as a virtual sorted block, then seeds the sketch.
flowchart LR
  accTitle: How a sparse row contributes to column statistics
  accDescr: A CSR row stores explicit values at columns three and seven, while every other column is an implicit zero. Explicit entries contribute to sums, sums of squares, minimum and maximum. Implicit zeros contribute to the row count, not the nonzero count, and add zero mass to the quantile sketch.
  classDef row fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e,stroke-width:2px
  classDef zero fill:#fef9c3,stroke:#ca8a04,color:#713f12,stroke-width:2px
  classDef stat fill:#dcfce7,stroke:#16a34a,color:#14532d,stroke-width:2px

  R["CSR row: [1.5 at col 3, −2.0 at col 7]"]:::row
  R --> E["explicit: col 3 = 1.5, col 7 = −2.0"]:::row
  R --> Z["implicit: every other column = 0"]:::zero
  E --> S["Σx, Σx², min, max"]:::stat
  Z --> N["count = rows (not nnz)"]:::stat
  Z --> Q["quantile sketch: zero mass n − e"]:::stat

This is the part most likely to be wrong in a naive port: a mean divided by the number of non-zeros looks plausible and is silently biased.

6. Estimators reuse what they already had

The in-memory fit already had sparse paths — Gram products over CsMatView, a retained design that stacks CSR, per-row SGD updates. The streaming change does not invent new algebra; it routes the block to the same code:

  • Scalers: per-column count, $\Sigma x$, $\Sigma x^2$ / extrema / sketch over CSR rows in O(nnz).
  • Polynomial features: expand each CSR row directly; the output is sparse and follows the documented column order.
  • Simple imputer: the marker predicate already special-cased the 0.0 marker for CSR implicit zeros; the streaming path reuses it.
  • OLS / ridge: accumulate the Gram matrix from CSR.
  • Lasso / elastic net / logistic regression: accumulate the retained design as CSR (a later dense batch is converted to CSR, never the reverse).
  • SGD: one epoch over CSR rows through the sparse row driver.

6.1 The coverage matrix: proving the set, not just the members

Per-estimator tests prove that each estimator handles CSR. They cannot prove that the set is complete — that no streaming estimator was forgotten, and that the one dense-only exception is deliberate. A second layer does that: a workspace-level matrix, one row per fit_streaming/partial_fit implementation, recording whether it offers partial_fit, dense streaming and sparse streaming, plus a note justifying the row.

flowchart LR
    accTitle: Two layers of streaming coverage
    accDescr: Each estimator's own sparse streaming suite proves it matches the dense fit. The workspace coverage matrix proves the set is complete, that the only dense-only streaming path is the documented categorical encoder, and that a deliberately dense-only path rejects CSR before reading an element.
    A["Per-estimator suite<br/>sparse stream = dense stream = dense fit"] --> C["Coverage matrix<br/>one row per streaming estimator"]
    C --> B["Completeness test<br/>fails when a row is missing"]
    C --> D["Exception test<br/>only SKOneHotEncoder is dense-only"]
    B --> E["Dense-only guard test<br/>UnsupportedRepresentation before any element"]
    classDef member fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef set fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef guard fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    class A member
    class C,B,D set
    class E guard

Three properties come out of it:

  1. Completeness. The matrix pins the count (thirteen estimators) and every name, and a source scan walks the sibling crates at test time counting fn fit_streaming and pub fn partial_fit definitions — so adding a streaming estimator without an audit row fails the suite.
  2. The exception is explicit. Exactly one row has sparse_streaming: false: SKOneHotEncoder. Its streaming input is not a numeric block at all — it is an iterator of categorical views — so numeric CSR support is meaningless there. Writing the exception down stops it from being mistaken for an oversight.
  3. The guard has a shape. A deliberately dense-only streaming estimator must match the representation once, before touching an element, and return UnsupportedRepresentation with a conversion suggestion. A local fixture in the audit module demonstrates that contract; no shipped numeric estimator is dense-only — the one-hot encoder’s seam is categorical, not numeric.

The no-densification rule is the thread running through both layers: the per-estimator suites compare a sparse stream against a dense stream and a dense fit, so a densified block would have to produce the same numbers while never being observed; the memory guard additionally bounds a batch by its stored byte size. These are strong signals, not an allocation proof: the guarded shape tests prove a stream completes where its dense twin is impractical for the test budget.

Sparse partial_fit: the gap the audit closed

Three scalers and OLS used to accept CSR only through fit_streaming; their partial_fit still called as_dense() and rejected a sparse batch. The audit made that visible, and the fix routes partial_fit through the same sparse accumulators the streaming driver uses: sparse_batch_moments (standard scaler), sparse_batch_extrema (min/max), extend_sparse_sketches (robust) and GramState::accumulate_sparse (OLS). One batch, two entry points, one code path — so an incremental sparse update learns exactly what a sparse stream would.

The audited surface

Estimatorpartial_fitNumeric streamingCSR
SKStandardScaleryesyesyes
SKMinMaxScaleryesyesyes
SKRobustScaleryesyesyes
SKPolynomialFeaturesnoyesyes
SKOneHotEncodernocategorical seamnot applicable
SKSimpleImputeryesyesyes
SKLinearRegressionyesyesyes
SKRidgeyesyesyes
SKLassoyesyesyes
SKElasticNetyesyesyes
SKLogisticRegressionyesyesyes
SKSGDClassifieryesyesyes
SKSGDRegressoryesyesyes

7. Walking the real tests

  • sciencekit_common/src/batching/feature_block/feature_block_tests.rs: construction, shape, zero-copy view (pointer identity), byte size from the stored buffers, ownership and cross-thread movement, f32.
  • The batch tests: dense and sparse construction, metadata, the target-count mismatch, a sparse block moved across threads.
  • The driver test: a sparse block reaches the update closure with its representation intact and the order preserved.
  • Per-estimator conformance: sparse stream ≡ dense stream ≡ dense fit on the concatenated data, with implicit-zero edge cases, sample_count() equality where available, and a read-time batch guard test (a sparse block fits a memory budget its dense twin would exceed). The older large-shape tests are shape sanity: they prove a stream completes at a shape whose dense twin is impractical for the test budget, not that no copy was ever made.
  • The scaler tests assert the sample count, not just the mean: a mean is invariant under duplication, so it cannot prove that the data was read once.
  • sparse_streaming_partial_fit_matches_dense (three scalers) and sparse_streaming_partial_fit_matches_the_dense_fit (OLS) prove an incremental sparse update reaches the same result as a dense fit.
  • sparse_reopenable_provider_runs_multiple_epochs proves a reopenable sparse provider feeds several epochs and the model reports them.
  • the_source_scan_matches_the_audited_streaming_surface and the_source_scan_reaches_every_streaming_crate run the completeness scan over the sibling crates.

8. Recap

  • One owned block type mirrors the borrowed view, so dispatch reads the same in both regimes.
  • The batches carry the block; the driver never converts; the memory guard measures the real buffers.
  • Implicit zeros are data: they shape every count, extremum and quantile.
  • No new algebra — the sparse paths of the in-memory fits are reused, now fed one batch at a time.

This closes the streaming story: providers let a fit take epochs, and the feature block lets those epochs be sparse.

Measuring a model: the metrics foundation

By the end of the previous chapter sciencekit could fit fourteen estimators: five preprocessors, two imputers and seven linear models. It could not answer the next question a user always asks — is the model any good? The shared scoring traits existed in sciencekit_common, but no crate implemented them. This chapter tells the story of the change that closed that gap, and of the two distances the next algorithms needed.


1. The problem we were solving

The product requirement is blunt (PRD §8.7): every implementation must run with lots of data and with little data, under concurrency, and produce metrics. Fourteen estimators had tests and benchmarks but no way to compute accuracy, error or a confusion matrix inside the library. Every downstream feature — model selection, grid search, even the neighbours and SVM waves — needs those numbers.

At the same time, the distance catalogue in sciencekit_math stopped at Euclidean, Manhattan and Cosine. The next wave needs two more:

  • Chebyshev ($L_\infty$), the “largest coordinate difference” distance used by $p = \infty$ neighbours;
  • NaN-aware Euclidean, the only distance a missing-value imputer can use, because it compares only the features observed in both rows.

The change therefore had two halves, both measurement: evaluation metrics in a new crate, and two distance kernels in the existing maths crate.

flowchart LR
    accTitle: The two halves of the metrics foundation
    accDescr: A new sciencekit_metrics crate provides evaluation; sciencekit_math gains two distance kernels. Both feed downstream algorithms.
    A[Fourteen estimators] --> B[sciencekit_metrics]
    C[pairwise distances] --> D[sciencekit_math]
    B --> E[accuracy, precision, recall, F1, MSE, R2]
    B --> F[mergeable accumulators]
    D --> G[Chebyshev]
    D --> H[NaN-aware Euclidean]
    E --> I[model selection and later waves]
    F --> I
    G --> J[neighbours with p infinity]
    H --> K[SKKNNImputer]
    classDef sky fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef emerald fill:#d1fae5,stroke:#059669,color:#064e3b
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    class A,B,E,F sky
    class C,D,G,H emerald
    class I,J,K violet

2. The concepts, taught from zero

2.1 Classification: labels and the label space

A classifier returns an integer label per row. To count how often it is right we need a label space: the set of labels that defines the rows and columns of the result. sciencekit offers two ways to build it:

  • an explicit list, validated (non-empty, no duplicates) and sorted internally;
  • otherwise the sorted union of the labels observed in the truth and in the predictions.

The order matters: every metric, every confusion-matrix row and every per-class score follows the same ascending order, so two evaluations of the same data always produce the same layout.

2.2 The confusion matrix

The confusion matrix is the atom of classification evaluation. Rows are true labels, columns are predicted labels, and each cell counts observations.

flowchart LR
    accTitle: A confusion matrix and the numbers derived from it
    accDescr: Rows are true labels, columns predicted labels. The diagonal holds true positives; row sums are support, column sums are prediction counts.
    A["true 0 / pred 0 (TP)"] --> D[precision and recall]
    B["true 0 / pred 1 (FN)"] --> D
    C["true 1 / pred 0 (FP)"] --> D
    E["true 1 / pred 1 (TP)"] --> D
    D --> F[accuracy]
    D --> G[per-class precision, recall, F1]
    G --> H[macro, micro, weighted, binary aggregates]
    classDef sky fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    class A,B,C,E sky
    class D,F,G violet
    class H amber

Precision asks of the rows we predicted as class c, how many really were c? Recall asks of the rows that really were c, how many did we find? F1 is their harmonic mean. When a denominator is zero the library returns zero, never NaN and never a panic: absence of evidence is not an undefined number.

2.3 Averaging across classes

Per-class scores are not enough for a single number. SKAveraging defines four policies:

PolicyQuestion it answers
MacroEvery class counts equally, regardless of size.
MicroPool every true positive and every observation; for single-label problems this equals accuracy.
WeightedWeight each class by its true support.
Binary { positive_label }Report one chosen class explicitly — no hidden pos_label = 1.

2.4 Regression: error and $R^2$

Regression predicts a continuous number. The library measures the mean squared error, its square root, the mean absolute error, and the coefficient of determination $R^2 = 1 - \mathrm{SSE} / \mathrm{SST}$. When every target is identical, $\mathrm{SST}$ is zero; the documented finite policy returns 1 for an exact prediction and 0 otherwise, instead of dividing by zero.

2.5 Streaming: sums, not predictions

A metric over a million rows must not store a million predictions. The regression accumulator stores constant-size state — count, a running mean, $M_2$ (the Welford/Chan sum of squared deviations from the mean), and compensated $\sum (y - \hat{y})^2$ and $\sum \lvert y - \hat{y} \rvert$ — and the classification accumulator stores one counter per observed label pair. Both can be merged, so batches and parallel partitions finalize to exactly the whole-input result.

flowchart TB
    accTitle: Mergeable accumulators
    accDescr: Batches or rayon partitions each build a small accumulator; merging combines the counters and sums; finalization produces the same matrix or errors as one pass.
    A[partition 1] --> D[merge]
    B[partition 2] --> D
    C[partition 3] --> D
    D --> E[finalize]
    E --> F[confusion matrix or regression sums]
    F --> G[same value as one whole-input pass]
    classDef sky fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef emerald fill:#d1fae5,stroke:#059669,color:#064e3b
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
    class A,B,C sky
    class D,E,F emerald
    class G violet

Long sums in f32 lose small addends next to large ones, and $\sum y^2 - n \cdot \overline{y}^2$ cancels catastrophically for large targets. The regression accumulator therefore uses Neumaier compensated summation for the error sums and the Welford/Chan M2 state for the target variance: $M_2$ accumulates squared deviations from the running mean, so no large terms cancel and merges use the standard parallel formula. A test sums [1e8, 1, -1e8, 1] in f32 and proves the compensated value is 2 while the naive sum is 1.

2.6 Missing values: the NaN-aware distance

nan_euclidean answers a different question from Euclidean distance. If a feature is missing in either row, it is not compared. The sum runs only over co-observed features, then is scaled by the ratio of total features to co-observed features:

$$d(a, b) = \sqrt{\sum_{\text{present}} (a_i - b_i)^2 \cdot \frac{\text{total_features}}{\text{present_features}}}$$

If the two rows share no observed feature, the distance is NaN. This is exactly the distance SKKNNImputer needs, because the set of comparable features changes from pair to pair — which is also why a spatial tree cannot index it.

flowchart LR
    accTitle: NaN-aware Euclidean distance
    accDescr: Only co-observed coordinates contribute to the squared difference; the result is scaled by total over present features, and a pair with none present yields NaN.
    A["row a: 1, NaN, 3"] --> C{co-observed?}
    B["row b: NaN, 2, 3"] --> C
    C -->|"feature 2 only"| D["sum = (3 − 3)² = 0"]
    D --> E["scale by 3 / 1"]
    E --> F["distance = 0"]
    C -->|"no feature"| G[NaN]
    classDef sky fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef rose fill:#ffe4e6,stroke:#e11d48,color:#881337
    class A,B,C sky
    class D,E,F amber
    class G rose

3. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Distances stay in sciencekit_mathThe pairwise-distances capability already owns them, and neighbours, SVM, clustering and imputation depend on math, not on evaluation.Mirroring scikit-learn’s metrics.pairwise namespace — it would invert the crate dependency for a cosmetic resemblance.
Extend the central SKErrorSKError is already #[non_exhaustive]; EmptyInput, NonFiniteValue and UnknownLabel are reusable across algorithms, and scorer adapters keep type Error = SKError.A crate-local SKMetricsError — it would force conversions at every boundary and contradict the central-taxonomy contract.
Explicit zero-division policyZero is finite, comparable and never contaminates an average; the policy is testable.Returning NaN — one undefined class poisons every macro average downstream.
Binary averaging is explicitBinary { positive_label } names the class instead of assuming label 1.scikit-learn’s hidden pos_label = 1 default — surprising for label sets without 1.
Compensated sums, scalar stays FAn f32 pipeline never detours through f64; compensation recovers the lost bits.Accumulating everything in f64 — a scalar detour inconsistent with the generic-float change.
Accumulators, not stored predictionsConstant-size regression state and $O(k^2)$ classification state finalize to the same values as a whole pass.Keeping every prediction — unbounded memory, defeats streaming.

4. Each public object, explained

sciencekit_metrics exposes three layers.

Whole-input functions — take borrowed views or slices and own nothing:

FunctionResult
sk_confusion_matrixSKConfusionMatrix over the resolved label space
sk_accuracy_scorefraction of exactly matching labels
sk_precision_score, sk_recall_score, sk_f1_scoreaggregated classification scores
sk_mean_squared_error, sk_root_mean_squared_error, sk_mean_absolute_errorregression errors
sk_r2_scorecoefficient of determination

Scorer adapters — implement the existing SKLabelScorer and SKSupervisedScorer contracts, so any compatible fitted model is scored through the pure form (stored outputs) or the convenient form (run inference, then delegate): SKAccuracyScorer, SKPrecisionScorer, SKRecallScorer, SKF1Scorer, SKMeanSquaredErrorScorer, SKRootMeanSquaredErrorScorer, SKMeanAbsoluteErrorScorer, SKR2Scorer.

Accumulators — SKClassificationAccumulator (observe, merge, finalize a confusion matrix) and SKRegressionAccumulator (observe, merge, finalize errors and $R^2$). Both are Send + Sync; both reject finalization over zero observations with EmptyInput.

The two distance kernels live in sciencekit_math::pairwise: sk_chebyshev_distance_matrix and sk_nan_euclidean_distance_matrix.


5. Walk-through: the tests are the specification

The label space

label_space_tests.rs pins the order and the validation:

#![allow(unused)]
fn main() {
let space = SKLabelSpace::from_explicit(&[2, 0, 1]).expect("valid label list");
assert_eq!(space.labels(), &[0, 1, 2]);
}

Sorting is not cosmetic: the same test suite checks that duplicates and an empty list are rejected as InvalidHyperparameter, and that a label outside the explicit space returns UnknownLabel { label }.

The confusion matrix and averaging

confusion_tests.rs builds the matrix from a known example and verifies the row-major counts. averaging_tests.rs then uses one unbalanced matrix — truth [0,0,0,0,1], predictions [0,0,0,1,1] — and checks every policy against hand-computed values: macro precision 0.75, micro precision 0.8, weighted precision 0.9, binary class-1 precision 0.5. The micro_averaging_equals_accuracy test is the important invariant: on single-label multiclass data, micro F1 and accuracy must agree.

The accumulators

classification_tests.rs observes the same pairs one by one and compares the finalized matrix with sk_confusion_matrix; merging_two_accumulators_equals_concatenation splits the same pairs, merges, and checks equality again. The concurrency test partitions 10 000 pairs across eight rayon tasks and reduces the accumulators. The regression twin does the same for MSE, MAE and $R^2$, and the acceptance suite repeats the exercise at $100,000$ observations.

The distances

chebyshev_tests.rs pins the largest-coordinate rule, symmetry, non-negativity and the parallel path against a direct reference. nan_euclidean_tests.rs encodes the formula as scenarios: co-observed-only comparison, the scale factor, the no-co-observation NaN, equality with Euclidean when nothing is missing, and symmetry.


6. Where it sits

flowchart TB
    accTitle: Crate dependencies after the metrics foundation
    accDescr: sciencekit_common supplies the contracts and errors; sciencekit_math supplies pairwise kernels; sciencekit_metrics builds evaluation on top; downstream algorithm crates consume both.
    common[sciencekit_common: contracts, errors] --> math[sciencekit_math: kernels, distances]
    common --> metrics[sciencekit_metrics: evaluation]
    math --> metrics
    metrics --> downstream[model selection, later waves]
    math --> algorithms[preprocessing, impute, linear models, neighbours, SVM]
    classDef sky fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef emerald fill:#d1fae5,stroke:#059669,color:#064e3b
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#4c1d95
    class common,math sky
    class metrics emerald
    class downstream,algorithms violet

The dependency direction is deliberate: evaluation may use the numeric substrate, but the numeric substrate never depends on evaluation. The next algorithms — an imputer that consumes nan_euclidean, neighbours that consume Chebyshev and the accumulators, SVM that consumes distances — plug into the same foundation.


7. What comes next

With evaluation in place, every estimator shipped so far can produce metrics, and the next wave can be judged as it is built. The immediate follow-ups are the SKKNNImputer, which the NaN-aware distance unblocks, and the neighbours wave, whose classifiers and regressors will use both the distance catalogue and the streaming accumulators.

Deterministic randomness: one generator for every stochastic estimator

Every algorithm in this chapter’s family — SGD, k-means++, MiniBatchKMeans, random forests, bagging, boosting, randomized SVD, isolation forests — needs randomness. Before this change, the repository had one pub(crate) SplitMix64 inside sciencekit_linear_model that only SGD used, plus two private xorshift64* permutations with hard-coded seeds inside the logistic SAGA solver and the coordinate-descent random selection. The two xorshift streams were not reachable through any builder, and the next crate that needed a random number would either copy one of them or, worse, call the operating system’s entropy source and make its tests flaky. This change promotes one generator to sciencekit_common, retires every private stream, gives the surface a public contract, and writes down the reproducibility rule the whole library follows from now on.

The capability is deterministic-randomness; the code lives in crates/sciencekit_common/src/random/.

1. The problem, in plain words

Imagine two runs of the same training job on the same data with the same configuration. If the model comes out different, you cannot tell whether you changed something that matters or whether the dice simply landed differently. Randomness is useful (it is what lets a forest grow different trees), but uncontrolled randomness makes results irreproducible and bugs unfindable.

There is a second problem, subtler. Suppose you seed one generator and share it across the eight threads that build a random forest. Which thread draws which number now depends on scheduling. Run the job again with four threads and the same seed and the forest changes. The seed did not buy you what you thought it bought.

So the requirement is not “use a seed”. It is:

The same seed, the same data and the same configuration produce the same model, independent of how many threads ran and in which order.

2. The decisions, and the roads not taken

  1. A shared generator, not one per crate. One implementation means one golden-vector test, one reproducibility promise and no drift. The SAGA permutations and the coordinate-descent random sweep order are migrated onto it, so no estimator keeps a private stream.
  2. SplitMix64. A 64-bit counter advanced by the golden-ratio increment and finished with an invertible bit mixer. It needs no entropy, no allocation and no platform state, so the raw stream is identical everywhere.
  3. A pure sub-seed function. Each independent component (tree #7, initialization, stage 3, fold 2) derives its own seed from the global seed with sk_derive_seed(global_seed, domain, index). Because the function keeps no state, the result depends only on its three inputs — not on who called it first or on which thread.
  4. random_seed(u64) on every stochastic builder, defaulting to 0. No ambient RNG, ever.

Roads not taken. A per-crate generator (duplication and inconsistent guarantees); a global thread-local RNG (order-dependent, exactly the bug above); rand from crates.io (a dependency and a moving target for reproducibility); and drawing sub-seeds from a shared stream (then thread count changes which component gets which seed).

3. The concepts, taught from zero

What a pseudo-random generator is

A pseudo-random generator (PRNG) is a function with memory: it holds a state, and each call returns a value derived from that state and advances it. Given the same starting seed, it replays the same sequence. “Pseudo” means the values look random but are fully determined.

flowchart LR
    accTitle: A seeded generator is a replayable sequence
    accDescr: A seed initialises the generator state. Each next_u64 call transforms the state and returns a value. The same seed always replays the same sequence, and different seeds start different sequences.
    S["Seed<br/>e.g. 42"] --> G["Generator state"]
    G -->|"next_u64()"| V1["value 1"]
    G -->|"next_u64()"| V2["value 2"]
    G -->|"next_u64()"| V3["value 3"]
    V1 --> T["Same seed → same sequence<br/>(bit for bit)"]
    V2 --> T
    V3 --> T
    classDef seed fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class S seed
    class G,V1,V2,V3 step
    class T result

SplitMix64, concretely

SplitMix64 keeps one u64. Each call does two things: add a fixed golden-ratio constant (the counter step), then mix the bits so neighbouring states look unrelated:

$$ \text{state} \leftarrow \text{state} + \varphi,\qquad z \leftarrow \text{mix}(\text{state}) $$

with $\varphi = \texttt{0x9E3779B97F4A7C15}$ and the mixer being two rounds of “xor-shift then multiply”. The mixer is invertible, so no output is ever lost; the shifts give avalanche — flipping one input bit changes about half the output bits. That is why 0, 1, 2, … seeds produce wildly different streams instead of near-identical ones.

Uniform, floats, and normal draws

next_u64 gives 64 random bits. Everything else is built on it:

  • next_f64 takes the top 53 bits and divides by $2^{53}$ — the exact number of bits an f64 can hold without rounding — producing a value in $[0, 1)$.
  • uniform(low, high) scales that value to the requested interval.
  • normal() uses Box–Muller: two independent uniforms become two independent standard normals. One is returned and the other is cached for the next call, so a pair of uniforms yields a pair of normals. That cache is why the generator has a second field, cached_normal.

Sub-seeds: independent components without shared state

If every component shares one generator, the number a component sees depends on how many draws happened before it — which depends on thread scheduling. The fix is to give each component its own generator, seeded from (global_seed, domain, index). The function folds the domain in with one golden-ratio multiplier and the index with another, mixing between them:

$$ \text{seed} = \text{mix}!\left(\text{mix}\left(s \oplus d\varphi_1\right) \oplus i\varphi_2\right) $$

Because it is a pure function of its inputs, deriving the 64 tree seeds sequentially or across eight threads produces the same 64 seeds. That is the whole trick behind thread-count invariance.

flowchart TD
    accTitle: Sub-seed derivation and thread-count invariance
    accDescr: A global seed plus a domain tag plus a component index enter a pure mixing function and produce one sub-seed. Because the function keeps no state, distributing the same 64 indices over one, two, four or eight threads yields the identical set of sub-seeds, so the model does not change with thread count.
    A["Global seed<br/>s = 42"] --> M["sk_derive_seed(s, domain, index)"]
    D["Domain tag<br/>tree, initialization, stage, fold, projection"] --> M
    I["Component index<br/>0, 1, 2, …"] --> M
    M --> R["One sub-seed per component"]
    R --> P1["1 thread"]
    R --> P2["2 threads"]
    R --> P8["8 threads"]
    P1 --> E["Identical seeds<br/>identical model"]
    P2 --> E
    P8 --> E
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef core fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef out fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A,D,I input
    class M core
    class R,P1,P2,P8 out
    class E result

Reproducibility scope — the honest fine print

The integer stream is bit-identical on every platform and every Rust version, because it uses only wrapping integer arithmetic. The floating-point draws use IEEE-754 basics plus sqrt, ln and cos; the same build on the same platform reproduces them exactly, while across platforms they are guaranteed only within the estimator’s documented tolerance. Estimators add one more condition: same input and same backend. Saying this out loud is part of the contract — a promise that silently breaks on another machine is worse than a narrower promise that holds.

4. Each public object, explained

  • SKRandomGenerator — the generator. new(seed) builds it; next_u64, next_f64, uniform, normal, next_index, shuffle, shuffled_indices and sample_indices_without_replacement draw from one stream. It is Send: a task can own one and move it across threads, but sharing one between threads needs external synchronization, so each component gets its own.
  • sk_derive_seed(global_seed, domain, index) -> u64 — the pure sub-seed function.
  • Domain constants — SK_RANDOM_DOMAIN_TREE, SK_RANDOM_DOMAIN_INITIALIZATION, SK_RANDOM_DOMAIN_STAGE, SK_RANDOM_DOMAIN_FOLD, SK_RANDOM_DOMAIN_PROJECTION. Distinct tags guarantee that, for example, tree #0 and fold #0 never share a stream.
  • All of them are re-exported from the sciencekit_common crate root, so an estimator imports sciencekit_common::SKRandomGenerator and nothing else.

5. A real walk-through, using the tests

The executable truth lives in random/generator_tests.rs and random/sub_seed_tests.rs. Three of them tell the whole story.

Test: golden_vectors_pin_the_splitmix64_stream

This test hard-codes the first five outputs for seeds 0, 1 and two others. If anyone changes a constant or a shift, the test fails immediately — which is exactly the point: the golden vectors are the compatibility promise. Compare with the concurrency test: seeds change the stream; constants change the stream; nothing else may.

Test: the_same_seed_produces_the_same_shuffle_order

Two generators with the same seed must produce the same permutation. This is the property SGD’s epoch shuffle depends on, and the companion test different_seeds_produce_different_shuffle_orders proves the seed actually does something.

Test: derivation_is_thread_count_invariant

The test computes 64 sub-seeds sequentially, then again with 1, 2, 4 and 8 threads, each worker handling a stride of indices. It collects every (index, seed) pair and asserts the set is identical. This is the test that would have caught the shared-generator design: with one shared stream, eight threads consume draws in a different order and the seeds differ. Because sk_derive_seed is pure, they cannot.

The companion test in sciencekit_linear_model goes one level up: it replays an SGD epoch with an order produced by SKRandomGenerator and asserts bit-identical coefficients. That proves the estimator really consumes the shared generator’s stream, rather than a look-alike.

6. Look inside

FileResponsibility
random/mod.rsPure dispatcher: declares and re-exports, no logic
random/generator.rsSplitMix64 and the draw operations
random/generator_tests.rsGolden vectors, range, permutation, moments
random/sub_seed.rssk_derive_seed and the domain constants
random/sub_seed_tests.rsDistinctness, purity, order and thread invariance

The folder module follows the repository rule: mod.rs carries no implementation, and each companion *_tests.rs sits beside the file it tests.

7. What this unlocks

Every stochastic estimator now has one convention: a random_seed(u64) builder parameter defaulting to 0 — proven by SKLogisticRegression (SAGA), SKLasso and SKElasticNet (random selection) alongside SKSGDClassifier/SKSGDRegressor — sub-seeds derived with sk_derive_seed, results collected in a stable order (the tests fit the same model under one and four rayon threads and compare coefficient rows by index), and no ambient RNG. The randomized SVD kernel, k-means initialization, forests, bagging, boosting and cross-validation folds will plug into the same contract, and their reproducibility tests get to be exact instead of statistical.

Sparse distance matrices: one dispatcher, four representation pairs

Measuring distances is the smallest-looking operation in a machine-learning library and one of the most consequential. k-nearest neighbours, k-means, DBSCAN, the RBF kernel, silhouette scores, nearest-centroid classifiers and the imputer all begin with a matrix of pairwise distances. Waves 0–2 computed that matrix for dense data only. Text features, one-hot encodings, user–item matrices and graph adjacency are sparse, and a sparse matrix with one million columns must never be turned into a dense one just because a distance routine was easier to write that way.

This chapter tells how the sparse pairwise path was built: what a distance matrix is, why the naive formula is dangerous, how the sparse kernels recover the dense answers from stored values only, and why a single dispatcher — rather than a flag inside every kernel — is what keeps the representation decision honest.

The capability is pairwise-distances; the code lives in crates/sciencekit_math/src/pairwise/.

1. The problem, in plain words

A distance matrix answers, for every pair of rows, “how far apart are they?”. With $n$ query rows and $m$ reference rows the answer is an $n \times m$ grid of numbers. Every algorithm above it reads that grid.

The dense formula for squared Euclidean distance is algebraically beautiful:

$$ \lVert a - b \rVert^2 = \lVert a \rVert^2 - 2,a\cdot b + \lVert b \rVert^2 $$

It lets you compute every pair with one matrix product instead of a subtraction per pair. But it is also numerically dangerous: when two rows are almost identical, $\lVert a\rVert^2$ and $\lVert b\rVert^2$ are large and nearly equal, and their difference loses precision. A second, structural problem appears for sparse data: the formula assumes every coordinate exists. In CSR storage, a coordinate that is not stored is zero, and a zero is a real observation — not “missing”. Any sparse kernel must therefore distinguish three kinds of coordinate for every pair:

CoordinateLeft valueRight valueContribution
sharedstored $a_i$stored $b_i$$f(a_i, b_i)$
left-onlystored $a_i$implicit $0$$f(a_i, 0)$
right-onlyimplicit $0$stored $b_j$$f(0, b_j)$

A sorted row merge walks both rows once and classifies every coordinate into one of the three cases. Everything else is arithmetic on those three cases.

2. The decisions, and the roads not taken

  1. One public dispatcher. sk_pairwise_distance_matrix(metric, left, right) is the single entry point. It validates shapes, matches metric × representation once, and calls a prepared kernel. Representation-specific kernels stay internal so the public surface cannot forget a combination.
  2. Dense formulas, sparse contributions. Each sparse metric is derived from the same definition the dense kernel uses — norms plus shared dot product for Euclidean, a merged sum for Manhattan and Chebyshev, stored dot and norms for cosine — never by densifying.
  3. Row-parallel fill. The output is filled row by row with rayon at grain 1024 — the same grain the dense Chebyshev and NaN-aware kernels use — so parallel and sequential runs are bit-identical.
  4. NaN-aware Euclidean is dense-only. In CSR an implicit zero is an observed value, so “what is the distance ignoring missing coordinates?” has no sparse meaning. The dispatcher rejects it up front with UnsupportedRepresentation.

Roads not taken. A is_sparse boolean threaded through every kernel (branching in the hot loop and easy to get wrong); densifying a sparse input when it is “small enough” (a silent memory cliff); and a separate public function per representation (four times the surface, and callers must choose). The norm-expansion form is used, because for sparse rows it needs only the stored values; the dense kernels keep the same form, so the two paths stay comparable — with the caveat that near-identical rows can lose precision in the dense expansion, which is why equivalence tests compare values that are not catastrophically close.

3. The concepts, taught from zero

CSR storage, in one paragraph

Compressed sparse row keeps three arrays: the stored values, the column each value lives in, and a pointer marking where each row starts. Row $i$ occupies the slice between indptr[i] and indptr[i+1]. Because columns inside a row are kept ascending, two rows can be merged with two indexes — the same trick merge sort uses.

Why the merge sees only three cases

Walk the left row and the right row together, advancing whichever column is smaller. When the columns match, the coordinate is shared; when only the left has an entry, it is left-only; when only the right does, right-only. At the end one row may be exhausted; the remainder is one-sided. That is the entire helper sk_merge_sorted_rows, and every sparse kernel is a fold over its output.

flowchart TD
    accTitle: Row merge yields the three sparse coordinate cases
    accDescr: Two ascending CSR rows are walked with two indexes. Equal columns are shared coordinates, a smaller left column is left-only, a smaller right column is right-only. The kernel folds a per-metric contribution over the three cases and never materialises a dense row.
    A["Left row<br/>stored columns ascending"] --> M{"Compare<br/>column indexes"}
    B["Right row<br/>stored columns ascending"] --> M
    M -->|"equal"| S["Shared coordinate<br/>f(a_i, b_i)"]
    M -->|"left smaller"| L["Left-only<br/>f(a_i, 0)"]
    M -->|"right smaller"| R["Right-only<br/>f(0, b_j)"]
    S --> F["Fold into the pair distance"]
    L --> F
    R --> F
    F --> O["Distance matrix cell"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef case fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A,B input
    class S,L,R case
    class F,O result

Each metric from its definition

  • Squared Euclidean. Shared coordinates contribute $(a_i-b_i)^2$; one-sided ones contribute the square of the stored value. Equivalently: $\lVert a\rVert^2 + \lVert b\rVert^2
    • 2\sum_{\text{shared}} a_i b_i$, with the norms computed from stored values only.
  • Euclidean. The square root of the squared form.
  • Manhattan. Sum of absolute differences; a one-sided coordinate contributes $|a_i|$ or $|b_j|$.
  • Chebyshev. The maximum absolute difference; one-sided coordinates still participate, so the maximum must also consider the largest stored magnitude of the side that has no counterpart.
  • Cosine. $1 - \dfrac{a\cdot b}{\lVert a\rVert,\lVert b\rVert}$, with the dot product over shared coordinates only. The zero-norm policy matches the dense kernel.

4. Each public object, explained

  • SKPairwiseMetric — SquaredEuclidean, Euclidean, Manhattan, Chebyshev, Cosine and the dense-only NanEuclidean.
  • sk_pairwise_distance_matrix(metric, left, right) — the dispatcher. Accepts two SKDataViews (any of the four dense/sparse combinations), validates the feature count before computing, and returns Array2<F>.
  • sk_sparse_squared_euclidean_distance_matrix, sk_sparse_euclidean_distance_matrix, sk_sparse_manhattan_distance_matrix, sk_sparse_chebyshev_distance_matrix, sk_sparse_cosine_distance_matrix — the public sparse kernels, taking two borrowed CSR views. The mixed sparse×dense and dense×sparse kernels stay internal: the dispatcher is the only public door, so every representation pair is reachable and none is forgotten.

5. A real walk-through, using the tests

The executable truth is in pairwise/sparse/*_tests.rs and the dispatcher tests.

sparse_squared_euclidean_matches_dense_on_the_same_logical_matrix

The single most important test in the change: build one logical matrix, hand it to the dense kernel as an Array2 and to the sparse kernel as a CsMat, and assert the two matrices agree within tolerance. It is the definition of correctness for every sparse kernel, and it is repeated per metric.

sparse_squared_euclidean_is_symmetric_with_zero_diagonal

A metric has structure: $d(a,b) = d(b,a)$ and $d(a,a) = 0$. The test checks both, which catches a whole class of merge bugs (double counting, dropped one-sided coordinates).

sparse_pairwise_wide_matrix_is_not_densified

A matrix with one hundred million columns and three stored entries is passed through the dispatcher for all five sparse metrics. A densified copy would need about 2.4 GB and fail, so the test only passes because every kernel reads stored values. The test also keeps the stored-entry count unchanged — the memory promise is a test, not a comment.

sparse_pairwise_rejects_sparse_nan_euclidean and sparse_pairwise_dense_nan_euclidean_keeps_the_dense_kernel

The dense-only exception is exercised in two halves: a sparse request for the NaN-aware metric returns UnsupportedRepresentation, and a separate test proves the dense request still produces the dense NaN-aware matrix. This is the data-view-boundary rule applied to a semantically undefined representation: rejection is the whole answer because no sparse alternative path can exist.

sparse_pairwise_parallel_equals_sequential and sparse_pairwise_concurrent_calls_are_deterministic

The row-parallel fill must be invisible: the same input produces the same matrix whether one thread or many computed it, and several threads calling concurrently get their sequential results.

6. Look inside

FileResponsibility
pairwise/dispatcher/SKPairwiseMetric, sk_pairwise_distance_matrix, validation (metric.rs) and the representation routing (routing.rs)
pairwise/sparse/row_merge.rssorted-row merge classifying shared/one-sided coordinates
pairwise/sparse/squared_euclidean.rssparse squared Euclidean and Euclidean
pairwise/sparse/manhattan.rssparse Manhattan
pairwise/sparse/chebyshev.rssparse Chebyshev
pairwise/sparse/cosine.rssparse cosine
pairwise/sparse/acceptance_tests/tiny, large and concurrent acceptance suite

7. Why this shape matters

The dispatcher is the load-bearing decision. It makes “every metric works on every representation pair” a property of one function that can be tested cell by cell, instead of a convention every kernel must remember. It also gives the dense-only exception exactly one place to live: the NaN-aware metric is rejected before a single element is read, and the reason is written next to the rejection. The neighbours, clustering, imputation and model selection changes now call one function and inherit all of it.

Ranking metrics: ROC, average precision, log loss and MCC

Accuracy answers one question: how often is the label right? It cannot answer the question that matters when a model outputs a score — “how well does the model rank the positives above the negatives?” A fraud detector that flags the right transactions but ranks them below a thousand harmless ones is useless in a review queue, even at high accuracy. Ranking metrics measure that ordering directly, and they are the last big piece of the evaluation foundation.

This chapter builds them: the ROC curve and its area (AUC), precision-recall curves and average precision, log loss, balanced accuracy and the Matthews correlation coefficient, plus their scorer adapters and a mergeable AUC accumulator.

The capability is ranking-metrics; the code lives in crates/sciencekit_metrics/src/ranking/ and the probability-scorer contract in sciencekit_common.

1. The problem, in plain words

Imagine sorting every example by the model’s score, highest first. Slide a threshold down that sorted list. At each point you can count four things:

predicted positivepredicted negative
actually positivetrue positive (TP)false negative (FN)
actually negativefalse positive (FP)true negative (TN)

Two rates summarise the point:

$$ \text{TPR} = \frac{TP}{TP + FN}, \qquad \text{FPR} = \frac{FP}{FP + TN} $$

The ROC curve plots TPR against FPR as the threshold moves; the area under it (AUC) is the probability that a randomly chosen positive is scored above a randomly chosen negative. An AUC of $1$ is a perfect ranking, $0.5$ is a coin flip, and $0$ is a perfectly inverted one. Precision-recall trades the same walk for $\text{precision} = TP/(TP+FP)$ against recall, which is far more informative when positives are rare.

The subtlety is ties. If two examples share a score, no threshold can separate them. Cutting the curve between them would invent an ordering the model never produced. The honest answer is to treat tied scores as one threshold and credit the pair with average ranks — the rank-sum form of AUC:

$$ \text{AUC} = \frac{\sum_{\text{positives}} \text{rank}i - \frac{n+(n_+ + 1)}{2}}{n_+ , n_-} $$

where tied scores receive the mean of the ranks they span.

2. The decisions, and the roads not taken

  1. Rank-sum AUC with average ranks. It computes the same number as integrating the ROC curve, in $O(n \log n)$ and with ties handled exactly once.
  2. One-vs-rest for multiclass. Each class gets its own binary problem; macro, micro and weighted averaging combine them. One-vs-one is explicitly out of scope.
  3. Log loss clips, never zeroes. A confident wrong prediction costs a lot but not infinity: probabilities are clipped at the scalar’s epsilon before the logarithm.
  4. A mergeable accumulator. Batches and whole-input evaluation must produce the same AUC, so streaming evaluation stays exact rather than approximate.
  5. A probability scorer contract. SKProbabilityScorer separates “give me scores and truth” from “give me a fitted model”, mirroring the other scoring contracts.

Roads not taken. Threshold-sweeping AUC (ties become arbitrary, and it is slower); a separate multiclass curve type per averaging mode; silently dropping non-finite scores instead of rejecting them; and an approximate streaming AUC.

3. The concepts, taught from zero

Why the curve needs distinct thresholds

If five examples share a score, they enter the positive set together. The ROC point after them is the only point the model can actually produce. Grouping equal scores before computing the step gives both the curve and the AUC a single, deterministic answer.

flowchart LR
    accTitle: From sorted scores to the ROC curve and its area
    accDescr: Examples are sorted by descending score. Equal scores are grouped into one threshold. At each group the true-positive and false-positive rates are recorded, producing the ROC curve. The area under that curve equals the rank-sum AUC, where tied scores share the average rank.
    A["Scores + labels"] --> B["Sort descending"]
    B --> C["Group equal scores<br/>one threshold per group"]
    C --> D["TPR and FPR<br/>after each group"]
    D --> E["ROC curve"]
    D --> F["Rank-sum AUC<br/>ties share average ranks"]
    E --> G["Area under the curve"]
    F --> H["Same number<br/>O(n log n)"]
    G --> H
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class B,C,D,E,F step
    class G,H result

Average precision is not the area under PR

The precision-recall curve is not monotone, so its area depends on how you interpolate. Average precision uses the step interpolation: each time recall increases, it adds the current precision weighted by the recall gain. That is what scikit-learn reports and what the tests pin.

Log loss: the cost of being confidently wrong

$$ \text{log loss} = -\frac{1}{n}\sum_i \left[ y_i \log p_i + (1-y_i)\log(1-p_i) \right] $$

With $y_i \in {0,1}$ and $p_i$ the predicted probability of the positive class. If $p_i$ is exactly $0$ for a positive example the logarithm diverges, so the probability is clipped at $\varepsilon$ first — finite by construction, still enormous for a confident mistake.

Balanced accuracy and MCC

Balanced accuracy is the mean of per-class recall: it refuses to reward a model that only learns the majority class. The Matthews correlation coefficient generalises beyond two classes (its binary form is the correlation on a $2\times2$ table) and ranges from $-1$ to $1$; it stays honest under strong class imbalance where accuracy flatters. In the general form, with $C$ the confusion matrix, $t_k = \sum_i C_{ik}$ the true count of class $k$, $p_k = \sum_i C_{ki}$ the predicted count, $c = \sum_k C_{kk}$ the correct count and $s = \sum_{ij} C_{ij}$ the total:

$$ \text{MCC} = \frac{c,s - \sum_k t_k p_k} {\sqrt{\left(s^2 - \sum_k p_k^2\right)\left(s^2 - \sum_k t_k^2\right)}} $$

4. Each public object, explained

  • sk_roc_curve(scores, labels, positive_label) -> SKRocCurve<F> — the grouped-threshold curve (false-positive and true-positive rates).
  • sk_roc_auc_score(scores, labels, positive_label) -> F — the rank-sum AUC with average ranks for ties.
  • sk_one_versus_rest_roc_auc_scores(...) and sk_multiclass_roc_auc_score(..., SKRankingAveraging) — per-class AUCs and the macro / micro / weighted combination.
  • sk_precision_recall_curve(...) -> SKPrecisionRecallCurve<F> and sk_average_precision_score(...) — the curve and its step-interpolated area.
  • sk_log_loss(...) and sk_binary_log_loss(...) — multiclass and binary log loss with epsilon clipping.
  • sk_balanced_accuracy_score(...) and sk_matthews_correlation_coefficient(...).
  • SKProbabilityScorer<F, M> in sciencekit_common — the pure form takes scores and truth, the convenient form obtains probabilities from a fitted SKClassifierPredictor. The shared validator checks the row count and the non-empty class axis; each metric then checks its own label/column rules.
  • Scorers — SKAucScorer, SKAveragePrecisionScorer, SKLogLossScorer, SKBalancedAccuracyScorer, SKMatthewsCorrelationScorer, each equal to its free function.
  • SKAucAccumulator — observe / merge / finalize, producing the same AUC as whole-input evaluation for both batched and merged streams.

5. A real walk-through, using the tests

roc_ties_use_average_ranks and roc_fully_tied_scores_have_half_auc

The first pins the rank-sum arithmetic on a hand-computed fixture with ties. The second is the degenerate case: every score equal means the model ranks nothing, and the AUC is exactly $0.5$. Together they prove the tie policy end to end.

precision_recall_hand_computed_average_precision

Average precision is easy to get subtly wrong (trapezoid instead of step). The fixture is small enough to compute by hand and asserts the exact value.

log_loss_zero_probability_is_finite_through_clipping

A predicted probability of exactly $0$ for the true class would be infinite; the test asserts the result is finite and large, proving the clip is applied rather than the logarithm guarded by a branch.

auc_accumulator_batches_equal_whole_input and auc_accumulator_merge_equals_concatenation

Streaming evaluation must not change the number. The tests feed the same data as one batch and as many batches, then as merged accumulators, and assert equality — the property that makes a streaming score trustworthy.

6. Look inside

FileResponsibility
ranking/roc.rsgrouped-threshold ROC curve and rank-sum AUC
ranking/multiclass_roc.rsone-vs-rest AUCs and averaging
ranking/precision_recall.rsprecision-recall curve and average precision
ranking/log_loss.rsbinary and multiclass log loss with clipping
ranking/balanced_accuracy.rsmean per-class recall
ranking/matthews.rsMatthews correlation coefficient
ranking/averaging.rsSKRankingAveraging
ranking/accumulator.rsSKAucAccumulator
scorers/ranking/the five scorer adapters (per-scorer files plus the label/column helpers)
sciencekit_common/src/scorer_traits/probability.rsSKProbabilityScorer

7. What this completes

With the label space, confusion matrix, regression errors and these ranking metrics, every estimator shipped so far can be evaluated on the axis its task cares about. Model selection (GridSearchCV, halving search) can now rank candidates by AUC or average precision, and the metrics suite no longer stops at accuracy.

Type-safe pipelines: making the data flow a compile-time property

A scaler followed by an imputer followed by a classifier looks trivial in a notebook. In a typed library it is a small design problem: each stage changes the shape of the data, some change the representation (dense to sparse), and the final estimator must receive the output of the last transformer, not the original input. Get it wrong at runtime and you find out with a shape error deep inside a fit; get it right at the type level and the wrong chain simply does not compile.

This chapter builds sciencekit_pipeline: a builder whose type records the stages composed so far, a classifier and a regressor finalizer, a forward fit walk, prediction delegation, and a dense/sparse block medium that carries the representation through the chain.

The capability is typed-pipeline; the code lives in crates/sciencekit_pipeline/.

1. The problem, in plain words

Consider the chain:

StandardScaler → SimpleImputer → LogisticRegression

Three things must line up:

  1. Scalar. The scaler works on f32 or f64; the classifier must use the same F.
  2. Medium. The scaler emits a dense matrix; the imputer accepts dense or sparse; the classifier is fitted on whatever the imputer produced.
  3. Order and arity. The final estimator is fitted on the transformed training data, and at prediction time the same transformers run in the same order before the classifier sees a row.

A runtime pipeline (a Vec<Box<dyn Transformer>>) can only check these at run time. The cost is not just errors: the compiler can no longer tell you that a classifier finalizer only accepts a supervised estimator, or that mixing f32 and f64 stages is impossible.

2. The decisions, and the roads not taken

  1. The builder type carries the stage tuple. SKPipeline::start::<F>() opens SKPipelineBuilder<F, ()>; each .then(stage) returns a builder with the tuple extended. The finalizer requires the tuple to end in a stage whose output the estimator accepts.
  2. Two finalizers, one per supervision kind. finalize_classifier returns SKPipelineClassifierBuilder; finalize_regressor returns the regressor one. Fitting a classifier as a regressor is not a runtime error — it does not type-check.
  3. A forward fit walk. fit runs the transformers in order on the training block, then fits the final estimator on the last output. The fitted model stores every stage model plus the final model, so prediction can replay exactly the same walk.
  4. One owned block medium. Stages exchange SKFeatureBlock (dense or CSR). A stage that changes representation says so in its own output type; the pipeline never densifies.
  5. Compile-fail doctests as contract tests. The claim “you cannot mix scalars” is tested by a compile_fail doctest, not by prose.

Roads not taken. A Vec<Box<dyn Transformer>> (runtime-only checks, dynamic dispatch in the hot path); an untyped fit(input) -> output graph (no finalizer guarantee); and converting everything to dense to dodge the representation question (silent memory blow-up on text data).

3. The concepts, taught from zero

Typed state: the builder remembers what you composed

Rust generics can carry values-shaped information in a type. SKPipelineBuilder<F, S> has a second parameter S — the tuple of configured stages. Appending a stage is a type-changing operation:

SKPipelineBuilder<F, ()>
    .then(scaler)  →  SKPipelineBuilder<F, ((), Scaler)>
    .then(imputer) →  SKPipelineBuilder<F, (((), Scaler), Imputer)>

The tuple is left-nested: every then wraps the previous tuple and the new stage, so the type grows without a variadic list. Nothing is stored dynamically — the stage values are moved into the builder by then, and fit turns them into fitted stage models. This is the “type-state” pattern: the compiler is the validator.

flowchart LR
    accTitle: The builder type grows with every composed stage
    accDescr: A pipeline builder's second type parameter is a tuple of the stages composed so far. Starting with an empty tuple, each then call returns a builder whose tuple has one more stage. The classifier finalizer only accepts a builder whose final stage feeds a supervised estimator, so an invalid chain fails to compile instead of failing at fit time.
    A["SKPipeline::start::&lt;f64&gt;()<br/>builder&lt;( )&gt;"] -->|".then(scaler)"| B["builder&lt;(( ), Scaler)&gt;"]
    B -->|".then(imputer)"| C["builder&lt;((( ), Scaler), Imputer)&gt;"]
    C -->|"finalize_classifier"| D["SKPipelineClassifierBuilder"]
    C -->|"finalize_classifier(regressor)<br/>rejected: not a classifier"| E["compile error"]
    D --> F[".fit(features, labels)"]
    classDef start fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef built fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef bad fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A start
    class B,C,D built
    class E bad
    class F result

The block medium and representation flow

Every stage receives and returns an SKFeatureBlock: either Dense(Array2<F>) or Sparse(CsMat<F>). The rule is simple and strict — the representation a stage produces is the representation the next stage receives. A dense scaler keeps the block dense; the one-hot encoder can emit CSR; the imputer accepts either. The pipeline itself never calls to_dense, so a sparse design stays sparse from the first stage to the classifier.

flowchart LR
    accTitle: Representation flows through the chain unchanged unless a stage changes it
    accDescr: A dense or sparse feature block enters the first stage, which returns a block of its own representation. Each following stage receives exactly what the previous one produced, and the final estimator is fitted on the last block. No stage densifies a sparse block unless its own output type says it does.
    I["Input block<br/>dense or CSR"] --> S1["Stage 1<br/>returns its own representation"]
    S1 --> S2["Stage 2<br/>receives exactly that block"]
    S2 --> E["Final estimator<br/>fitted on the last block"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef stage fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class I input
    class S1,S2 stage
    class E result

Why a forward walk is enough

A pipeline is a chain, not a graph: the output of stage $i$ is the input of stage $i+1$. One forward pass over the training data fits every transformer, and one forward pass over a query batch transforms it. There is no back-propagated state, so the fitted model is simply the ordered list of fitted stage models plus the fitted final estimator.

4. Each public object, explained

  • SKPipeline::start::<F>() — opens the typed builder.
  • SKPipelineBuilder<F, Stages> — .then(stage) appends a transformer stage; the type records the tuple.
  • finalize_classifier(estimator) / finalize_regressor(estimator) — produce SKPipelineClassifierBuilder / SKPipelineRegressorBuilder; each requires the composed tuple to match its supervision kind.
  • .fit(&features, targets) — runs the forward walk and returns SKPipelineClassifier / SKPipelineRegressor, which implement the shared SKClassifierPredictor / SKRegressorPredictor contracts.
  • Accessors — number_of_stages, the fitted stage models in order, and the final model, so a pipeline can be inspected after fitting.
  • SKPipelineTransformer and SKConfiguredStages — the traits that let an existing transformer become a stage and let the builder introspect its configured tuple.
  • SKFeatureBlock / SKIntoFeatureBlock — the owned dense/CSR medium and the conversion seam. The seam exists in sciencekit_common because the orphan rule forbids implementing a foreign From for a foreign type from the pipeline crate.

5. A real walk-through, using the tests

a_scaler_imputer_classifier_chain_fits_each_stage_on_the_previous_output

This is the definition of correctness for the forward walk. It fits the scaler on the raw features, then the imputer on the scaled features, then the classifier on the imputed features, and asserts the fitted stage statistics prove it: the scaler learned the mean of the raw columns ([3, 4]), and the imputer learned statistics near zero, which is only possible if it saw scaled data. If a stage were fitted on the raw input, those numbers would differ.

classifier_probabilities_equal_transform_then_final_model

Prediction must replay the same walk. The test transforms a query batch by hand through each fitted stage and then calls the final model, and asserts the pipeline’s probabilities match. Labels and regressor responses have their own versions, so delegation is covered for both supervision kinds.

a_sparse_classifier_pipeline_matches_the_dense_one

A dense chain (scaler → imputer → classifier) and a sparse chain (imputer → classifier, since the scaler is dense-only in its fitted statistics) are fitted on the same logical design and produce the same labels. The chains differ in composition, but both keep their representation end to end; the parity claim is about the data, not about an identical stage list.

The two compile_fail doctests

They are tests of the type system. The first passes a stage implemented only for f64 into an f32 pipeline, and the compiler rejects the SKPipelineTransformer<f32> bound. The second calls finalize_classifier with a regressor, and the compiler rejects it because SKLinearRegressionModel<f64> does not implement SKClassifierPredictor. Both doctests assert that the snippet does not compile — which is the contract.

the_same_pipeline_fitted_twice_produces_identical_predictions and concurrent_prediction_agrees_with_the_sequential_result

Determinism and thread-safety are part of the acceptance checklist: refitting an identically configured pipeline gives identical predictions, the fitted model is Send + Sync, and several threads predicting concurrently get their sequential answers.

6. Look inside

FileResponsibility
lib.rscrate documentation and the composition example
block.rsre-export of SKFeatureBlock / SKIntoFeatureBlock
stage.rsSKPipelineTransformer, the stage adapters and shape errors
stages/the left-nested stage chain (chain.rs) that fits and transforms in order
pipeline/builder.rstyped builder, then, the two finalizers
pipeline/model.rsfitted classifier/regressor models and accessors
pipeline/fit.rsthe forward fit walk
pipeline/predict.rsprediction delegation
pipeline/concurrency_tests.rsdeterminism and concurrent prediction
acceptance_tests/tiny/large, dense/sparse and composed-model acceptance

7. What this enables

Pipeline composition is the last piece model selection needed: a grid search can now vary the stages and the final estimator, and DAGs (the next change) generalise this chain to a graph with shared preprocessing. Because the type carries the composition, an invalid pipeline is a compiler error with a precise message rather than a shape panic after a long fit.

Spatial indexes: k-d trees and ball trees

Nearest-neighbour search is the first algorithm in the library whose cost is dominated by geometry rather than by arithmetic. Answering “which training rows are closest to this query?” by comparing every pair is $O(n \cdot m)$: a million training rows and ten thousand queries means ten billion distance computations. A spatial index prunes almost all of them.

This chapter builds two exact indexes — a k-d tree (axis-aligned boxes) and a ball tree (nested balls) — behind one searcher contract. Both return the exact answer a brute-force scan would return, in deterministic order, and both are the documented dense-only exception to representation parity.

The capability is kd-tree-and-ball-tree; the code lives in crates/sciencekit_neighbors/.

1. The problem, in plain words

Imagine a map. To find the five nearest cafés you do not measure the distance to every café in the country; you look at the neighbourhood first. A spatial index is the data structure that makes “look at the neighbourhood first” exact rather than heuristic.

It works by partitioning space and keeping a summary of each part:

  • a k-d tree splits on one coordinate at a time. Each node owns an axis-aligned box, and the box is summarised by its minimum and maximum on every axis.
  • a ball tree splits by picking two far-apart pivots and grouping points around them. Each node owns a centre and a radius, and the ball contains all of its members.

With a summary you can compute a lower bound on the distance from a query to anything inside the node. If that lower bound is already farther than the worst neighbour found so far, the entire subtree can be skipped — with no approximation.

2. The decisions, and the roads not taken

  1. Two indexes, one contract. SKNearestNeighborsSearcher<F> has k_nearest and radius_neighbors; both trees implement it, so callers can swap them.
  2. Exact, never approximate. Pruning uses a proven lower bound; nothing is dropped that could be a true neighbour.
  3. Deterministic ordering. Distances ascending, ties broken by the smallest training row index — never by tree layout or hash order. Two different partitions of the same data must produce the same result.
  4. Dense-only, explicitly. Tree geometry is boxes and balls; there is no honest sparse form. A sparse training or query view is rejected before any element is processed with UnsupportedRepresentation and a suggestion (the brute-force searcher arrives with the neighbours estimators).
  5. Bounded leaves and parallel batches. Build until every leaf holds at most leaf_size rows; scan the leaf with an auto-vectorizable loop; parallelise across query rows with rayon.

Roads not taken. Approximate indexes (random projections, HNSW) — they change the definition of the answer; cosine distance — it violates the triangle inequality, so tree pruning is unsound; NaN-aware distance — there is no sparse missing marker; and a single generic tree with a runtime metric branch inside the hot loop.

3. The concepts, taught from zero

Why a lower bound is enough

The search keeps a set of the best neighbours found so far. Let $d_{\max}$ be the current worst distance in that set. For a candidate node, compute $b$: a value that is guaranteed to be no larger than the distance from the query to any point in the node.

$$ b \le d(q, x) \quad \text{for every } x \text{ in the node} $$

If $b > d_{\max}$, then every point in the node is farther than the worst neighbour already found, so the node cannot improve the answer. Skipping it is safe — that is what makes the index exact. If $b \le d_{\max}$, descend and eventually scan the leaves.

flowchart TD
    accTitle: Exact pruning with a distance lower bound
    accDescr: A query descends the tree. At each node the algorithm computes a lower bound on the distance from the query to anything inside the node. If that bound exceeds the worst neighbour already found, the node is skipped. Otherwise the node is visited, and leaves are scanned. Because the bound never overestimates, no true neighbour is ever discarded.
    Q["Query row"] --> N["Current node"]
    N --> B["Lower bound b<br/>(box gap or ball gap)"]
    B --> D{"b > worst neighbour<br/>found so far?"}
    D -->|"yes"| S["Skip the subtree<br/>(exact, no approximation)"]
    D -->|"no"| V["Visit node"]
    V --> L{"Leaf?"}
    L -->|"no"| C["Descend into children"]
    L -->|"yes"| SCN["Scan the leaf<br/>update the best set"]
    C --> N
    SCN --> Q
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef skip fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class Q,N input
    class B,V,L,C,SCN step
    class S skip
    class D result

The k-d tree: boxes on axes

Each node splits its rows on one coordinate — the axis with the largest spread — by the median. The median guarantees balance, so the depth is $O(\log n)$. Every node stores the box that encloses its members: the minimum and maximum on each axis.

The lower bound is the box gap: for each axis, the distance from the query to the interval $[\min_i, \max_i]$, combined with the metric’s own combination rule (sum of squares for Euclidean, sum of absolute values for Manhattan, maximum for Chebyshev). Inside the box the gap is zero, which is why a query that lands inside a node always descends.

The ball tree: nested balls

The ball tree picks two far-apart pivots and splits the rows by which pivot is closer. Each node stores its centre and the radius that covers all members. The ball gap is $g = \max(0, \lVert q - c \rVert - r)$: zero when the query is inside the ball, otherwise how far outside it lies. The bound is then converted to the metric’s own unit — $g$ for Euclidean and Manhattan, $g^2$ for squared Euclidean, and $g/\sqrt{f}$ for Chebyshev, where $f$ is the feature count. Because the subtraction mixes two large magnitudes, the implementation subtracts an error term proportional to $\varepsilon,(\lVert q-c\rVert + r)$ from the gap before converting it. Pruning also requires the bound to exceed the limit by a small relative tolerance, so a bound that rounds onto the radius never discards a true neighbour: exploring one extra node is cheap, while pruning a node exactly at the radius would be wrong.

Ties, and why they need a rule

Two training rows at the same distance are equally good neighbours, but a list needs an order. Tree layout depends on the split, so “whatever the traversal found first” would make the result depend on the data structure. The contract fixes it: distance ascending, then the smallest training row index. A test partitions the same data differently and asserts the same order.

4. Each public object, explained

  • SKKDTree<F> / SKBallTree<F> — the built, immutable indexes.
  • SKKDTreeBuilder<F> / SKBallTreeBuilder<F> — builder-only construction with leaf_size (default documented and asserted), metric, backend (default Faer) and execution_mode (default Automatic); build(features) takes the borrowed training view.
  • SKNearestNeighborsSearcher<F> — the shared contract: k_nearest(queries, neighbors_count) returns a row-major SKNeighborQuery (distances + indices), and radius_neighbors(queries, radius) returns SKRadiusNeighbors (per-row slices, inclusive boundary, empty neighbourhoods allowed).
  • SKNeighborMetric — the implemented metrics: Euclidean, squared Euclidean, Manhattan and Chebyshev. SKRequestedNeighborMetric is the user-facing request type, which rejects Cosine and NaN-aware Euclidean at build time with a clear reason.
  • Internal node types (SKKDTreeNode, SKBallTreeNode) and the permutation are crate-private; the public accessors expose only the configuration, node_count and depth.

5. A real walk-through, using the tests

acceptance_every_metric_matches_brute_force_on_both_trees

The definition of correctness: for every metric, both trees return exactly the neighbours a brute-force scan returns. An index that prunes too aggressively fails here immediately.

kd_query_breaks_distance_ties_by_the_smallest_training_index and kd_query_tie_order_is_independent_of_the_tree_partition

Ties are the classic source of nondeterminism. The second test builds the same rows with different leaf_size values — different partitions — and asserts the neighbour order is identical.

kd_radius_query_includes_the_boundary and kd_radius_query_represents_an_empty_neighborhood

Radius queries are inclusive, and “nobody is within the radius” is a valid answer that must be representable rather than an error.

representation_rejects_sparse_training_for_both_trees

The dense-only exception, tested at the boundary: a CSR training view is rejected before the tree is built, with UnsupportedRepresentation. The reason is written next to the rejection — tree geometry has no sparse form.

acceptance_large_batches_agree_between_both_trees and acceptance_one_shared_index_serves_concurrent_batches

Large batches prove the parallel query path equals the sequential one, and a Send + Sync index answers several threads concurrently with their sequential results.

6. Look inside

FileResponsibility
kd_tree/builder, build (median splits and node array), k_nearest, radius and parallel query
ball_tree/builder, build (farthest pivots), k_nearest, radius and parallel query
metric/point distances and the box/ball lower bounds per metric
searcher/the shared contract, result types and query validation
acceptance_tests/tiny/large, every metric, ties, radius and concurrency

7. What this unlocks

The next change (knn-classifier-regressor) reuses both indexes and adds the brute-force searcher behind the same contract, which is how the estimators keep full representation parity: dense queries use a tree, sparse or mixed queries use brute force over the stored training rows, and the estimator never densifies. This change supplies the dense half of that story, tested against the answer that matters — the one brute force would give.

Dataset interop: one seam from engines into sciencekit

Every real dataset arrives from somewhere else: a Parquet file through Polars, a SQL result through DataFusion, an Arrow table, a pandas DataFrame, a Spark job. Those sources are columnar, heterogeneous and nullable — each column has its own type and may name missing values in its own way. sciencekit’s algorithms want homogeneous, dense or sparse numeric feature matrices plus targets.

The gap between the two is where most integration bugs live: a categorical column silently becomes a float, a null becomes 0.0 in one engine and NaN in another, a column order changes between batches, an async engine blocks the compute thread. This chapter builds the single seam that closes the gap — one schema, one selection, one missing-value policy, one conversion path, one streaming source contract and one async bridge.

The capability is dataset-interop-core; the code lives in crates/sciencekit_interop/.

1. The problem, in plain words

A columnar table is a list of named columns, each with its own logical type (integer, float, boolean, string, categorical) and its own nullability. To feed a model we must answer four questions deterministically:

  1. Which columns are features, and in what order? Model coefficients are positional, so the order must be explicit and stable — never “whatever the engine returned”.
  2. Which column is the target? Exactly one, and it may not also be a feature.
  3. What does a missing value mean? Reject the row, map it to NaN, fill a constant, or use the documented categorical code. Every engine must produce the same answer.
  4. Which representation? Dense for small numeric designs, CSR for sparse ones, and a stream for out-of-core fits.

A seam that answers all four in one place means the next engine adapter (Polars, Arrow, DataFusion) is a thin translation rather than another interpretation of the rules.

2. The decisions, and the roads not taken

  1. Engine-neutral core. sciencekit_interop does not depend on Polars, Arrow or DataFusion. Those arrive later behind optional features; the core defines the vocabulary they translate into.
  2. An ordered schema with explicit roles. SKTabularSchema keeps the column order, rejects duplicate names and empty schemas, and gives every column a role (feature, target, ignored) and a logical type.
  3. Explicit selection. SKColumnSelection names features and the optional target by name or position; the resolved selection is what conversion consumes, so the order is the selection order and never the engine’s.
  4. One missing-value policy. SKMissingValuePolicy (reject / map to NaN / fill a constant / documented categorical code) is applied identically to every engine.
  5. Typed column batches. SKTabularBatch holds SKColumnData per column with null counts; unsupported types are rejected once per batch, before any element is read.
  6. Conversion produces existing representations. Dense Array2, zero-copy views where the layout allows it, CSR blocks, SKDataBatch/SKSupervisedBatch for streaming, and the categorical view for coded columns.
  7. A reopenable source and an async bridge. SKTabularSource can be reopened for multi-epoch fits; SKAsyncTabularSource drains an async stream on a dedicated thread so the CPU never blocks an async runtime, and cancellation drops the reader.

Roads not taken. A single “convert everything to f64” path (loses categoricals and precision); engine crates as core dependencies (couples the library to four moving targets); per-engine missing-value conventions (irreproducible models); and letting a tokio runtime drive the conversion (blocks the compute pool).

3. The concepts, taught from zero

Columnar tables and logical types

A columnar table stores each column contiguously, which is why engines can compress and scan it efficiently. Each column has a logical type — what the values mean, not how they are laid out in memory. SKLogicalType is the neutral vocabulary: integers, floats, booleans, strings and categoricals. A model never sees “an Arrow Int64 array”; it sees “an integer column”, and the interop layer decides how to coerce it.

Nulls are not zeros

A null means “this value is unknown”. Mapping it to 0.0 invents a measurement; mapping it to NaN marks it as missing for the imputers. That is why the policy is explicit and applied once, not left to each engine.

flowchart TD
    accTitle: From a columnar table to a model input
    accDescr: An engine table enters as typed columns with nulls. The ordered schema assigns roles, the selection fixes feature and target order, the missing-value policy resolves nulls, and unsupported types are rejected before any element is read. The result is a dense matrix, a zero-copy view, a sparse block or a streaming batch, plus a typed target.
    E["Engine table<br/>named, nullable columns"] --> S["SKTabularSchema<br/>ordered roles and logical types"]
    S --> C["SKColumnSelection<br/>feature order + one target"]
    C --> P["SKMissingValuePolicy<br/>reject / NaN / constant / code"]
    P --> V{"supported type?"}
    V -->|"no"| X["structured error<br/>before any element"]
    V -->|"yes"| O["Dense Array2 / zero-copy view<br/>CSR block / streaming batch"]
    O --> T["Typed target view"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef bad fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class E input
    class S,C,P,V step
    class X bad
    class O,T result

Why the async bridge exists

An async engine yields batches asynchronously. sciencekit’s streaming executor is synchronous and CPU-bound. Bridging them naively — block_on inside the executor — blocks the runtime thread. SKAsyncTabularSource therefore runs a dedicated reader thread that awaits the stream and delivers batches through a bounded channel; the consumer never polls, back-pressure bounds memory, and dropping the consumer cancels the reader.

4. Each public object, explained

  • SKColumnRole / SKLogicalType / SKColumnSchema — the neutral vocabulary of one column; role and logical-type names round-trip and an unknown name is rejected.
  • SKTabularSchema — the ordered column list with deterministic lookup, duplicate-name and empty-schema rejection, and role partitioning.
  • SKColumnSelection / SKColumnSelectionBuilder / SKResolvedSelection — feature and target selection by name or position, validated once (no duplicate features, no target counted twice, no out-of-range position).
  • SKMissingValuePolicy — reject, map to NaN, fill a constant (validated finite) or use SK_CATEGORICAL_MISSING_CODE.
  • SKColumnData / SKTabularBatch — typed, nullable column storage and the validated batch (row-count agreement, logical-type agreement) with projection.
  • Conversion — dense Array2, SKRowMajorFeatureView/SKNumericColumnView (zero-copy when the layout allows), CSR materialization, SKDataBatch/SKSupervisedBatch.
  • SKTargetExtraction / SKCategoricalExtraction — typed targets (continuous, integer, nominal canonicalized deterministically) and coded/nominal categorical columns.
  • SKTabularSource / SKSupervisedTabularLazySource / SKTabularSourceProvider — the reopenable source contract and its bridge into the Phase 0 streaming providers.
  • SKAsyncTabularSource / SKAsyncTabularStream — the async-to-sync bridge.
  • SKInteropConversionAttributes / SKInteropSourceKind — the observability span and the stable source-kind names.

5. A real walk-through, using the tests

tiny_table_converts_for_both_scalars and large_table_converts_and_streams_in_order

The first proves the smallest end-to-end path (schema → selection → policy → matrix) for f32 and f64. The second proves order and streaming: a large table converts batch by batch in the input order and reports the expected row counts.

nullable_and_categorical_columns_follow_the_policy

Nulls and categoricals are where engines disagree. The test pins the numeric-null-to-NaN policy and the coded categorical path together, so the documented answer is not incidental. The Reject and ConstantFill variants have their own unit tests.

type_rejection_precedes_element_processing and unsupported_type_is_named_with_a_suggestion

An unsupported column type is rejected once per batch, before any element is read, with the column named and a suggestion. This is the same “reject up front” discipline as the representation rules.

caller_thread_never_polls and dropping_the_source_cancels_and_drops_the_stream

The async bridge is tested for the two properties that matter: the caller never polls (the reader thread does the waiting), and dropping the consumer cancels the reader instead of leaking a task.

one_shot_source_rejects_reopening and reopenable_source_replays_each_pass

A multi-epoch fit needs a reopenable source; a one-shot source must say so instead of silently returning an empty second pass.

6. Look inside

FileResponsibility
schema/roles, logical types, column schema and the ordered tabular schema
selection/feature/target selection and its resolved form
missing/the missing-value policy
columns/typed nullable column storage and scalar coercion
batch/the validated tabular batch, views, materialization, targets and categoricals
source/the reopenable source contract and the provider bridge
bridge/the async-to-sync reader thread, back-pressure and cancellation
observability/the conversion span and source-kind names
acceptance/tiny/large, nullable, concurrent and error-path suites

7. What this unlocks

Known limitation

A nominal target is canonicalized per batch: a streamed supervised batch carries the encoded indices but not the label table, so the mapping is not recoverable from the stream. Callers that need it extract the target directly. Global canonicalization across a whole stream is deferred.

Every engine change — Arrow, Polars, DataFusion, memory-mapped files, and the Python/Julia/JVM dataset bridges — becomes a translation into this vocabulary. The rules live in one crate, so a null means the same thing in a pandas DataFrame and a Parquet scan, and a feature order never depends on which engine produced the table.

k-means: Lloyd, Elkan and a seed you can trust

Clustering is the first unsupervised learning task in the library. Given $n$ rows and a requested number of clusters $k$, the goal is to partition the rows so that each one sits close to its group’s centre. It sounds simple, and the classic algorithm is short — but the interesting engineering is elsewhere: how to initialise without luck, how to accelerate without changing the answer, and how to keep the result identical across runs and thread counts.

This chapter builds SKKMeans: the Lloyd iteration, the Elkan accelerated variant, seeded k-means++ initialisation, best-of-n restarts, empty-cluster repair and the typed cluster assignment surface.

The capability is kmeans-lloyd-elkan; the code lives in crates/sciencekit_cluster/.

1. The problem, in plain words

k-means minimises the inertia: the sum of squared distances from every row to the centre of the cluster it was assigned to.

$$ \text{inertia} = \sum_{i=1}^{n} \lVert x_i - c_{a(i)} \rVert^2 $$

The algorithm alternates two steps until nothing changes:

  1. Assign every row to its nearest centre.
  2. Update every centre to the mean of the rows assigned to it.

That is Lloyd’s algorithm. Its two famous problems are initialisation (a bad starting guess gives a bad local optimum) and cost (each assign step compares every row to every centre). Everything else in this change exists to solve one of those two.

2. The decisions, and the roads not taken

  1. k-means++ initialisation, seeded. Pick the first centre uniformly, then pick each next centre with probability proportional to its squared distance to the closest chosen centre. Every draw comes from SKRandomGenerator seeded through sk_derive_seed, so the same random_seed reproduces the same centres.
  2. Best of number_of_initializations runs. k-means++ is still stochastic; running it several times and keeping the lowest inertia removes most of the variance. Ties go to the earliest initialisation, so the choice is deterministic.
  3. Elkan’s acceleration, same answer. Elkan keeps a lower bound on the distance from each row to every centre and skips comparisons that provably cannot win. It returns exactly what Lloyd returns, just faster.
  4. Auto picks by representation. Dense data uses Elkan; sparse data uses Lloyd with the norm-expansion kernel (Elkan’s bounds are cheap only when distances are cheap to compare and update). An explicit Elkan on sparse input falls back to Lloyd and the model reports what it actually ran.
  5. Empty clusters are repaired, deterministically. If a centre loses all its rows, it is moved to the row farthest from its own centre, with ties broken by row index.
  6. Typed assignments. predict returns Array1<SKClusterLabel>, never a bare index and never noise.

Roads not taken. Random initialisation as the default (unstable results); a fixed number of iterations instead of convergence (wasted work); sampling-based approximations (they change the answer); and sharing one RNG across parallel initialisations (thread count would leak into the result).

3. The concepts, taught from zero

Why k-means++ matters

Imagine the data has three natural groups and the first centre happens to land on one of them. Picking the second centre uniformly might land right next to it, wasting a centre while two groups share one. k-means++ makes that unlikely: it chooses the next centre where the current centres are far away, weighted by squared distance.

flowchart TD
    accTitle: k-means++ picks centres where the current ones are far
    accDescr: The first centre is drawn uniformly from the rows. Each next centre is drawn with probability proportional to the squared distance from the row to the closest chosen centre, so far-away rows are much more likely. The result is a well-spread starting set, which is then improved by the Lloyd iterations.
    A["Rows"] --> B["First centre<br/>uniform draw"]
    B --> C["Distance to the closest centre<br/>for every row"]
    C --> D["Draw the next centre<br/>weighted by squared distance"]
    D --> E{"k centres?"}
    E -->|"no"| C
    E -->|"yes"| F["Starting set"]
    F --> G["Lloyd / Elkan iterations"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class B,C,D,E step
    class F,G result

Lloyd’s loop, and why it stops

Each assign step can only decrease the inertia (every row moves to a centre at least as close as before), and each update step can only decrease it again (the mean is the point minimising the sum of squared distances). The inertia is bounded below by zero, so the loop must reach a fixed point. In practice it stops when the centres move less than tolerance or the iteration budget runs out; an exhausted budget returns a model with converged() == false rather than pretending.

Elkan: prune with bounds

Elkan maintains, for every row $x$ and centre $j$:

  • $d(x, c_j)$ — the exact distance to centre $j$ (needed only for the assigned one),
  • $\text{lower}(x, j)$ — a lower bound on the distance to centre $j$,
  • $\text{upper}(x)$ — an upper bound on the distance to its assigned centre.

A centre $j$ can be skipped when either bound test holds:

$$ \text{upper}(x) \le \text{lower}(x, j) \quad\text{or}\quad \text{upper}(x) \le \tfrac{1}{2},d(c_{a(x)}, c_j) $$

The first says the stored lower bound already exceeds the best distance. The second follows from the triangle inequality: $d(x,c_j) \ge d(c_a,c_j) - d(x,c_a) \ge \tfrac{1}{2}d(c_a,c_j)$ whenever $d(x,c_a) \le \tfrac{1}{2}d(c_a,c_j)$, so centre $j$ cannot be closer.

Both conditions are sufficient to prove another centre is at least as close, so pruning never changes the assignment. That is why kmeans_elkan_equals_lloyd_on_dense_data can assert exact equality: the acceleration is invisible in the output.

Sparse data: norms instead of differences

For a CSR design, forming $x - c$ is wasteful — most entries are zero. The kernel expands the squared distance:

$$ \lVert x - c \rVert^2 = \lVert x \rVert^2 - 2,x\cdot c + \lVert c \rVert^2 $$

with the dot product over stored entries only. The design is never densified, which is why a wide sparse matrix clusters in memory proportional to its stored values.

4. Each public object, explained

  • SKKMeans / SKKMeansBuilder — builder-only configuration: number_of_clusters, initialization (KMeansPlusPlus default, Random), number_of_initializations (default 1 for k-means++, 10 for random), maximum_number_of_iterations, tolerance, algorithm (Auto default, Lloyd, Elkan), random_seed (default 0), backend (default Faer) and execution_mode (default Automatic).
  • SKKMeansModel — the fitted state: centres, per-row assignments, inertia, the number of iterations and whether it converged, plus the configuration carried into the model.
  • SKKMeansAlgorithm / SKKMeansInitialization — the closed catalogues of algorithm and initialisation choices.
  • Fit and predict — SKUnsupervisedFit for fit; SKClustererPredictor for predict_clusters; transform returns the distance from every row to every centre; fit_predict returns the training assignments.
  • inertia() — the objective value a model selection search can compare.

5. A real walk-through, using the tests

kmeans_distance_sparse_wide_design_is_not_densified

A design with a very large number of columns and few stored entries is clustered through the sparse kernel. If any step called to_dense, this test would not complete — the no-densification promise is executable, not a comment.

kmeans_elkan_matches_lloyd_on_overlapping_data, kmeans_elkan_equals_lloyd_on_dense_data and kmeans_elkan_prunes_impossible_distances

The first draws five seeded, overlapping datasets (no planted clusters) and asserts Elkan returns Lloyd’s exact assignments and inertia — well-separated blobs hide stale-bound bugs, so this fixture is the real guard. The second checks the simple separated case; the third proves the acceleration actually prunes (a test that only compared answers would pass even if Elkan silently ran Lloyd). Together they pin correctness and the point of the variant.

kmeans_init_plus_plus_is_reproducible and kmeans_init_tie_selects_the_earliest_initialization

The seeded initialisation must replay exactly for a fixed random_seed; and when two initialisations reach the same inertia, the earlier one wins, so the outcome does not depend on rayon’s completion order.

acceptance_determinism_is_independent_of_the_thread_count

The same fit is repeated under different rayon thread counts and must produce identical assignments and centres. This is the test that would catch a shared generator: sub-seeds are derived per initialisation with sk_derive_seed, so thread count cannot leak into the answer.

kmeans_lloyd_empty_cluster_repair_moves_the_farthest_point

Empty clusters are a classic source of silent nonsense (a centre left at the origin). The test forces one and asserts the documented repair: move the centre to the row farthest from its own centre, with ties by row index.

6. Look inside

FileResponsibility
kmeans/builder.rsbuilder surface, defaults, validation
kmeans/distance.rsdense and sparse squared-Euclidean assignment kernels
kmeans/init.rs, kmeans/selection.rsseeded k-means++/random initialisation and best-run selection
kmeans/iteration.rs, kmeans/lloyd.rsshared iteration step, convergence, empty-cluster repair, Lloyd loop
kmeans/elkan.rsbounds, pruning and the accelerated assignment
kmeans/fit.rsfit entry point and algorithm resolution
kmeans/model.rs, kmeans/predict.rsfitted model, predictions, transform, accessors
acceptance_tests/tiny/large, representations, determinism, concurrency, metrics

7. What this unlocks

SKKMeans is the first estimator that produces the typed SKClusterLabel surface built in clustering-contracts, so silhouette-style scorers and the clustering metrics can evaluate it directly. It also provides the inertia objective that model selection can minimise, and the Elkan/Lloyd split previews the pattern the remaining clusterers follow: an exact algorithm, an accelerated variant, and a representation-driven choice between them.

Decision trees: CART, impurity and split search

A decision tree is the first model in the library that is not a linear combination of features. It asks a sequence of yes/no questions — “is $x_3 \le 1.7$?” — and predicts from the leaf a row ends in. That makes trees expressive (they capture interactions and thresholds a linear model cannot) and interpretable (the path is the explanation), and it makes them the foundation of every ensemble that follows: random forests, bagging, gradient boosting.

This chapter builds the CART tree: impurity, split search over dense and sparse designs, the two splitters (best and random), growth constraints, class weights, feature importances, classification and regression, and the deterministic order that makes all of it testable.

The capability is decision-trees; the code lives in crates/sciencekit_tree/.

1. The problem, in plain words

A tree grows by splitting a node: choose a feature and a threshold, divide the rows into “left” and “right”, and recurse. The question is which split to choose. CART answers with a loss: pick the split that most reduces the impurity of the children.

A node’s impurity measures how mixed it is:

  • Classification uses Gini $1 - \sum_c p_c^2$ or entropy $-\sum_c p_c \log p_c$, where $p_c$ is the fraction of the node’s rows in class $c$.
  • Regression uses squared error (variance around the mean) or absolute error (deviation around the median).

A pure node has impurity zero. The best split maximises the weighted impurity decrease:

$$ \Delta = \text{impurity}(\text{parent})

  • \frac{n_L}{n},\text{impurity}(L)
  • \frac{n_R}{n},\text{impurity}(R) $$

2. The decisions, and the roads not taken

  1. Sorted-threshold scan per feature. Sort the node’s rows by one feature, sweep the threshold left to right, and update the class counts or the running moments incrementally. That is $O(n \log n)$ per feature instead of $O(n^2)$.
  2. Sparse CSC scan. For a CSR design the natural scan is per column, so the design is converted once to CSC at fit time; each feature is read as its stored entries plus the implicit zeros, with no dense copy.
  3. Two splitters. Best evaluates every candidate (deterministic, the default) and Random draws a seeded threshold per feature, which the ensembles need.
  4. Deterministic ties. Equal impurity decreases go to the smaller feature index, then to the lower threshold. Growth is deterministic for the same data and seed, independent of thread count.
  5. Feature subsampling is seeded. maximum_features (All, Sqrt, Log2, Fraction, Count) draws its subset through sk_derive_seed per node, so thread count never changes it.
  6. Class weights change the impurity, not the vote. Balanced or explicit weights enter the class counts, so the split and the leaf probability both respect them.
  7. Importances from impurity decrease. A feature’s importance is its normalised total decrease; a tree without splits has all-zero importances.

Roads not taken. Exhaustive pairwise thresholds (quadratic); converting sparse to dense for split search (memory cliff); random tie-breaking (irreproducible trees); and a separate tree implementation per task (one growth engine, two criteria families).

3. The concepts, taught from zero

Why sorting enables a single sweep

For one feature, sort the rows by value. Every meaningful threshold sits between two consecutive distinct values. Sweep left to right, moving one row at a time from the right child’s counts to the left child’s, and after each move evaluate the impurity decrease. The best split is the maximum over the sweep — one pass per feature.

flowchart TD
    accTitle: CART split search on one feature
    accDescr: The node's rows are sorted by the feature. A sweep moves rows from the right child to the left one, updating class counts or moments incrementally. After each move the weighted impurity decrease is computed, and the split with the largest decrease wins, with ties going to the smaller feature and lower threshold.
    A["Node rows"] --> B["Sort by feature value"]
    B --> C["Sweep the threshold"]
    C --> D["Move one row left<br/>update counts or moments"]
    D --> E["Compute weighted impurity decrease"]
    E --> F{"Largest so far?"}
    F -->|"yes"| G["Remember feature + threshold"]
    F -->|"no"| C
    G --> H["Recurse into the children"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class B,C,D,E,F step
    class G,H result

Implicit zeros in a sparse scan

A CSR/CSC row may not store a coordinate — which means zero. A sparse split must therefore consider the zero side too. The scan sorts the stored values; for non-negative designs it starts with every implicit zero on the left and the stored entries on the right, then moves stored values across one by one (negative stored values sort before zero, and the sweep follows the same ordering rule). The test sparse_scan_recovers_the_implicit_zero_split builds a case where the only useful threshold separates zeros from non-zeros, so a scan that ignored implicit zeros would miss it.

Deterministic ties, and why they matter

Suppose two features produce exactly the same impurity decrease. If the tree picked whichever came first in a hash map, two runs could produce different trees — and every downstream ensemble would inherit the nondeterminism. The rule is simple: smaller feature index wins, then the lower threshold. best_split_is_independent_of_feature_order shuffles the feature order and asserts the same split.

Class weights

With weights $w_i$, the class mass in a node is the sum of its rows’ weights, and the impurity uses the normalised masses. A balanced weighting gives every class the same total mass, so a model cannot ignore a rare class simply because it is rare. The leaf probability is the weighted fraction, not the raw count.

4. Each public object, explained

  • SKDecisionTreeClassifier / SKDecisionTreeClassifierBuilder and SKDecisionTreeRegressor / SKDecisionTreeRegressorBuilder — builder-only surface: criterion, splitter (Best/Random), maximum_depth, minimum_samples_split, minimum_samples_leaf, maximum_features, class_weight (classifier), random_seed, backend and execution_mode.
  • SKDecisionTreeClassifierModel / SKDecisionTreeRegressorModel — the fitted tree plus predict_labels/predict_probabilities or predict, feature_importances, the node count and the configuration carried from the estimator.
  • SKTree / SKTreeNode — the node array and its accessors (split feature and threshold, leaf value, children), so the structure is inspectable.
  • SKTreeCriterion — Gini/entropy for classification, squared/absolute error for regression; using the wrong family is rejected at build time.
  • SKMaximumFeatures — All, Sqrt, Log2, Fraction, Count(n), resolved per node.
  • SKSplitter — Best (exhaustive, deterministic) or Random (seeded).
  • SKClassWeight — None, Balanced, Explicit.

5. A real walk-through, using the tests

dense_scan_recovers_the_separating_split

The simplest correctness statement: on a feature that perfectly separates two classes, the scan finds the threshold between them. Everything else builds on this.

sparse_scan_matches_the_dense_scan and sparse_scan_recovers_the_implicit_zero_split

The first proves the CSC path is equivalent to the dense path on the same logical design. The second proves it actually understands implicit zeros — the case a naive sparse scan would get wrong.

best_split_is_independent_of_feature_order and best_split_breaks_ties_by_smaller_feature

Determinism at the split level: shuffling features must not change the chosen split, and exact ties resolve by feature index.

classifier_sparse_fit_equals_dense_fit / regressor_sparse_fit_equals_dense_fit

The whole estimator, not just the scan: a tree fitted on CSR predicts exactly what the same tree fitted densely predicts.

balanced_weights_equalize_the_class_mass and explicit_weights_can_flip_the_majority_class

Weights are not cosmetic: the test constructs a case where weighting flips the leaf’s prediction, proving the weights reach the impurity and the probability.

one_model_serves_several_threads and parallel_classifier_prediction_equals_sequential

Fitted trees are immutable and Send + Sync; prediction is parallel across rows and equals the sequential answer.

6. Look inside

FileResponsibility
node.rsSKTree, SKTreeNode, traversal and value counting
impurity/Gini/entropy and squared/absolute error
splitter/Best/Random splitters, candidate ordering and the scan
splitter/scan/per-criterion sweeps (classification, squared, absolute, ranked) and boundary selection
growth/growth engine: depth, split and leaf constraints, feature subsampling
classifier/builder, validation, fit, prediction, probabilities, class-weight expansion
regressor/builder, fit, prediction
class_weight/None/Balanced/Explicit expansion
design/dense/CSR/CSC design view and conversion
acceptance_tests/, determinism_tests.rstiny/large, representations, determinism, concurrency

7. What this unlocks

The tree is the base learner for the ensemble wave: random forests subsample features and rows, bagging resamples, and gradient boosting fits trees on residuals. Because the split search is deterministic, seeded and representation-aware, every ensemble inherits those properties for free — and because the sparse scan never densifies, text-scale designs can be boosted without a memory cliff.

Model selection: splits, folds and honest scores

Every number a model reports about itself is only as trustworthy as the data it was measured on. Training accuracy is a lie — the model has already seen those rows. The whole discipline of model selection exists to answer a narrower, honest question: how well would this model perform on data it has never seen?

This chapter builds the machinery for that question: a train/test split, K-fold, stratified K-fold, group K-fold, and cross-validation scoring. All of it is deterministic, seeded, representation-aware and built on one row-gathering primitive.

The capability is model-selection-core; the code lives in crates/sciencekit_model_selection/.

1. The problem, in plain words

You have $n$ labelled rows and a model. To estimate generalisation you must hide some rows from the model while it trains, then score it on them. Three decisions follow:

  1. Which rows are hidden? A random subset is the usual answer, but it must be the same subset every time you rerun, or your comparison between two models is noise.
  2. How many times? Hiding a quarter once gives one estimate. K-fold hides every row once, in $k$ rounds, and averages — a more stable estimate that uses all the data.
  3. What must stay together? With imbalanced classes, a random split can leave a fold with no rare-class example; with grouped data (several rows per patient), splitting a group across train and test leaks information.
flowchart TD
    accTitle: K-fold hides every row exactly once
    accDescr: The rows are partitioned into k disjoint folds. In each round one fold is the test set and the rest train the model. Every row is used for testing exactly once, and the k scores are averaged into one estimate. Shuffling before partitioning is seeded so the folds are reproducible.
    A["n rows"] --> B["Seeded shuffle"]
    B --> C["Partition into k folds"]
    C --> D["Round 1: fold 1 tests"]
    C --> E["Round 2: fold 2 tests"]
    C --> F["… round k: fold k tests"]
    D --> G["k scores"]
    E --> G
    F --> G
    G --> H["Mean score<br/>honest estimate"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class B,C,D,E,F step
    class G,H result

2. The decisions, and the roads not taken

  1. One partition type. Every splitter yields an SKIndexSplit: the training indices and the test indices. Nothing else — no copied features, no boxed closures. Gathering rows is a separate, explicit step.
  2. Seeded Fisher–Yates shuffle. Shuffling uses SKRandomGenerator, so the same random_seed reproduces the same partition. No ambient entropy.
  3. Three K-fold flavours. Plain SKKFold; SKStratifiedKFold, which keeps class proportions per fold and rejects a class with fewer examples than folds; and SKGroupKFold, which never splits a group.
  4. One gather primitive for dense, sparse and targets. sk_gather_rows copies only the selected rows, keeps CSR sparse (no densification) and gathers continuous, integer and nominal targets consistently.
  5. Validation up front. Fractions that consume every row, counts that leave a side empty, k < 2, k > n, a rare class, a group-length mismatch, a target-length mismatch and non-finite values are all rejected with the central error taxonomy before any split is produced.
  6. Cross-validation as a function, not a framework. sk_cross_val_score_classifier and sk_cross_val_score_regressor take a splitter, features, targets and a scorer, then fit a fresh model per fold and score its test rows, returning the per-fold scores. The helper takes no group labels: pre-split grouped data with SKGroupKFold and loop, or use the splitter directly. The builders record execution_mode as configuration; the parallel fold loop always uses rayon, and fold scores are collected in fold order.

Roads not taken. A “shuffle everything at fit time” helper (irreproducible comparisons); a splitter that copies data eagerly (memory waste and a hidden densification risk); stratified sampling by rejection (it can loop forever on rare classes); and a cross-validation trait hierarchy before there is a second use for it.

3. The concepts, taught from zero

Why the same split must come back

Suppose model A scores 0.81 and model B 0.83 on a random split. Is B better? Only if both were scored on the same rows — otherwise the difference may be which rows happened to be hard. Seeding the shuffle makes the partition a pure function of (n, k, seed), so comparisons are fair and a failing test reproduces exactly.

Stratification, in one paragraph

Stratified K-fold assigns rows to folds per class: each class is shuffled and dealt round robin into the folds. Every fold then holds roughly the same class proportions as the whole dataset. If a class has fewer examples than folds, exact stratification is impossible; the splitter rejects the request instead of silently producing empty folds.

Groups, and leakage

If five rows belong to one patient and the patient’s rows appear in both train and test, the model can memorise the patient rather than learn the pattern. SKGroupKFold partitions the groups, then derives the row split from the group assignment. The number of folds defaults to the number of distinct groups, and asking for more is rejected.

Cross-validation, honestly

For each fold: fit a fresh estimator on the training rows, predict the test rows, score them. The result is $k$ numbers. Reporting their mean is the usual summary; reporting all $k$ is more honest, and the API returns all of them.

4. Each public object, explained

  • SKIndexSplit — train() and test() (plus number_of_train_rows and number_of_test_rows), the universal output; SKTrainTestSplit adds train_indices()/test_indices() because it also owns the gathered data.
  • SKSplitter — the contract every splitter implements: split(features, targets, groups) yields index splits.
  • SKKFold / SKKFoldBuilder — number_of_splits, shuffle, random_seed.
  • SKStratifiedKFold / SKStratifiedKFoldBuilder — the same surface, stratifying on the targets.
  • SKGroupKFold / SKGroupKFoldBuilder — groups in, group-preserving folds out.
  • sk_train_test_split / SKTrainTestSplit / SKTrainTestSplitBuilder — fractions (test_fraction), explicit counts (SKPartitionSize), shuffle, random_seed and optional stratify.
  • sk_gather_rows — dense/sparse feature gathering plus target gathering, preserving order and never densifying CSR.
  • sk_shuffle_indices — the seeded Fisher–Yates permutation other changes reuse.
  • sk_cross_val_score_classifier / sk_cross_val_score_regressor — fit-and-score per fold, returning every fold’s score.

5. A real walk-through, using the tests

kfold_test_partitions_are_disjoint_and_exhaustive

The defining property of K-fold: every row is in exactly one test fold, and the union is all rows. If a row were duplicated or dropped, the average would be wrong in a subtle way.

kfold_shuffle_is_seeded_and_reproducible

Two splitters with the same seed produce identical index vectors; a different seed produces a different order. This is what makes a cross-model comparison meaningful.

stratified_every_fold_sees_every_class_in_proportion

A three-class dataset (30/20/10 examples over five folds) must not produce a fold with zero minority examples. The test asserts every fold holds all three classes in the expected proportions ([6, 4, 2]).

group_never_splits_a_group_across_train_and_test

The leakage guarantee: for every group, all of its rows land on the same side of the split.

gather_sparse_features_keeps_csr_without_densifying

Gathering selected rows from a CSR design returns CSR. A naive implementation would call to_dense and pass the small test anyway; this one asserts the representation survives.

cross_validation_parallel_scores_equal_sequential_scores

Folds are independent, so they run in parallel — but the scores must not depend on it.

validation_rejects_non_finite_sparse_features

Missing values are not silently tolerated: a NaN in a stored entry is reported with its position before the split is produced.

6. Look inside

FileResponsibility
index_split.rs, split/splitter.rsSKIndexSplit and the SKSplitter contract
gather/dense/CSR feature gathering and target gathering (target_partition)
shuffle.rsseeded Fisher–Yates
split/kfold/, split/stratified/, split/group/the three K-fold flavours and their builders
train_test_split/fractions, counts, stratification
cross_validation/fit-and-score per fold (fresh model each fold)
split/validation/shared input checks
acceptance_tests/tiny/large, representations, determinism, concurrency, metrics

7. What this unlocks

SKGridSearchCV and the halving search are the next changes in this lane, and they consume exactly this surface: a splitter to produce folds, a scorer to evaluate each candidate, and a seed to keep the comparison fair. Because the splits are index-only and gathering is explicit, a grid search can hold one copy of the data and slice it per candidate instead of cloning it per configuration — which is what makes searching many hyperparameters affordable.

A stable C ABI: handles, ownership and no panics across the boundary

Rust is the implementation language; most of the world is not Rust. A data team calls from Python, a simulation from C or C++, a services team from Go, a research group from Julia or from the JVM. Each of those needs to call the library without reimplementing its own unsafe glue — and without a careless pointer turning a modelling run into a segmentation fault.

This chapter builds the stable C ABI: a small integer-based surface, opaque handles, borrowed inputs, owned outputs, thread-local error messages, panic containment and a C smoke test that compiles and runs against the real shared library.

The capability is ffi-abi; the code lives in crates/sciencekit_ffi/.

1. The problem, in plain words

A C boundary has three hard rules that Rust does not enforce for you:

  1. Nothing may unwind. A Rust panic crossing into C is undefined behaviour. Every entry point must catch it and return a status code.
  2. Ownership must be explicit. Who frees an output buffer? When is a handle valid? Without a written rule, every binding leaks or double-frees.
  3. Pointers may be wrong. Null, misaligned, too short, freed — the library must validate before dereferencing, because the caller’s language cannot express Rust’s guarantees. A misaligned pointer is rejected explicitly: building a typed slice from it is undefined behaviour, and the resulting abort cannot even be caught by catch_unwind.

The ABI also has to erase generics: Rust’s estimators are generic over f32/f64, C has no generics. The answer is a runtime data-type code plus opaque handles.

2. The decisions, and the roads not taken

  1. Opaque handles, never struct layouts. SKFfiBuilder and SKFfiModel are incomplete C types; the binding never knows their size or fields, so the Rust internals can change without breaking the ABI.
  2. Status codes, not exceptions. Every fallible function returns SKFfiStatus; the message travels separately through a thread-local last-error string.
  3. Borrowed inputs, owned outputs. An array passed to the library is borrowed for the call; an array returned by it is owned and released with sk_ffi_array_free (idempotent).
  4. A handle registry. Freed handles are never dereferenced: a registry lookup runs first, so use-after-free returns SK_FFI_STATUS_INVALID_HANDLE.
  5. catch_unwind at every entry point. A panic becomes SK_FFI_STATUS_INTERNAL plus a message, and the process keeps running.
  6. One encoding for persistence. Save/load use the SKModelState contract from sciencekit_common::interop, so the C path and the Rust path agree on what a model is.
  7. A compiled C smoke test. The header is verified by compiling and running real C against the cdylib, not by reading it.

Roads not taken. Exposing Rust structs directly (ABI breakage on every field change); returning Rust Strings (unfreeable from C); panicking on invalid input (undefined behaviour); and a per-language binding in this change (Lua, Go, Julia and the JVM come later, on top of this ABI).

flowchart LR
    accTitle: One C boundary, several language bindings
    accDescr: A C, C++, Go, Julia or JVM caller uses the stable sk_ffi_ functions. Inputs are borrowed arrays, outputs are owned arrays freed by sk_ffi_array_free, and builders and models are opaque handles. Status codes carry failures and a thread-local message carries the text. The same ABI is what every later language binding wraps.
    A["C / C++ / Go / Julia / JVM"] --> B["sk_ffi_* stable functions"]
    B --> C["Opaque handles<br/>builder, model"]
    B --> D["Borrowed input arrays"]
    B --> E["Owned output arrays<br/>sk_ffi_array_free"]
    B --> F["Status codes<br/>+ thread-local message"]
    C --> G["Rust estimators"]
    D --> G
    G --> E
    classDef caller fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef abi fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A caller
    class B,C,D,E,F abi
    class G result

3. The concepts, taught from zero

Opaque handles and a registry

A handle is an opaque pointer to a Rust value. The binding must never dereference it, so the ABI keeps a registry: each handle has a numeric identifier, and every entry point looks the identifier up. Freeing removes it. A second use finds nothing and returns SK_FFI_STATUS_INVALID_HANDLE — no garbage read, no crash.

Borrowed versus owned

For an input, the C caller passes a pointer, a length and a stride description. The library reads it during the call and never stores it. For an output, the library allocates, fills and returns a descriptor; the caller must free it exactly once. sk_ffi_array_free tolerates a second call so a defensive free in a binding is safe.

Panics must not cross

Rust’s unwinding is not compatible with C frames. Each entry point wraps its body in std::panic::catch_unwind, converts the payload into a message, and returns Internal. The test panic_is_converted_to_internal_status installs a panicking path and asserts the process survives with the right status.

Why the ABI erases generics with a code

f32 and f64 estimators are different Rust types. The C surface takes an SKFfiDataType (F32, F64, I64, U8) at builder creation and validates every array against it. That is the whole generics story from C’s point of view: one builder, one data-type code, one model handle.

4. Each public object, explained

  • SKFfiStatus — stable integer codes (OK, INVALID_HANDLE, SHAPE, INVALID_ARGUMENT, UNSUPPORTED, NOT_FITTED, IO, INTERNAL). Never renumbered.
  • SKFfiDataType — F32, F64, I64, U8, checked against every descriptor.
  • SKFfiArray / SKFfiArrayShape / SKFfiOwnedArray — the descriptor, its shape metadata and the owned output wrapper.
  • SKFfiBuilder / SKFfiModel — opaque handles; create, configure, fit, predict, transform, score, free.
  • sk_ffi_last_error — the thread-local message; it is cleared by the next successful call.
  • sk_ffi_version / sk_ffi_features — ABI version and capability bitmask, so a binding can refuse an incompatible library instead of crashing.
  • Persistence — sk_ffi_model_save / sk_ffi_model_load over the shared SKModelState contract. Scope today: fitted linear regression in f64; an f32 model or a scaler returns SK_FFI_STATUS_UNSUPPORTED, as does a state exported by another estimator.

5. A real walk-through, using the tests

panic_is_converted_to_internal_status

A deliberately panicking entry point returns SK_FFI_STATUS_INTERNAL, sets a message and does not abort the process. This is the single most important property of the boundary.

predict_after_free_returns_invalid_handle and handle_use_after_free_is_rejected

Predict through a freed model, or look up a freed builder token: the registry answers INVALID_HANDLE without touching the freed memory. Both tests are safe by construction, which is the point.

boundary_rejects_a_misaligned_data_pointer, …_a_misaligned_shape_pointer and …_a_misaligned_strides_pointer

Each field is checked before it is turned into a typed slice: a pointer offset by one byte is rejected with INVALID_ARGUMENT naming the field, instead of reaching the typed-slice precondition (which aborts rather than unwinds).

array_length_mismatch_is_rejected and boundary_rejects_length_mismatch_before_reading

Before any element is read, the number of elements is checked against the declared shape. A short buffer cannot cause an out-of-bounds read.

persistence_save_and_load_keep_predictions

A fitted model is saved to a file, loaded into a new process-local handle, and predicts the same values. This proves the C path and the Rust SKModelState encoding agree.

The C smoke test (tests/c_smoke.c)

Compiled with cc and linked against the real cdylib, it creates a builder, fits, predicts, scores, saves and loads, exercises the scaler and checks an invalid handle. A header that lies about a signature fails to compile; an ABI that lies about behaviour fails at run time.

version_header_declares_every_entry_point and version_header_declares_no_symbol_outside_the_inventory

The check is bidirectional: every inventory entry appears in the header, and every sk_ffi_* the header declares is in the inventory. Adding an entry point without declaring it — or declaring one that is not implemented — fails a test rather than a user.

6. Look inside

FileResponsibility
abi.rsthe stable ABI constants and the entry-point inventory
handle/the registry and identifier allocation
array/, array/validation/descriptors, shape, length, stride and alignment checks, owned buffers
boundary/the only module that dereferences raw pointers, plus the entry points grouped by area
error.rs, error_kind.rsstatus codes and the thread-local message
model/the model handle and its operations
persistence/the SKModelState file encoding
include/sciencekit.hthe stable C header
tests/c_smoke.cthe compiled end-to-end C test

7. What this unlocks

Every non-Rust binding — Lua, Go, Julia, the JVM — is now a thin wrapper over this ABI rather than a second implementation. The rules that make bindings safe (opaque handles, borrowed inputs, owned outputs, status codes, panic containment) are written once, tested once, and inherited by all of them.

Clustering metrics: silhouette, ARI, NMI and the centroid indices

A clusterer always returns some partition. The question is whether the partition is any good — and unlike supervised learning there are no labels to compare against. Clustering evaluation is therefore a family of proxies, each answering a different question:

  • Silhouette — are points closer to their own cluster than to the next one?
  • Davies-Bouldin and Calinski-Harabasz — how compact and separated are the clusters, judged from centroids and dispersions?
  • Adjusted Rand index, normalized mutual information, homogeneity/completeness/V-measure — when a reference labelling exists, how much do the two partitions agree, with ARI correcting for chance?

This chapter builds all of them, with the dense/sparse parity, noise policy and degenerate-case handling the rest of the library follows.

The capability is clustering-metrics; the code lives in crates/sciencekit_metrics/src/clustering/.

1. The problem, in plain words

Two partitions of the same $n$ rows can be compared in two very different ways.

Internally, without any reference: a good clustering has points near their own centroid and far from the others. The silhouette captures that per point:

$$ s(i) = \frac{b(i) - a(i)}{\max{a(i),, b(i)}} $$

where $a(i)$ is the mean distance from point $i$ to the other members of its cluster and $b(i)$ the mean distance to the members of the nearest other cluster. The value lies in $[-1, 1]$: near $1$ means well inside its cluster, near $0$ on the boundary, negative means it is probably in the wrong cluster.

Externally, with a reference labelling: count how the two partitions agree. The raw agreement is misleading — two random partitions agree by chance, and the chance level grows with the number of clusters. The adjusted Rand index subtracts that expectation, so $0$ means chance and $1$ means identical (up to relabelling).

2. The decisions, and the roads not taken

  1. Chunked pairwise distances. Silhouette needs, per point, the mean distance to every cluster. The pairwise matrix is computed in row chunks and reduced immediately, so peak memory is one chunk instead of $n^2$.
  2. Noise is excluded, explicitly. A Noise assignment has no cluster to be close to, so the silhouette/centroid metrics drop those rows and document it; the pairwise metrics take plain i64 labels and treat noise as an ordinary label.
  3. Chance correction is explicit. The adjusted Rand index subtracts the expected agreement of independent partitions. NMI is not chance-corrected; it is mutual information normalised by the two label entropies (arithmetic, geometric or max), with identical partitions scoring 1.
  4. Homogeneity, completeness and V-measure come from the same contingency table, so the three are consistent with each other by construction.
  5. Degenerate cases are documented, not papered over. Fewer than two clusters, all-noise assignments, singleton clusters, coincident centroids and zero within-cluster dispersion each have a stated answer (rejection, 0, or positive infinity).
  6. Dense and sparse designs score identically, and a wide sparse design is never densified.

Roads not taken. Materialising the full pairwise matrix (memory blow-up); comparing raw agreement without chance correction (favours many clusters); and silently dropping noise in the pairwise metrics (it would hide a modelling decision).

3. The concepts, taught from zero

The silhouette, one point at a time

For point $i$ in cluster $C_i$:

  • $a(i)$ = mean distance to the other points of $C_i$ (a cluster of one has $a(i) = 0$ by convention, and its silhouette is defined as $0$);
  • $b(i)$ = the smallest mean distance to any other cluster.

Then $s(i)$ compares them. Averaging over the non-noise rows gives the mean silhouette.

flowchart TD
    accTitle: The silhouette from pairwise distances
    accDescr: For each point, the mean distance to its own cluster is a, and the smallest mean distance to another cluster is b. The silhouette is (b minus a) divided by the larger of the two, giving a value between minus one and one. Points near one are well inside their cluster, points near zero sit on a boundary, and negative points are probably misassigned.
    A["Point i"] --> B["a: mean distance<br/>to its own cluster"]
    A --> C["b: smallest mean distance<br/>to another cluster"]
    B --> D["s = (b - a) / max(a, b)"]
    C --> D
    D --> E{"value"}
    E -->|"near 1"| F["well inside its cluster"]
    E -->|"near 0"| G["on a boundary"]
    E -->|"negative"| H["probably misassigned"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef bad fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    class A input
    class B,C,D step
    class F,G result
    class H bad

Chance correction, in one paragraph

Suppose both partitions have many small clusters. Even a random labelling will put some pairs together, so raw agreement is high. ARI subtracts the expected agreement and divides by the maximum possible, which is why it can be negative (worse than chance) and why it stays near zero for independent labellings regardless of cluster count. NMI is a different correction: mutual information divided by the two label entropies, so identical partitions score $1$ and independent ones approach $0$ — it is normalised, not chance-adjusted.

The centroid indices

Davies-Bouldin averages, over clusters, the worst ratio of within-cluster spread to between-centroid distance: lower is better, zero for perfectly separated clusters. Calinski-Harabasz is a variance ratio (between-cluster dispersion over within-cluster dispersion, scaled by degrees of freedom): higher is better. Both need centroids; both exclude noise rows for the same reason as the silhouette.

4. Each public object, explained

  • sk_silhouette_samples — the per-point silhouette, in the order of the non-noise rows.
  • sk_silhouette_score — its mean; rejects fewer than two clusters and all-noise input.
  • SKSilhouetteScorer — the scorer adapter over SKUnsupervisedScorer, taking typed assignments and applying the same noise policy as the free function.
  • sk_adjusted_rand_score — chance-corrected pair agreement.
  • sk_normalized_mutual_information_score with SKMutualInformationNormalization — arithmetic, geometric or max normalisation.
  • sk_homogeneity_score, sk_completeness_score, sk_v_measure_score — the three contingency-table views.
  • sk_davies_bouldin_score, sk_calinski_harabasz_score — centroid-based indices.

5. A real walk-through, using the tests

silhouette_samples_exclude_noise_rows

A partition containing Noise rows returns one sample per non-noise row. Noise has no cluster to be close to, so counting it would corrupt the mean.

silhouette_samples_agree_between_dense_and_sparse

The same logical design, once dense and once as CSR, yields the same silhouettes. This is where a hidden densification or a wrong sparse mean would show up.

adjusted_rand_is_invariant_under_label_permutation

Renaming the clusters must not change the score: ARI depends on the partition, not on the labels.

adjusted_rand_matches_the_hand_computed_cross_fixture

A small contingency table is computed by hand; the function must match it exactly. This is what pins the chance-correction formula rather than an approximation of it.

nmi_matches_the_hand_computed_normalization_variants

All three normalisations are checked on the same fixture, so the difference between them is explicit and tested.

davies_bouldin_matches_the_hand_computed_fixture and calinski_harabasz_matches_the_hand_computed_fixture

Both centroid indices are pinned against a hand-computed value; davies_bouldin_is_near_zero_for_separated_clusters and calinski_harabasz_is_large_for_separated_clusters confirm the direction of “better”.

clustering_validation_rejects_a_single_cluster and clustering_validation_rejects_noise_only_input

Degenerate inputs are rejected with a structured error rather than producing a meaningless number.

clustering_large_data_produces_the_expected_verdict and clustering_scorer_is_send_and_sync

Large-data behaviour and thread-safety round out the acceptance checklist.

6. Look inside

FileResponsibility
clustering/silhouette.rsper-sample silhouette, chunked distances, mean score
clustering/adjusted_rand.rschance-corrected pair agreement
clustering/mutual_information.rsNMI with three normalisations
clustering/homogeneity.rshomogeneity, completeness, V-measure
clustering/davies_bouldin.rsDavies-Bouldin index
clustering/calinski_harabasz.rsCalinski-Harabasz index
scorers/clustering.rsSKSilhouetteScorer
acceptance_tests/clustering_acceptance_tests.rslarge data, concurrency, Send + Sync

7. What this unlocks

The clustering lane now has the same evaluation depth as the supervised one: SKKMeans can be compared on internal quality (silhouette, centroid indices) and, when a reference exists, on external agreement (ARI, NMI, homogeneity family); later clusterers inherit the same surface. Because the metrics share the pairwise kernels and the typed-assignment contract, a new clusterer gets all of them without new plumbing.

k-nearest neighbours: a search strategy behind one estimator

k-nearest neighbours is the simplest supervised model in the library and, in production, one of the most useful: no training beyond storing the data, no assumption about the shape of the decision boundary, and a decision you can explain by showing the neighbours. It is also the first estimator whose prediction cost depends on how the data is searched, which is why it sits at the intersection of the geometry chapter and the estimator contracts.

This chapter builds SKKNeighborsClassifier and SKKNeighborsRegressor: the brute-force searcher, the runtime strategy dispatch, weighting, voting and probabilities, and the representation parity that lets a sparse design be classified without densification.

The capability is nearest-neighbor-estimators; the code lives in crates/sciencekit_neighbors/.

1. The problem, in plain words

To classify a query row:

  1. find its $k$ nearest training rows;
  2. let them vote.

With $k = 5$ and three of the neighbours in class A, the prediction is A, and the estimated probability is $3/5$. For regression, take the mean of the neighbours’ responses. Optionally, weight each neighbour by inverse distance so a very close neighbour counts more.

Two engineering questions decide the quality of the implementation:

  • How do you find the neighbours? A k-d or ball tree is fast on dense, low-dimensional data; brute force is the honest fallback for sparse, high-dimensional or cosine data.
  • What happens when the neighbours are tied? Both the neighbour list and the vote need a deterministic rule, or the model is irreproducible.

2. The decisions, and the roads not taken

  1. One contract, three searchers. The brute-force searcher joins the k-d tree and ball tree behind SKNearestNeighborsSearcher, so the estimator can swap them at run time.
  2. Auto picks by representation and metric. Dense Euclidean/Manhattan/Chebyshev data uses a tree; sparse, mixed or cosine data uses brute force. An explicit tree request on a representation the tree cannot serve returns UnsupportedRepresentation.
  3. Sparse is never densified. The brute-force searcher computes distances over the stored entries plus the implicit zeros using the shared pairwise kernels.
  4. Deterministic neighbours and votes. Neighbours are ordered by distance then the smallest training index (inherited from the searcher contract); a vote tie goes to the smallest canonical class index.
  5. Two weighting modes. Uniform (plain vote/mean) and Distance (inverse distance); a zero-distance neighbour is handled by the documented convention so weights stay finite.
  6. Typed targets, scalar-independent labels. Integer and nominal targets go through SKLabelTable; predict_labels returns canonical i64 indices and predict_probabilities returns the model scalar.

Roads not taken. A single searcher with a runtime branch inside the distance loop (slow and error-prone); densifying sparse queries (memory cliff on text data); random tie-breaking (irreproducible models); and a separate classifier per weighting mode (combinatorial surface).

flowchart TD
    accTitle: One estimator, a runtime search strategy
    accDescr: The estimator's Auto policy inspects the representation and the metric. Dense Euclidean, Manhattan or Chebyshev data goes to the k-d or ball tree; sparse, mixed or cosine data goes to the brute-force searcher. Both implement the same contract and return neighbours ordered by distance then training index, so voting and probability estimation are identical.
    A["fit / predict"] --> B{"representation and metric"}
    B -->|"dense, tree metric"| C["KD-tree or ball tree"]
    B -->|"sparse, mixed or cosine"| D["Brute-force searcher"]
    C --> E["Neighbours<br/>distance, then index"]
    D --> E
    E --> F["vote / mean / inverse-distance"]
    F --> G["labels, probabilities or responses"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class B,C,D,E,F step
    class G result

3. The concepts, taught from zero

Why the representation changes the algorithm

A k-d tree prunes by comparing coordinates; its bounding boxes have no meaning when most coordinates are implicit zeros. Brute force does not care: it computes the distance to every training row using only the stored entries, in $O(\text{nnz})$ per pair. So the same estimator is fast on dense low-dimensional data and correct on sparse high-dimensional data — the representation chooses the strategy, not the user.

Uniform and distance weighting

Uniform voting counts neighbours. Inverse-distance weighting uses $1/d$ (with the zero-distance case handled explicitly), so the nearest row dominates. Both are legitimate; the choice belongs in the builder, and the probabilities must still sum to one.

Ties are a specification, not an accident

Two equidistant neighbours, or two classes with the same vote, need an order. The searcher guarantees distance-then-index ordering; the vote breaks ties by the smallest canonical class index. Both are tested, because a nondeterministic tie would make cross-validation scores depend on hash-map iteration order.

4. Each public object, explained

  • SKKNeighborsClassifier / SKKNeighborsClassifierBuilder — nearest_neighbors_count (default 5), weights (Uniform/Distance), algorithm (Auto/KdTree/BallTree/ BruteForce), metric (Euclidean/Manhattan/Chebyshev/Cosine), leaf_size, backend, execution_mode.
  • SKKNeighborsRegressor / SKKNeighborsRegressorBuilder — the same surface for responses.
  • Fitted models — implement SKClassifierPredictor (labels + probabilities) or SKRegressorPredictor, and expose the class table, the training row/feature counts, the resolved search strategy and the carried backend.
  • SKNeighborsAlgorithm, SKNeighborsWeights, SKNeighborsMetric — the closed catalogues of choices.
  • SKBruteForceSearcher — the sparse-aware searcher implementing the shared contract.

5. A real walk-through, using the tests

brute_force_* agreement with the k-d tree

The brute-force searcher is checked against the tree on the same dense data: same distances, same indices, same order. The new searcher never gets to invent a different answer.

representation_* dense/sparse parity

The estimator fitted on CSR predicts the same labels as the one fitted densely, and the mixed combinations (dense fit / sparse predict and the reverse) agree too. This is the representation parity rule applied to an estimator whose search depends on it.

classifier_probabilities_*

Probabilities are neighbour fractions (or weighted fractions) and must sum to one; the columns follow the canonical class table, which records classes in first-occurrence order.

acceptance_knn_equidistant_neighbors_*

Equidistant neighbours produce a deterministic list and a deterministic vote, so the prediction cannot drift between runs.

acceptance_knn_large_* and concurrency_*

A 20 000-row acceptance case, the dense/sparse/mixed combinations exercised elsewhere in the suite, and a fitted model shared across threads with the same predictions as a single thread.

validation_rejects_*

Zero or excessive neighbour counts, feature-count mismatch, non-finite values and unsupported metric/algorithm pairs are rejected with the central error taxonomy.

6. Look inside

FileResponsibility
neighbors/brute_force/sparse-aware brute-force neighbour search
classifier/builder, fit, labels, probabilities, target canonicalization
regressor/builder, fit and response prediction
neighbors/algorithm.rs, neighbors/weights.rs, neighbors/metric.rsthe closed catalogues and Auto resolution
neighbors/{configuration,index,search,training_data,validation}.rsstored configuration, strategy resolution, query search and validation
acceptance_tests/tiny/large, representations, ties, parallelism, metrics

7. What this unlocks

The neighbours estimators complete the representation-parity story that the trees began: dense queries use geometry, sparse queries use brute force, and the user sees one estimator either way. They are also the natural consumer of the clustering metrics and the model-selection splits, which is why this lane can now evaluate itself end to end. The next neighbour change (knn-imputer) reuses the same searcher to fill missing values from the nearest complete rows.

The k-NN imputer: filling a hole from the nearest complete rows

SKSimpleImputer fills a missing value from the column’s own statistic — mean, median, mode, constant. That is cheap and often enough. It is also blind: a 90-year-old’s missing income is replaced by the average income of everyone, including teenagers. The k-nearest-neighbour imputer makes the fill local: it finds the training rows most similar to the incomplete row and averages the values those rows hold in the missing column.

This chapter builds SKKNNImputer: the missingness mask, the NaN-aware donor search, the weighting and fallback rules, the optional missingness indicator, and the memory bound that keeps a large transform affordable.

The capability is nearest-neighbor-imputation; the code lives in crates/sciencekit_impute/src/knn/.

1. The problem, in plain words

For a row with a missing cell in column $j$:

  1. compare it to every training row that has a value in column $j$;
  2. keep the $k$ closest such rows (the donors);
  3. fill the cell with their mean, or an inverse-distance weighted mean.

“Closest” needs a distance that ignores the missing coordinates on both sides: a row is not far away just because the column you are about to fill is empty. The documented metric is the NaN-aware Euclidean distance, which compares only co-observed features and scales by the fraction of features observed in both rows.

flowchart TD
    accTitle: Filling one missing cell from its nearest complete donors
    accDescr: The incomplete row is compared with every training row that has a value in the missing column, using a distance that only compares features both rows observe. The k smallest distances become the donors, and their values are averaged uniformly or weighted by inverse distance. If no donor has a finite distance, the column mean is used instead.
    A["Row with a missing cell<br/>in column j"] --> B["Candidate donors:<br/>training rows with column j observed"]
    B --> C["NaN-aware Euclidean distance<br/>co-observed features only"]
    C --> D["k smallest distances<br/>ties by training index"]
    D --> E{"finite distance?"}
    E -->|"yes"| F["uniform or inverse-distance mean"]
    E -->|"no"| G["column mean fallback"]
    F --> H["Imputed cell"]
    G --> H
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef fallback fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class B,C,D step
    class G fallback
    class F,H result

2. The decisions, and the roads not taken

  1. One marker predicate, shared with SKSimpleImputer. NaN, a scalar sentinel (e.g. -999) or any configured value identifies a missing cell; the same predicate drives fit and transform, so the two imputers cannot disagree about what “missing” means.
  2. Column-wise donor pools. A row can only donate to a column it observes, so the pool for column $j$ is the training rows with $j$ present. This is both correct and cheaper than a full $n \times m$ neighbour search.
  3. Chunked distance blocks. The donor distances are computed in blocks sized by a byte budget, so a transform never materialises the full receiver × training matrix.
  4. Deterministic donor selection. The $k$ smallest distances are selected with a partial selection; ties break by the smallest training row index — the same rule as the neighbours searchers.
  5. Two weighting modes and an explicit fallback. Uniform and Distance; a zero-distance donor takes the whole weight; when no distance is finite (no co-observed feature), the column mean fills the cell.
  6. Dense-only, stated up front. The donor search needs a dense missingness mask; a sparse design is rejected with UnsupportedRepresentation rather than silently densified.
  7. The indicator composes. add_indicator appends the missingness mask after the imputed features, tolerating missingness patterns unseen at fit.

Roads not taken. Reusing the spatial-tree index (missing coordinates break its bounding boxes); a full pairwise matrix (memory); random donor selection (irreproducible fills); and densifying sparse input to reuse the dense path.

3. The concepts, taught from zero

Why the distance must ignore missing coordinates

Classic Euclidean distance treats a missing value as impossible to compare, so it either fails or substitutes a number (often zero), which invents a distance. The NaN-aware form instead computes the squared distance over the features both rows observe and multiplies it by $\text{total}/\text{observed}$ (so the distance scales by $\sqrt{\text{total}/\text{observed}}$), so two rows that happen to share only one feature are not treated as artificially close; the rescale restores the scale of a full-feature comparison. If two rows share no observed feature, the distance is NaN — and a NaN donor is never averaged in.

Why the donor pool is per column

The value you need comes from a column the donor must actually have. Restricting the pool to rows that observe column $j$ removes every donor that would contribute another hole, and makes the search smaller.

The memory bound

A naive transform computes one distance per (receiver row, donor) pair. With a 100 000-row training set and a 100 000-row batch that is $10^{10}$ numbers. The implementation processes receiver rows in blocks sized against a byte budget, so peak memory is bounded regardless of the input size; the block plan is tested directly (knn_distance_block_rows_stays_within_the_byte_budget).

4. Each public object, explained

  • SKKNNImputer<F> / SKKNNImputerBuilder<F> — builder-only configuration: missing_values, nearest_neighbors_count (default 5), weights (Uniform/Distance), add_indicator, keep_empty_features, backend (default Faer) and execution_mode.
  • SKKNNImputerModel<F> — the learned state: the retained training design with missing cells normalised to NaN, the mask, the valid columns, the per-column means and the donor pools. It implements SKFeatureTransformer, which is what transform is.
  • Marker and mask — the shared predicate and the dense missingness mask.
  • Distance blocks and donor selection — the NaN-aware kernel and the partial selection.
  • Weights and averaging — uniform, inverse-distance, zero-distance and mean fallback.

5. A real walk-through, using the tests

knn_transform_imputes_a_known_matrix

A tiny matrix whose answer can be computed by hand: the missing cell is the mean of its two nearest donors. This pins the whole pipeline — mask, pool, distance, selection, average.

knn_transform_preserves_observed_cells_bit_identically

Imputation must never perturb a value that was present — with one documented exception: a column that was all-missing at fit and kept by keep_empty_features is emitted as zero for every row, including a row that observes it. A bit-identical assertion on the normal columns catches any accidental re-scaling or recomputation.

knn_transform_keeps_a_retained_empty_column_at_zero

An all-missing column kept by keep_empty_features produces zeros, even for a receiver that observes it — the documented exception to “observed cells are untouched”.

knn_transform_falls_back_to_the_column_mean_without_a_comparable_donor

When no donor shares an observed feature (all distances NaN), the documented fallback applies instead of writing NaN or panicking.

knn_marker_predicate_is_the_shared_one

The k-NN imputer and SKSimpleImputer share one marker predicate in missingness. The test pins the predicate’s semantics (the NaN, scalar and categorical cases); the two estimators import the same function, so a sentinel configured in one cannot be interpreted differently by the other.

knn_validation_rejects_sparse_fit_input and …_sparse_transform_input

The dense-only contract is enforced on both entry points, before any mask is built, with a suggestion rather than a silent densification.

acceptance_knn_imputer_fits_ten_thousand_rows_and_transforms and …_large_transform_is_deterministic

Large data stays correct and repeatable; the block plan does not introduce order dependence.

acceptance_knn_imputer_produces_a_low_imputation_error

A planted missing pattern is imputed and compared against the known truth, so the test measures quality, not just shape.

6. Look inside

FileResponsibility
knn/builder.rs, knn/mod.rsbuilder surface and the pure dispatcher
knn/marker.rs, knn/fit.rsshared missingness mask and the retained training state
knn/distance_block.rs, knn/donors.rschunked NaN-aware distances and k-smallest selection
knn/weights.rs, knn/transform.rsweighting, averaging, fallback and the row-parallel transform
knn/validation.rsdense-only contract and input validation
knn/acceptance_tests/tiny, large, patterns, metrics and concurrency

7. What this unlocks

With SKKNNImputer, the imputation lane covers both ends of the spectrum: cheap column statistics and local, similarity-driven fills. The shared marker, mask and indicator semantics mean the two imputers compose in a pipeline without surprises, and the chunked design shows how a neighbour search can stay inside a memory budget — a pattern the remaining out-of-core work reuses.

Grid search: trying every candidate honestly

Hyperparameters are not learned from the data; they are chosen. Choosing them well means answering the same question model selection already taught us — “how well would this configuration generalise?” — once per candidate, on the same folds, and then committing to the one that wins.

This chapter builds SKGridSearchCVClassifier and SKGridSearchCVRegressor: the candidate enumeration, cross-validated scoring, deterministic winner selection, the refit, and the result surface a caller inspects afterwards.

The capability is grid-search; the code lives in crates/sciencekit_model_selection/src/grid_search/.

1. The problem, in plain words

You have a model class, three values of alpha and two values of tolerance. That is six candidates. Grid search:

  1. enumerates the six configurations;
  2. for each one, runs the same K-fold split and scores every fold;
  3. aggregates each candidate’s fold scores into a mean (and a spread);
  4. picks the highest mean, breaking ties deterministically;
  5. optionally refits the winner on all the data so it can predict.

Every step has a trap. Different folds per candidate make the comparison unfair. A nondeterministic tie makes runs disagree. Averaging scores from different scales (accuracy and log loss) is meaningless. And a candidate that fails on one fold must not silently disappear.

flowchart TD
    accTitle: Grid search over a shared fold partition
    accDescr: A list of configured candidates and one splitter produce a shared fold partition. Every candidate is fitted and scored on every fold, producing a score matrix of candidates by folds. Each candidate's mean and standard deviation are computed, the highest mean wins with ties broken by candidate order, and the winner is optionally refitted on all rows to produce the final model.
    A["Candidate list<br/>(fully configured estimators)"] --> C["Shared folds<br/>from one splitter"]
    C --> D["Score matrix<br/>candidate × fold"]
    D --> E["mean and standard deviation per candidate"]
    E --> F["best mean<br/>ties by candidate index"]
    F --> G{"refit?"}
    G -->|"yes"| H["Refit the winner on all rows"]
    G -->|"no"| I["results only<br/>prediction disabled"]
    H --> J["Fitted models + predictions"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#2c6e49
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A,C input
    class D,E,F,G step
    class H,I,J result

2. The decisions, and the roads not taken

  1. Candidates are configured estimators, not string maps. A candidate is a fully built SKDecisionTreeClassifier (or any SKSupervisedFit estimator) with its hyperparameters already set. Type safety replaces a HashMap<String, String> and a runtime parser.
  2. One splitter, one fold partition. The splitter runs once; every candidate is scored on the same indices, so differences come from the configuration, not from the data.
  3. Classification and regression scoring are separate enums. SKClassifierScoring (Accuracy, BalancedAccuracy, F1, Precision, Recall, Auc, LogLoss) and SKRegressorScoring (R2, NegativeMeanSquaredError, NegativeMeanAbsoluteError) make a regressor scorer on a classifier unwritable at compile time.
  4. Errors are a policy. SKErrorScore::Raise propagates the first failing fold; SKErrorScore::Value(v) records v for that fold and continues. A NaN error score is ordered below every finite mean, so a broken candidate can never win.
  5. Deterministic winner. Highest mean wins; an exact tie goes to the earliest candidate in the list.
  6. Refit is explicit. With refit(true) the winner is fitted on all rows and the result exposes prediction; without it, results are available but prediction is rejected.
  7. Parallel and order-preserving. Candidates (and folds) run in parallel, but the score matrix, ranking and best index are collected in declaration order.

Roads not taken. Random search (a different change), string-keyed parameter grids (untyped and unvalidated), a separate scorer passed as a trait object (loses the classifier/regressor split), and refitting every candidate (wasted work — only the winner is deployed).

3. The concepts, taught from zero

Why the folds must be shared

If candidate A is scored on folds ${1,2,3}$ and candidate B on ${2,3,4}$, the difference in mean score may be the difference between those folds. Grid search therefore asks the splitter once and replays the same index splits for every candidate.

The score matrix

The evaluation produces a $C \times K$ matrix: $C$ candidates, $K$ folds. Row means are the selection criterion; the population standard deviation is reported alongside because a candidate that is excellent on average but wildly variable is often not what you want to deploy.

Error policies, from zero

A candidate can fail: a fold may not contain a class the scorer needs, or a solver may not converge. Silently dropping such a candidate biases the search. Raise stops and tells you; Value(v) lets the search continue with a penalty. The penalty is the caller’s declaration: it must be worse than any score a healthy configuration could reach under the chosen metric (for example -1e9 under negative MSE, or NaN, which is guaranteed to rank below every finite mean). Choosing 0 under a negative metric would let a failing candidate win — that is the documented contract, not a hidden guarantee.

4. Each public object, explained

  • SKGridSearchCVClassifier<F, E> / SKGridSearchCVRegressor<F, E> — the search estimators, built through SKGridSearchCVClassifierBuilder / …RegressorBuilder with candidates, splitter, scoring, error_score, refit, backend, execution_mode.
  • Result accessors — results(), mean_scores(), best_index(), best_candidate_index(), best_parameters() (the winning configured candidate), best_score(), ranked_candidate_indices() and best_model().
  • Fitted models — SKGridSearchCV…Model, which predict by delegating to the refitted best model.
  • SKClassifierScoring / SKRegressorScoring / SKErrorScore — the closed policy catalogues.

5. A real walk-through, using the tests

grid_evaluation_* — the hand-computed matrix

A tiny three-candidate, five-fold fixture whose score matrix can be computed by hand. This pins fold sharing, ordering and aggregation in one test.

grid_selection_*

mean and population standard deviation, the highest mean winning, and an exact tie going to the earlier candidate. A mean is easy; the tie rule is what makes a search reproducible.

grid_errors_*

Raise propagates, Value records per failing fold, and a healthy candidate beats a penalised one. The numeric-policy test uses -999.0 to prove a declared penalty is recorded, and the acceptance suite uses NaN to prove a NaN penalty ranks below every finite mean.

grid_refit_* and grid_predict_*

With refit, the winner is fitted on all rows and prediction delegates to it; without refit, prediction is rejected. Labels, probabilities and responses match the best model exactly.

grid_representation_*

A sparse design is scored and predicted without densification; dense and sparse folds agree.

grid_concurrency_*

Prediction without refit is blocked; a refitted model is shared across eight threads with the same results.

grid_acceptance_*

Tiny and large data, every scoring policy, K-fold/stratified/group splitters, thread-count determinism, and the composition of an error policy with refit.

6. Look inside

FileResponsibility
grid_search/builder/classifier and regressor builders, configuration, validation
grid_search/scoring/the classifier/regressor scoring enums and fold-scorer seam
grid_search/evaluation/parallel candidate × fold evaluation
grid_search/results.rsaggregation, ranking and best selection
grid_search/error_score.rsthe Raise/Value policy
grid_search/classifier/, grid_search/regressor/refit, prediction delegation, models
acceptance_tests/grid_search/tiny/large, policies, splitters, determinism, metrics

7. What this unlocks

A grid search turns a model class into a searchable space, and it does so on the same honest folds the rest of the lane uses. The halving search next builds on this shape — same candidates, same scoring, same error policy — and adds successive halving to spend fewer folds on hopeless configurations.

Lua bindings: embedding Lua, not requiring it

Lua is a small, fast scripting language designed to be embedded in a host program. That word is the whole design brief for this change: a Lua user should require("sciencekit") and call the library, and an operator should not have to install a Lua interpreter, a development package, or a matching liblua before the module builds.

This chapter builds the Lua binding: the embedded interpreter, the module entry point, userdata for builders and models, table↔matrix conversion, error mapping, lifecycle and packaging.

The capability is lua-bindings; the code lives in its own repository, neurono-ml/sciencekit-lua, as the standalone Cargo project sciencekit_lua. The main repository keeps the Rust core and the shared C ABI (sciencekit_ffi) that the crate consumes through a git dependency.

1. The problem, in plain words

A native binding has to answer five questions:

  1. Where does Lua come from? If the answer is “the system”, every deployment becomes a compatibility puzzle (liblua5.4 present? correct ABI? headers installed?).
  2. How does a Lua table become a matrix? Lua has no arrays of numbers; it has tables that can hold anything, including ragged rows.
  3. What owns the model? A Lua value is garbage-collected; a C handle is not. Something must free the handle exactly once.
  4. How do errors surface? A status code is invisible to a script; the failure must become a Lua error with a readable message.
  5. How is it packaged? A module that cannot be installed is a demo, not a binding.
flowchart LR
    accTitle: An embedded Lua module over the C ABI
    accDescr: A Lua script calls require on the sciencekit module. The module is a native library that embeds Lua 5.4 compiled from source, so no system interpreter is needed. Calls become userdata operations over the C ABI, arrays are copied between Lua tables and numeric buffers, and ABI status codes are raised as Lua errors. The garbage collector and an explicit close release the handles exactly once.
    A["Lua script<br/>require('sciencekit')"] --> B["Native module<br/>embeds Lua 5.4"]
    B --> C["Userdata<br/>builders and models"]
    C --> D["sciencekit_ffi<br/>C ABI in process"]
    D --> E["Rust estimators"]
    C --> F["Lua tables ↔ f64 buffers<br/>(copy semantics)"]
    D --> G["status code + message"]
    G --> H["Lua error with code and text"]
    classDef script fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef module fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef engine fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#4c1d95
    classDef error fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    class A script
    class B,C,D module
    class E,F engine
    class G,H error

2. The decisions, and the roads not taken

  1. mlua with lua54 + vendored. Lua 5.4 is compiled from source into the module. The build needs a C compiler (already required by the workspace) and nothing else.
  2. Reuse the C ABI in process. The module calls sciencekit_ffi, so a Lua call exercises exactly the code path a C consumer sees — no second implementation to drift.
  3. One entry point written by hand. mlua’s module feature cannot be combined with vendored, so luaopen_sciencekit is written explicitly over the entry-point constructor.
  4. Copy semantics, stated plainly. A Lua table is copied into a contiguous f64 buffer and outputs are fresh tables of rows. No zero-copy is promised across a garbage-collected, dynamically typed value.
  5. f64 only. Lua 5.4 numbers are IEEE-754 doubles; accepting f32 descriptors would add rounding without saving memory.
  6. Double lifecycle control. Userdata frees its handle on garbage collection (Drop), and an explicit close() releases it early; both are idempotent, and a live-handle counter makes double-free testable.
  7. Errors are Lua errors. An ABI status plus the thread-local message becomes a Lua error carrying the status name and code, so pcall sees something actionable.
  8. A rockspec and a Lua test suite. Packaging is part of the change, not an afterthought.

Roads not taken. Linking the system liblua (deployment friction); LuaJIT FFI (a different ABI); implementing estimators directly in the binding (duplication); and promising zero-copy through Lua tables (impossible without pinning the value).

3. The concepts, taught from zero

What “vendored” means

A C library is normally found on the system at build time (pkg-config, headers, a shared object). Vendoring ships the C sources inside the Rust crate and compiles them with the cc crate. The result is a static copy linked into the module: the same build works on a machine with no Lua installed, and the module does not care which liblua the loader might find.

Userdata and garbage collection

A Lua userdata is an opaque value whose memory is managed by Lua’s collector. The binding stores a handle inside it and implements the destructor; when the value becomes unreachable the collector calls it and the handle is freed. Because the collector’s timing is not defined by the script, an explicit close() gives deterministic release for long-running processes. Both paths funnel into the same idempotent free.

Tables as matrices

A matrix is a table of rows, each row a table of numbers. The conversion validates rectangularity (every row the same length), rejects non-numeric cells with the offending position, and copies into a row-major buffer. On the way out, every row becomes a fresh table. That is a copy in both directions, and the README says so.

4. Each public object, explained

  • The module table — require("sciencekit") returns constructors (linear_regression(), standard_scaler()), version, abi_version() and features().
  • Builder userdata — chainable setters (include_intercept, with_mean, with_std, backend), fit(...), and close().
  • Model userdata — predict, transform, score, save, load, close.
  • Conversion helpers — table → SKFfiArray, SKFfiArray → table, with rectangularity and numeric-cell validation.
  • Error mapping — the ABI status name/code and message as a Lua error.

5. A real walk-through, using the tests

module_loads_through_require

The module registers itself and require returns a table. If the embedded interpreter or the entry point is wrong, nothing else can run.

module_reports_abi_version_and_features

The script can interrogate the library before using it, which is what a production binding needs to refuse an incompatible binary instead of failing deep inside a fit.

convert_rejects_ragged_table and the non-numeric case

Ragged rows and string cells are rejected with a position, not silently coerced. A scripting language makes malformed input easy; the boundary must be strict.

userdata_close_is_idempotent_and_rejects_further_use and errors_gc_after_close_does_not_double_free

Release is safe from both the explicit and the collector path. The live-handle counter makes the leak/double-free assertions observable.

operations_linear_regression_fits_predicts_and_scores and operations_standard_scaler_transforms_with_the_expected_shape

The end-to-end path for both families, through tables, exercising the ABI underneath.

concurrency_shared_model_predicts_deterministically and concurrency_independent_vms_fit_and_predict

Several Lua states can use the library at once; a model shared in one state predicts deterministically across calls.

The Lua suite (tests/run.lua)

Run with the system Lua 5.4 from the devcontainer against the built library, it covers module metadata, both estimator families, persistence, structured errors and the single-free lifecycle. It is the “can a Lua user actually use this” test.

6. Look inside

The files live in the neurono-ml/sciencekit-lua repository, at its root:

FileResponsibility
src/lib.rs, src/module.rsthe module entry point and exports
src/userdata/builder/model handles, setters, close, GC
src/convert.rstable ↔ buffer conversion and rectangularity
src/operations.rsfit/predict/transform/score/save/load wiring
src/errors.rsABI status → Lua error mapping
Cargo.tomlthe standalone project and its git dependency on sciencekit_ffi
tests/run.lua, sciencekit-*.rockspecthe Lua suite and packaging

7. What this unlocks

The Lua lane is the first binding on top of the C ABI, and it validates the ABI’s design: an embedded interpreter, copied arrays, structured errors and a deterministic lifecycle are enough to expose the library to a scripting language. The Go and JVM bindings follow the same shape, with their own garbage collectors and packaging.

Go bindings: cgo over a stable C ABI

Go is the language of infrastructure and data tooling, and it is unusually good at what a machine-learning binding needs: explicit errors, predictable lifetimes and cheap concurrency. It also has cgo, which lets Go call C directly — and that is both the opportunity and the hazard. The binding must wrap the ABI without leaking a single handle, without copying unsafe pointers into Go memory, and without hiding the status codes that the ABI was built around.

This chapter builds the Go module: a typed layer over sciencekit_ffi with builders, models, matrices, structured errors and a lifecycle that survives a garbage collector.

The capability is go-bindings; the code lives in its own repository, neurono-ml/sciencekit-go, as the module github.com/neurono-ml/sciencekit-go. The main repository keeps the Rust core and the shared C ABI (sciencekit_ffi) that the module links against.

1. The problem, in plain words

A Go value is managed by the Go runtime; a C handle is not. cgo crosses that boundary, and the crossing has four rules:

  1. C memory is not Go memory. A pointer returned by C must never be stored in a Go pointer that the collector may move or free.
  2. The collector may run at any time. A model that becomes unreachable must release its handle — but only once, even if Close also runs.
  3. cgo calls are cheap but not free. A builder must be safe when several goroutines use it.
  4. Errors must stay errors. The ABI communicates through integer status codes; the binding must turn them into Go errors carrying the code, without inventing a second taxonomy.
flowchart LR
    accTitle: A Go model over cgo and the C ABI
    accDescr: A Go program builds a model through typed builders. cgo copies a Go matrix into a C-owned descriptor buffer, because storing a Go pointer in C memory is forbidden. The C ABI performs the operation and returns a status. The binding copies the output back into Go memory, maps the status to a Go error carrying the code and message, and releases handles through Close or a finalizer exactly once.
    A["Go program<br/>Matrix[T], builders"] --> B["cgo boundary"]
    B --> C["C descriptor<br/>C-owned copy + shape"]
    C --> D["sciencekit_ffi<br/>status code"]
    D --> E["copy output into Go memory"]
    D --> F["status → ScienceKitError<br/>(code + message)"]
    G["Close / finalizer"] --> H["handle released once"]
    classDef go fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef c fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef error fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef life fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A go
    class B,C,D,E c
    class F error
    class G,H life

2. The decisions, and the roads not taken

  1. Typed generics, one C surface. Matrix[T] and the builders are generic over Float (float32, float64), while the ABI sees a data-type code. Go’s type system carries the scalar; C never does.
  2. C-owned copies. A matrix is copied into a C.malloc buffer (shape and data) for the call and freed after it. No Go pointer is ever stored in C memory, which is what the cgo pointer rules require; GOEXPERIMENT=cgocheck2 enforces it in CI.
  3. Explicit Close plus a finalizer. Both funnel into one idempotent release guarded by a mutex, and a live-handle counter makes double-free and leaks testable.
  4. Errors carry the ABI code. ScienceKitError exposes Status and Message, and IsStatus(err, status) lets a caller branch on the error kind without string matching.
  5. Go-side validation before the boundary. Ragged matrices, wrong target counts, empty paths and unknown backends are rejected in Go with ordinary errors; the ABI only sees valid input.
  6. A build script and a CI job. Linking a cdylib needs flags; the repository ships a script and a workflow, so “it compiles on my machine” is not the test.

Roads not taken. A pure-Go reimplementation (drift), storing C pointers inside Go structs (collector hazards), panicking instead of returning errors (un-Go-like), and a single non-generic API returning []float64 (loses f32 without simplifying anything).

3. The concepts, taught from zero

cgo in one paragraph

import "C" lets Go call C functions declared in a preamble. The call itself is a real function call with a stack switch; the expensive part is the boundary crossing and the copy. The cgo pointer rules forbid passing a Go pointer that contains another Go pointer, which is why a matrix is copied into a C buffer rather than handing the Go slice directly.

Why cgo needs a C-owned copy

The cgo pointer rules forbid storing a Go pointer inside C memory. A descriptor whose data field points at a Go slice — even one kept alive with runtime.KeepAlive — violates that rule, because KeepAlive only extends reachability; it does not pin the object or make the pointer safe to store in C. The binding therefore allocates the shape array and the data buffer with C.malloc, copies the values in, and frees both after the call. GOEXPERIMENT=cgocheck2 turns any remaining violation into a runtime abort, which is why CI runs the suite in that mode.

Finalizers are a safety net, not a lifecycle

A finalizer runs on the collector’s schedule, possibly never. It protects against a forgotten Close, but deterministic code calls Close. The binding implements both with the same idempotent release, so the finalizer can never double-free.

4. Each public object, explained

  • NewMatrix(rows, columns, data) / Matrix[T] — shape validation and a typed dense matrix.
  • NewLinearRegressionBuilder[T]() with IncludeIntercept, Backend, Fit, Close, and NewStandardScalerBuilder[T]() with WithMean, WithStd, Backend, Fit, Close.
  • LinearRegressionModel[T] — Predict, Score, Save, Close; StandardScalerModel[T] — Transform, Save, Close.
  • ScienceKitError, Status, IsStatus — the error surface with the ABI codes.
  • VersionInfo and the package-level version/feature functions — ABI introspection at init.

5. A real walk-through, using the tests

TestLinearRegressionFitPredictAndScore

The end-to-end path through cgo: matrix → descriptor → fit → predict → score, with the known linear fixture and $R^2 \approx 1$.

TestLinearRegressionFloat32

The generic surface is real: an f32 matrix goes through the same code with the F32 data-type code and comes back as []float32.

TestDescriptorRejectsMalformedMatrix and TestNewMatrixRejectsBadShapes

Malformed input never reaches C: ragged data, zero columns and inconsistent lengths are Go errors, so the ABI is only asked to do valid work.

TestBuilderFinalizerReleasesHandle and TestModelFinalizerReleasesHandle

A value dropped without Close still releases its handle, observed through the live-handle counter. The test proves the safety net works and that it runs once.

TestConcurrentCloseAndPredict

A Close racing a prediction is the classic use-after-free. The binding serialises it with a mutex: either the prediction completes, or it returns a closed-handle error — never a crash.

TestConcurrentFitSerializesOneBuilder

One builder used from several goroutines is serialised; the ABI builder is mutable, so the binding owns the lock rather than hoping the C side is thread-safe.

TestPersistenceRoundTrip and TestSaveRejectsUnsupportedModels

The ABI’s persistence scope (f64 linear regression) is surfaced honestly: a supported model round-trips, an unsupported one returns UNSUPPORTED rather than writing a broken file.

The devcontainer run

The whole suite runs inside the devcontainer (go test ./...) against a release cdylib, plus go vet, gofmt -l, go test -race and GOEXPERIMENT=cgocheck2 go test ./..., which is what the CI job reproduces.

6. Look inside

The files live in the neurono-ml/sciencekit-go repository, at its root:

FileResponsibility
cgo.gothe cgo preamble, native handles and descriptors
builders.go, models.gotyped builders and models, Close and finalizers
types.goMatrix[T], Float, BackendKind validation
errors.goScienceKitError, Status, IsStatus
version.goABI version and feature introspection
include/sciencekit.hthe vendored copy of the stable C ABI header
README.md, scripts/build-native-library.sh, scripts/sync-header.sh, .github/workflows/ci.ymlbuild, docs and CI
*_test.go, examples/unit, concurrency, large-array and example coverage

7. What this unlocks

The Go module proves the ABI is usable from a language with its own collector and its own concurrency model — the hardest case after Rust itself. The Julia and JVM bindings follow with different marshalling and their own lifecycle idioms, and the Arrow/Polars interop changes sit underneath all of them.

Arrow interop: one memory model for every engine

Apache Arrow is the closest thing the data world has to a shared ABI for tables. Polars, DataFusion, pandas/pyarrow, Spark, Julia’s Arrow.jl and most columnar file formats all agree on one thing: what a table is made of. A table is a schema plus, for each column, a set of buffers — a validity bitmap, the values, and (for text) an offsets buffer — plus a data type and a length. Nothing about that description mentions rows.

That agreement is enormously useful, and it is also the source of almost every subtlety in this chapter. sciencekit’s algorithms want a row-major matrix. Arrow wants contiguous columns. A matrix cannot alias a multi-column table. A table’s chunks are not a table. A Float32 column is not a Float64 column. A null is not a NaN.

flowchart LR
    accTitle: How Arrow data crosses the sciencekit seam
    accDescr: Arrow record batches, chunked columns, file readers and the C Data Interface all enter through the arrow module. The schema mapping translates Arrow types into the neutral logical vocabulary and rejects unsupported columns by name. The import path applies the declared missing-value policy and produces a tabular batch, while complete primitive columns are borrowed without copying. The export path turns sciencekit results back into Arrow arrays, record batches and a C stream, always copying and reporting so.
    A["Arrow sources<br/>batches, chunks,<br/>files, FFI"] --> B["schema mapping<br/>neutral vocabulary"]
    B -->|unsupported type| X["UnsupportedColumnType<br/>naming the field"]
    B --> C["import<br/>missing-value policy"]
    A -->|complete primitive| D["zero-copy borrow<br/>no copy, no unsafe"]
    C --> E["SKTabularBatch"]
    D --> E
    E --> F["sciencekit algorithms"]
    F --> G["export<br/>arrays, batches, CSR"]
    G --> H["Arrow out<br/>always copies"]
    classDef arrow fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef neutral fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef reject fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    class A arrow
    class B,C,D,E,F,G,H neutral
    class X reject

This chapter builds the Arrow adapter: the first concrete engine behind the neutral seam described in the dataset-interop chapter. It maps Arrow types onto sciencekit’s neutral vocabulary, imports record batches and chunked columns, borrows primitive buffers without copying, applies the declared missing-value policy to Arrow’s validity bitmaps, exports results back to Arrow, and speaks the Arrow C Data Interface in both directions.

The capability is arrow-columnar-interop; the code lives in crates/sciencekit_interop/src/arrow/, behind the arrow feature of sciencekit_interop.

1. The problem, in plain words

Suppose you have a Parquet file with 500 columns and you want to fit a scaler on columns 3, 17 and 42. Three questions decide how the adapter must behave:

  1. What is a column, here? Arrow says “a buffer of Float64 with a validity bitmap”. sciencekit says “a column of logical type Float64 with role Feature”. The adapter must translate — and must refuse anything it cannot translate, before reading a single row.
  2. When is a copy allowed? Arrow stores columns contiguously, so a single complete Float64 column is already exactly the memory a numeric column view wants. Copying it would be pure waste. But a column with nulls has a bitmap, and the numeric path needs a materialized sentinel instead.
  3. What goes back out? A fitted model must return its results to the caller’s engine — as Arrow arrays, record batches, or a C stream — without a detour through text.

The whole adapter is the answer to those three questions, plus the discipline of making every refusal a structured, named error rather than a panic.

2. The decisions, and the roads not taken

  1. A narrow, closed type vocabulary. sk_logical_type_from_arrow_data_type maps Arrow types onto sciencekit’s six logical types (Float32, Float64, Integer64, Boolean, Nominal, CategoryCode). Nested, temporal, binary, decimal, Float16, UInt64 and Null columns are rejected up front with SKError::UnsupportedColumnType naming the field and suggesting a conversion.
  2. Roles travel as field metadata. sk_arrow_schema_from_tabular_schema writes sciencekit:role and sciencekit:logical_type into each field’s metadata, so a schema exported by sciencekit round-trips its roles without the caller restating them. The sciencekit:logical_type key exists for exactly one ambiguity: CategoryCode and Integer64 both travel as Arrow Int64.
  3. Zero-copy means borrowed, and only for complete primitive columns. sk_arrow_borrowed_column returns SKArrowBorrowedColumn::Float32/Float64/Integer64 — a plain slice borrowed from the Arrow buffer, with no unsafe at all. A column with nulls, or of any other type, is refused with UnsupportedRepresentation so the caller materializes through the normal import path instead.
  4. The missing-value policy decides what a null means. Arrow’s validity bitmap is applied when a column is materialized: Reject fails naming the column, NumericNaN writes NaN, ConstantFill(value) writes the value, and CategoricalMissingCode keeps the missing code for the categorical path. The neutral column types keep the nulls they receive: nullable integers stay Integer64 with Option<i64> entries, text stays Nominal, booleans stay Boolean — all of them with their nulls intact. The import therefore never rewrites a batch’s schema to make a null fit; the policy is applied later, by extract_target / the categorical extraction, against the scalar the caller actually asked for. That is also where the exactness guard lives: a nullable integer column read as f64 is fine up to 2^53, while reading 16_777_217 as f32 is rejected instead of silently rounded.
  5. A dictionary column is a label table plus codes. sk_dictionary_label_table builds a reversible SKLabelTable following the dictionary’s own value order, so code i restores label_of(i) exactly. The import path converts the keys to SKColumnData::CategoryCode after remapping them through the canonicalised label table, and a key that points at a null or out-of-range dictionary slot is rejected. Only Utf8 / LargeUtf8 dictionary values are accepted; any other value type is refused with UnsupportedColumnType, consistently with the schema mapping. An empty string dictionary yields an empty label table instead of an error.
  6. The C Data Interface is the binding ABI. Export produces Arrow’s own FFI_ArrowArray and FFI_ArrowSchema; import consumes them and takes ownership of the release callback, which is exactly what keeps the data alive after the producer drops its handle. unsafe is confined to the ffi module; every public entry point is safe and transfers ownership exactly once.
  7. File formats are reopenable sources, not one-shot readers. SKArrowFileSource opens a fresh reader per pass, so an iterative estimator sees the same batches in the same order on every epoch. Parquet and IPC push the projection down into the reader; CSV and JSON are projected by the cursor after decoding.
  8. Export always copies, and says so. SKArrowExportedArray::is_zero_copy() and SKArrowExportedRecordBatch::is_zero_copy() exist so callers can branch on the same report shape as the import path — but they are always false, because Arrow buffers and sciencekit buffers are separate allocations.

Roads not taken. Depending on Polars or DataFusion instead of the arrow-* crates (they pin Arrow versions and drag a query engine along); a bespoke C ABI of (data, indices, indptr, shape) (every binding would have to reimplement it, and it could not carry null bitmaps or schemas); densifying a sparse input (the representation-parity rule forbids it); and accepting nested types by flattening them silently (it would change a column’s meaning without telling anyone).

3. The concepts, taught from zero

Columns, not rows

Arrow’s central decision: a table’s storage is a set of column buffers. The row i of column j is the i-th element of that column’s buffer. This is why a 500-column Parquet file can be read two columns at a time (only those buffers are decoded) and why a row-major matrix can never alias it — the matrix’s element (i, j) is i * ncols + j bytes apart from (i, j+1), while Arrow’s are stride_j bytes apart. sk_export_dense_matrix makes this explicit: a one-column matrix exports as a primitive array; a wider matrix exports as a StructArray with one field per column, because there is no row-major buffer to alias.

The validity bitmap

Every Arrow array carries an optional validity bitmap: one bit per row, 1 meaning “this row has a value”. null_count() > 0 means the bitmap has at least one zero bit. The bitmap is not the data — a null row still occupies a slot in the values buffer. That is why a column with nulls cannot be borrowed as a plain slice: the slice would contain garbage where the nulls are, and the reader would have no way to know.

Buffers, offsets and slices

Arrow arrays also carry an offset. Array::slice(offset, length) produces a view over the same buffers, starting at a different position. It is zero-copy, and it is why the import path must resolve the offset rather than assume position zero. The record-batch import handles this naturally: sk_tabular_batch_from_record_batch reads the sliced window’s logical values through Arrow’s own accessors, and the test sk_sliced_record_batch_imports_the_logical_window proves it.

The chunked column

A Table in Arrow is a schema plus, per column, a list of chunks. The logical column is the concatenation of the chunks. This adapter does not import a Table type: it takes the chunks directly, as &[Vec<ArrayRef>] — one vector of chunk arrays per column — and concatenates them in declaration order with Arrow’s own concat. A column with zero chunks becomes a typed empty column instead of an error. This is a documented deviation from the original plan, which spoke of Table and ChunkedArray: the adapter depends on arrow-array directly and models the chunk list itself, so no Table type crosses the seam.

The C Data Interface

The Arrow C Data Interface is a C ABI for handing an array between two runtimes. An FFI_ArrowSchema describes the type; an FFI_ArrowArray describes the buffers and owns a release callback. The contract is: whoever consumes the structure owns it, and calls the release callback exactly once when done. An FFI_ArrowArrayStream is the streaming equivalent — a producer-owned private_data plus a get_next/get_schema/release callback trio.

Two rules follow, and the adapter honours both:

  • Export is a transfer. sk_export_array_to_ffi produces a pair that, when dropped, calls the release callback exactly once.
  • Import is the mirror. sk_import_array_from_ffi takes the pair by value, consumes it and thereby assumes ownership of the release callback. The imported array stays valid after the producer drops its own handle — the imported side now owns the buffers.

Missing values, three ways

A null in Arrow, a NaN in a numeric matrix and a missing code in a categorical column are three different things. SKMissingValuePolicy names all four behaviours explicitly — Reject, NumericNaN, CategoricalMissingCode, ConstantFill(f64) — and the adapter never guesses. The default is Reject: an unexpected null fails with SKError::NullValueInColumn naming the Arrow field, instead of silently poisoning a fit.

4. Each public object, explained

Everything below lives in sciencekit_interop::arrow and is compiled only when the arrow feature is on.

Schema and types

  • sk_logical_type_from_arrow_data_type(data_type, field_name) — one Arrow data type to one neutral logical type, or a structured rejection naming the field.
  • SKArrowColumnRoles — the role assignment for an import: .role(name, role), .target(name), .role_of(name). Columns without an entry default to SKColumnRole::Feature.
  • sk_tabular_schema_from_arrow_schema(schema, roles) — an Arrow schema to a validated neutral SKTabularSchema, preserving names and order.
  • sk_arrow_schema_from_tabular_schema(schema) — the reverse direction, writing the role and logical-type metadata keys.
  • sk_arrow_data_type_from_logical_type(logical_type) — the neutral type to its Arrow counterpart.

Import

  • sk_tabular_batch_from_record_batch(batch, policy, position, is_final) — one record batch to one SKTabularBatch.
  • sk_tabular_batch_from_column_chunks(schema, column_chunks, policy, position, is_final) — the chunked representation, concatenated in order.
  • sk_column_data_from_arrow_array(name, array, policy) — one Arrow array to one SKColumnData, dispatching on the data type.
  • sk_dictionary_label_table(array) and sk_label_tables_from_record_batch(batch) — the reversible label tables.
  • sk_boolean_category_codes(column_name, column, policy) — a boolean column to 0/1 category codes, on request.
  • sk_text_borrowed_view(array) — SKArrowTextBorrowedView, a row-indexed view whose bytes are Arrow’s own UTF-8 payload.

Zero-copy

  • sk_arrow_borrowed_column(array) — SKArrowBorrowedColumn, a borrowed slice of f32, f64 or i64 values, or UnsupportedRepresentation.
  • sk_arrow_conversion_report::<F>(array) — SKArrowConversionReport, with is_zero_copy() and is_cast().

Sources

  • SKArrowRecordBatchSource — a reopenable source over a reader factory: .new(factory, selection, batch_size, policy).
  • SKArrowOneShotTabularSource — a source that consumes one reader exactly once.
  • SKArrowFileSource — a path-based source: .new(path, format), .with_batch_size(), .with_selection(), .with_missing_value_policy(), .with_explicit_schema(), .with_csv_header(), .with_csv_delimiter(), .with_json_schema_inference().
  • SKArrowFileFormat — Parquet, Csv, IpcFile, IpcStream, Json, NdJson.
  • SKArrowFileOptions — a crate-private options struct behind those builders; SKArrowFileSource accepts the options through its builder methods, so the type itself is not part of the public API.

Export

  • sk_export_prediction(values) — a prediction vector to SKArrowExportedArray.
  • sk_export_dense_matrix(matrix, name) — a dense matrix to an Arrow array (primitive for one column, StructArray for several).
  • sk_export_data_batch(batch) — SKArrowBatchExport, either Dense or Sparse.
  • sk_export_supervised_batch(batch, target_name) — features plus a target column.
  • sk_export_csr_matrix(matrix) — SKArrowCsrExport with indptr(), indices(), data(), shape(), and the sciencekit:number_of_rows / sciencekit:number_of_columns metadata keys.

The C Data Interface

  • sk_export_array_to_ffi(array) / sk_import_array_from_ffi(ffi) — the array pair.
  • sk_export_record_batch_reader_to_stream(reader) / sk_import_stream(ffi) — the stream.
  • SKArrowFfiArray and SKArrowFfiStream — the owning wrappers, with .into_parts() / .from_parts() and .into_stream() / .from_stream(). from_parts and from_stream are unsafe: they trust the caller that the pair is a valid, matching Arrow C Data Interface pair (the same trust Arrow itself demands). sk_import_array_from_ffi and sk_import_stream stay safe, because the only way to build the wrapper is through sk_export_* or through the documented unsafe constructor.

5. A real walk-through, using the tests

The suites are the executable version of this chapter; each file below sits beside the implementation it covers.

schema_mapping_tests.rs — the vocabulary

sk_primitive_and_text_types_map_to_neutral_logical_types walks the accepted types; sk_string_dictionary_maps_to_category_codes shows a dictionary arriving as CategoryCode; sk_nested_temporal_and_binary_columns_are_rejected_with_the_field_name shows a List column refused by name; sk_roles_come_from_the_request_and_from_field_metadata shows the request winning only when the metadata is absent; and sk_round_trip_preserves_names_types_and_roles closes the loop — export a neutral schema, re-import it, get the same names, types and roles.

zero_copy_tests.rs — the borrow

sk_complete_f64_column_borrows_the_arrow_buffer asserts pointer identity: the borrowed slice is the Arrow buffer, not a copy of it. sk_complete_f32_and_i64_columns_borrow_the_arrow_buffer extends that to the other two borrowable types. sk_nullable_column_is_not_borrowed shows the refusal path. And sk_conversion_report_distinguishes_zero_copy_from_cast_and_materialization is the three-way distinction the whole design turns on: a matching complete column is zero-copy, a complete column of the other precision is a cast, and a nullable column is neither — it must be materialized.

null_policy_tests.rs — the four policies

sk_numeric_nan_policy_writes_nan_at_null_positions, sk_constant_fill_policy_writes_the_constant_at_null_positions and sk_reject_policy_reports_the_arrow_field cover three policies on the same fixture. sk_nullable_integer_promotes_to_float64_for_the_nan_policy covers the materialization: the import keeps the nullable integer column as Integer64 with its nulls, and extracting it as f64 under the numeric NaN policy writes NaN at the null positions. f32 extraction of a value above 2^24 is rejected, and the batch schema is never rewritten mid-stream. sk_lossy_integer_promotion_is_rejected is the guard on the other side: a value too large to survive the promotion fails instead of being rounded. sk_non_finite_fill_overflowing_f32_is_rejected catches the f32 narrowing case.

record_batch_import_tests.rs and chunked_import_tests.rs

sk_record_batch_becomes_a_tabular_batch_preserving_names_order_and_values is the basic contract; sk_empty_record_batch_imports_with_zero_rows and sk_sliced_record_batch_imports_the_logical_window are the edges. sk_chunks_concatenate_in_order_with_the_total_length proves the chunked path; sk_zero_chunks_become_an_empty_column, sk_single_chunk_is_imported_verbatim and sk_mismatched_column_count_or_chunk_type_is_rejected close the corners.

boolean_import_tests.rs and dictionary_import_tests.rs

sk_boolean_feature_imports_as_zero_and_one shows the numeric path; sk_boolean_column_becomes_category_codes_on_request the categorical one; sk_boolean_null_becomes_the_missing_category_code the missing-value interaction. sk_dictionary_imports_codes_and_a_deterministic_label_table is the reversible mapping; sk_dictionary_codes_are_stable_across_repeated_imports proves the label order does not drift between imports; and sk_text_import_owns_the_values_but_the_borrowed_view_aliases_the_text separates the two text paths — the imported column owns its bytes, while sk_text_borrowed_view aliases Arrow’s.

source/source_tests.rs — streaming

sk_batch_size_is_respected_and_only_the_last_batch_is_final is the batching contract: the cursor keeps one batch in flight and one buffered ahead, so it knows whether the batch it is delivering is truly the last one before it marks it final. sk_reader_error_propagates_after_complete_batches proves the lookahead discipline — a failure while peeking must not swallow a complete window the reader already produced. sk_reopenable_source_replays_the_same_batches is the epoch guarantee, and sk_one_shot_source_rejects_a_second_open is the counterpart: a one-shot source refuses to be reopened.

file/projection_tests.rs and file/*_tests.rs — the formats

sk_parquet_projection_reads_only_the_selected_columns_in_selection_order is the performance requirement in the spec: a 500-column file must not decode 497 of them. sk_csv_projection_preserves_selection_order shows the same result for CSV, where the projection happens in the cursor rather than in the reader — arrow-csv decodes eagerly, so the columns are dropped after decoding. That difference is deliberate and documented: CSV projection saves the conversion, not the decode.

The format suites cover the rest: sk_csv_schema_is_inferred_from_the_header_by_default and sk_csv_explicit_schema_overrides_inference; sk_csv_malformed_row_is_a_structured_error; sk_parquet_batches_never_exceed_the_configured_size, sk_parquet_row_order_is_preserved_across_batches and sk_truncated_parquet_file_is_a_structured_error; sk_json_requires_a_schema_unless_inference_is_opted_in — the JSON deviation, discussed below; and sk_truncated_ipc_stream_fails_after_the_complete_batches.

file/large_file_tests.rs closes the acceptance loop: sk_large_file_delivers_bounded_batches_and_every_row keeps the resident memory bounded while every row still arrives, and sk_concurrent_readers_produce_identical_results shows two readers agreeing.

export/export_tests.rs — the way back

sk_prediction_vector_exports_as_a_floating_arrow_column is the simplest export. sk_dense_data_batch_exports_feature_columns and sk_supervised_batch_exports_features_and_the_target_column cover the streaming blocks. sk_csr_export_preserves_pointers_indices_values_and_shape is the sparse export — three arrays and a shape, because Arrow has no sparse type. sk_both_scalar_precisions_export_and_cast_reports_zero_copy_false is the honest report: the export always copies, and it says so.

ffi/ffi_tests.rs — ownership

sk_dense_matrix_round_trips_through_the_c_data_interface and sk_stream_round_trips_batch_for_batch prove the round trip. The ownership tests are the important ones: sk_release_callback_runs_exactly_once counts the release calls, sk_failed_import_releases_the_exported_array_once proves the error path also releases exactly once, and sk_dictionary_and_text_round_trip_through_the_c_data_interface shows the richer types survive the boundary too.

provider_bridge_tests.rs — the seam in action

sk_reopenable_arrow_source_serves_multiple_epochs_through_the_provider is the whole point of the adapter: an Arrow source drives a multi-epoch fit. sk_supervised_provider_reads_the_arrow_target_column shows the target column arriving through the same path. And sk_arrow_provider_streams_sparse_blocks_without_densifying proves the representation-parity rule survives the crossing — a sparse Arrow source stays sparse.

6. Look inside

FileResponsibility
crates/sciencekit_interop/src/arrow/mod.rsthe module dispatcher and the public re-exports
.../arrow/schema_mapping.rsthe Arrow ↔ neutral schema mapping and the metadata keys
.../arrow/data_type_mapping.rsone Arrow data type → one logical type, or a named rejection
.../arrow/import/record-batch, chunk, column, null, boolean, dictionary and text import
.../arrow/zero_copy.rsthe borrowed column, the conversion report and the borrow guard
.../arrow/source/the batch source, the one-shot source, the cursor and the projection
.../arrow/file/the format enum, the options and the Parquet/CSV/IPC/JSON readers
.../arrow/export/the array, dense, record-batch and CSR exports
.../arrow/ffi/the C Data Interface and the C Stream Interface, and the only unsafe
.../arrow/*_tests.rsthe suites walked through above

7. The documented deviations

Four places where the implementation departs from the original design, on purpose:

  1. Table and ChunkedArray are not used. The chunked representation is modelled directly as &[Vec<ArrayRef>] — one vector of chunk arrays per column — and concatenated with Arrow’s concat. A column with no chunks becomes a typed empty column.
  2. JSON is record-oriented. The JSON reader decodes a record stream — one object per line, or a concatenated sequence of objects — which is what NDJSON and JSON-lines exports look like. It is not a reader for a JSON array document of arbitrary nesting. Because untyped JSON has no schema, an explicit schema is required unless inference is opted into with with_json_schema_inference(true).
  3. CSV projection happens in the cursor. arrow-csv decodes eagerly, so the columns are dropped after decoding rather than before. The observable result — selection order preserved, unselected columns absent — is the same as Parquet’s, but the saving is smaller.
  4. Export always copies. Arrow buffers and sciencekit buffers are separate allocations, so every exported array reports is_zero_copy() == false. The flag exists so the report shape is the same in both directions.

8. What this unlocks

Arrow is the common denominator under Polars, DataFusion and pandas — so the adapters for those engines become short: they convert their own types to Arrow and reuse this path entirely. The C Data Interface is in turn the transport for the language bindings, which can now hand a sciencekit result to Python, Julia or the JVM without an intermediate format. And the file sources mean a Parquet file is a first-class training input, with projection pushdown doing the work a hand-rolled reader would have to reinvent.

GPU compute contracts: devices, buffers and honest fallbacks

sciencekit is a CPU library. Every algorithm in it runs on the host, on arrays in ordinary memory, dispatched through faer or a BLAS backend. That is a deliberate choice — but it is not a permanent one, and the moment a GPU is mentioned, three questions become unavoidable:

  1. What is a GPU here? Not “the machine has an NVIDIA card” — a device: an enumerated, identified piece of hardware with a kind, an amount of memory and a list of things it can compute.
  2. Which one? A laptop may have an integrated GPU and a discrete one; a workstation may have four devices of the same kind. The choice must be deterministic — the same inventory and the same request must always pick the same device, or results stop being reproducible.
  3. What happens when there is no GPU? This is the question that separates a serious design from a hopeful one. A library that says “GPU not available” is useless. A library that silently computes on the CPU and reports the same numbers is lying in the telemetry: the operator sees a fast operation and cannot tell it ran on the CPU.
flowchart LR
    accTitle: How a device request becomes a plan with a truthful span
    accDescr: An execution context carries an optional device request with the configured backend, the required kernel and the enumerated inventory. Planning selects a device deterministically by kind priority and device index. When selection succeeds the plan carries the device backend; when it fails the plan falls back to the host backend and records why. The span records the backend and the fallback reason, so the operator can tell a device run from an honest CPU fallback.
    A["execution context<br/>device request"] --> B["deterministic selection<br/>(kind priority, index)"]
    B -->|a compatible device exists| C["plan<br/>backend = device kind"]
    B -->|no device, or no kernel| D["plan<br/>backend = host<br/>fallback_reason set"]
    C --> E["span<br/>backend, fallback_reason empty"]
    D --> F["span<br/>backend, fallback_reason set"]
    classDef request fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef decide fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef device fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef host fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    class A request
    class B decide
    class C,E device
    class D,F host

This chapter builds the foundation that answers all three: the device vocabulary, the device buffer, the closed kernel catalogue, the execution plan that carries a backend and a fallback reason, and the span fields that tell the truth about which of the two happened.

The capability is gpu-compute-contracts; the code lives in crates/sciencekit_common/src/device/, crates/sciencekit_common/src/execution/ and the new crates/sciencekit_gpu/ crate.

1. The problem, in plain words

Suppose you want to add GPU acceleration to a library whose algorithms currently assume a host array. The temptation is to reach for the vendor SDK directly: allocate a buffer, copy data, launch a kernel, copy back. But three different vendors (OpenCL, CUDA, ROCm) would then each invent their own version of that sequence, and the algorithms would have to know which vendor they are running on. Worse, the decision to use a GPU — which device, whether to fall back, what to tell the operator — would end up scattered across a dozen algorithm files, each with its own slightly different rules.

The alternative is to fix the shape of the decision now, before any kernel exists:

  • a vocabulary for describing devices, shared by every backend;
  • a contract every backend implements, so the algorithms depend on the contract rather than on a vendor;
  • a plan that resolves to exactly one backend, plus the reason when that backend is not a device;
  • observability that records which of the two happened.

This chapter builds exactly that, and nothing more: no kernels, no vendor runtime, no performance claim.

2. The decisions, and the roads not taken

  1. The vocabulary lives in sciencekit_common, not in sciencekit_gpu. Execution planning resolves the plan; it must consume a device inventory without depending on the crate that defines the backend contracts — that would be a cycle. So SKDeviceInfo, SKDeviceCapabilities, SKGpuKernel, SKDevicePreference and SKFallbackReason are defined in sciencekit_common::device, and sciencekit_gpu re-exports them as its public contract.
  2. The backend enum stays closed, and gains three device kinds. SKBackendKind becomes Faer, MatrixMultiply, NdArrayLinalg, OpenCl, Cuda, Rocm, with is_host() and is_device() distinguishing the two families. Keeping the enum closed means the compiler forces every exhaustive match in the workspace to name the device kinds too — a new backend cannot be added without every decision point confronting it.
  3. Selection is a pure function. sk_select_device(inventory, preference, required_kernel) filters, sorts by (kind priority, device index) and takes the first. No enumeration, no probing, no I/O: the inventory is an input, so planning is deterministic and testable without a machine.
  4. The preference decides the candidate set, then a fixed order breaks ties. SKDevicePreference::Backend(kind) restricts the candidates strictly to that kind — a requested Cuda never silently runs on OpenCL — and any other device yields NoDeviceAvailable. SKDevicePreference::AnyDevice accepts every device kind and orders them OpenCL → CUDA → ROCm, because OpenCL is vendor-transparent. Within one kind, the lowest device index wins.
  5. Device buffers are validated at construction. SKDeviceBuffer carries its backend kind, device index, scalar type, logical shape and capacity. The builder rejects a shape that exceeds the capacity and a payload that does not match the shape — a buffer can never exist in an inconsistent state.
  6. The transfer policy defaults to an explicit copy. SKDeviceTransferPolicy::Explicit is the default; MappedWhenSupported declares that a backend can expose a mapped view. The policy is reported by SKComputeBackend::transfer_policy, so the caller can see the cost model before dispatching; a device that does not advertise supports_mapped_memory must declare Explicit.
  7. The kernel catalogue is closed. Four families — PairwiseDistance, Gemm, Elementwise, TreePredict — with a stable name each. A backend that does not implement one returns SKError::UnsupportedOperation naming the kernel. It never silently computes something else.
  8. The plan records the fallback reason. SKExecutionPlan gained two fields: backend (the kind the plan runs on) and fallback_reason (Option<SKFallbackReason>). The span records the same two facts as backend and fallback_reason.
  9. No GPU runtime enters the core crates. sciencekit_gpu is #![forbid(unsafe_code)] and depends on no vendor SDK. The only device implementation is a mock compiled for tests. Concrete OpenCL, CUDA and ROCm backends arrive in their own changes (gpu-opencl-backend, gpu-cuda-backend, gpu-rocm-backend), each behind its own feature flag.

Roads not taken. Feature-detecting the vendor at crate load (a library that panics because a driver is missing is unusable); a Box<dyn Any> device abstraction (it erases the type safety the closed enum provides); allowing “the best available device” to depend on free memory or temperature (non-deterministic); and making the GPU the default backend so that a machine without one takes a slow path (the plan should say what it did, and the default should stay the predictable one).

3. The concepts, taught from zero

A device, not a GPU

The word “GPU” hides three different things: the hardware, the runtime that drives it, and the device — one addressable unit of the runtime with its own memory. This chapter is about the third. SKDeviceInfo describes one:

FieldMeaning
indexthe enumeration position within the device’s backend kind — the stable identity the planner sorts by
kindthe backend kind that drives it (OpenCl, Cuda, Rocm)
namethe human-readable name the runtime reported
memory_bytestotal device memory
capabilitieswhat the device advertises

kind names the runtime, not the hardware: an NVIDIA card driven through OpenCL is an OpenCl device. That is deliberate — the backend kind is what determines which runtime handles a dispatch.

Capabilities are opt-in

SKDeviceCapabilities has the three boolean flags supports_f32, supports_f64 and supports_mapped_memory, which default to false, plus supported_kernels, a Vec<SKGpuKernel> that defaults to an empty list. A device must declare what it can do. The alternative — defaulting to “yes” and letting a backend opt out — means an unknown backend is mistaken for a capable one, and the failure appears later, as a wrong answer rather than as an error.

The device buffer

SKDeviceBuffer<F> is a handle to device-resident storage for one dense matrix. It carries everything an operation must check before touching device memory: which backend owns it, which device it lives on, what scalar type it stores, its logical shape and its capacity. The foundation backs it with an owned staging allocation; a concrete backend swaps the staging vector for its runtime handle behind the same validated surface. The validation lives in the constructor, so every buffer that exists is consistent.

The closed kernel catalogue

SKGpuKernel names four kernel families, each with a stable kebab-case name (pairwise-distance, gemm, elementwise, tree-predict) that round-trips through FromStr. The catalogue is closed on purpose: a backend either implements one of these or reports it as unsupported. A backend cannot grow a private kernel and be selected for it — the planner filters the inventory by the kernel an operation requires, using the same catalogue.

Deterministic selection

candidates = inventory filtered by is_device() and by the preference
candidates = candidates filtered by supports_kernel(required_kernel)
winner     = candidates sorted by (kind_priority(kind), index), first element

Every step is deterministic. kind_priority depends on the preference: an explicitly requested backend gets priority 0, then OpenCL, CUDA and ROCm. The index breaks ties within a kind. Two calls with the same inputs return the same device — the test selection_is_deterministic_across_repeated_calls asserts it.

The fallback reason

When selection fails, the reason is not free text — it is one of three bounded values:

  • NoDeviceAvailable — no device of the requested kind is in the inventory.
  • KernelNotSupported — devices exist, but none implements the required kernel.
  • ExplicitModeDoesNotSelectDevice — the operation asked for an explicit execution mode, which never selects a device.

Each renders as a stable kebab-case token, and that token is what lands on the span.

4. Each public object, explained

The device vocabulary (sciencekit_common::device)

  • SKDeviceInfo — one enumerated device: .new(index, kind, name, memory_bytes, capabilities), .is_device(), .supports_scalar_type(name).
  • SKDeviceCapabilities — .new(supports_f32, supports_f64, supports_mapped_memory), .with_kernels(&[SKGpuKernel]), .supports_kernel(kernel), .supports_scalar_type(name).
  • SKGpuKernel — the closed catalogue: PairwiseDistance, Gemm, Elementwise, TreePredict, plus SKGpuKernel::ALL, .name() and FromStr.
  • SKDevicePreference — Backend(SKBackendKind) or AnyDevice.
  • SKFallbackReason — the three reasons above, with stable token rendering.
  • SKDeviceContext — the request an execution context carries: .new(configured_backend), .with_required_kernel(kernel), .with_inventory(devices).
  • sk_select_device(inventory, preference, required_kernel) — the deterministic selection.
  • SK_HOST_FALLBACK_BACKEND — the host backend a plan falls back to (Faer).

Execution planning (sciencekit_common::execution)

  • SKExecutionContext — gains a device: Option<SKDeviceContext> field. None means “no device was considered”, and the plan stays on the host backend.
  • SKExecutionPlan — gains backend: SKBackendKind and fallback_reason: Option<SKFallbackReason>.
  • sk_resolve_execution_plan(intent, context) — the resolution, now device-aware.

The GPU crate (sciencekit_gpu)

  • SKDeviceDiscovery — the trait every device backend implements: discover_devices(&self) -> Result<Vec<SKDeviceInfo>, Self::Error>, with Self::Error: From<SKError> so a backend reports a structured failure without leaking a runtime type into planning.
  • SKComputeBackend<F> — the compute contract: backend_kind(), transfer_policy() -> SKDeviceTransferPolicy (provided, defaults to Explicit), upload(ArrayView2<'_, F>) -> Result<SKDeviceBuffer<F>, Self::Error>, download(&SKDeviceBuffer<F>) -> Result<Array2<F>, Self::Error> and dispatch(SKGpuKernel, &[SKDeviceBufferRef<'_, F>]) -> Result<SKDeviceBuffer<F>, Self::Error>. The Self::Error associated type keeps runtime error types out of the contract, and SKDeviceBufferRef<'_, F> carries the lifetime of the borrowed argument buffers.
  • SKDeviceBuffer<F> — the validated device buffer: .backend_kind(), .device_index(), .scalar_type(), .shape(), .capacity(), .to_host_matrix().
  • SKDeviceBufferBuilder<F> — the only public constructor: .new(kind, index), .shape(rows, columns), .capacity(elements), .values(vec), .build().
  • SKDeviceTransferPolicy — Explicit (the default) or MappedWhenSupported; every backend declares its policy through SKComputeBackend::transfer_policy, so the policy is part of the contract rather than a convention.
  • SKDeviceBufferRef<'a, F> — a borrowed argument buffer passed to dispatch.

Observability

  • SKBackendKind — the closed enum, with .is_host(), .is_device(), .name() and FromStr; OpenCl, Cuda and Rocm join the three host kinds.
  • SKOperationObservation::record_fallback_reason(reason) — records the reason on the span, and only when a plan actually fell back.

Errors

Three new SKError variants: DeviceUnavailable, UnsupportedScalarType and DeviceTransferFailure — structured, never a panic.

5. A real walk-through, using the tests

crates/sciencekit_common/src/device/device_tests.rs — the vocabulary

device_info_reports_identity_memory_and_capabilities shows a device describing itself. scalar_type_support_follows_the_capability_flags ties the scalar query to the flags. the_default_capabilities_support_nothing is the opt-in rule: SKDeviceCapabilities::default() supports nothing at all.

crates/sciencekit_gpu/src/device/selection_tests.rs — deterministic selection

multiple_devices_are_ordered_by_kind_priority_then_index is the ordering rule in one test: the preferred kind first, then OpenCL, CUDA, ROCm, and within a kind the lowest index. a_configured_backend_selects_its_first_device covers the explicit preference; no_matching_device_reports_the_host_fallback and an_empty_inventory_falls_back_to_the_host_backend cover the two failure shapes. a_host_backend_preference_never_selects_a_device proves a CPU backend never selects a device. selection_is_deterministic_across_repeated_calls and fallback_reasons_render_as_stable_tokens close the loop on determinism and on the token vocabulary.

crates/sciencekit_gpu/src/buffer/buffer_tests.rs and buffer_validation_tests.rs — buffers

a_host_buffer_round_trips_through_a_mock_device is the basic round trip; single_precision_buffers_round_trip covers f32; a_device_buffer_reports_its_allocation shows the buffer describing itself; and the_default_transfer_policy_is_explicit pins the default.

The validation suite is the interesting half. a_shape_exceeding_the_buffer_capacity_is_rejected and a_payload_that_does_not_match_its_shape_is_rejected prove the constructor’s invariants. an_upload_exceeding_the_device_capacity_returns_shape_mismatch covers the device’s own capacity limit. an_unsupported_scalar_type_is_rejected covers a device that does not run f64. a_failed_upload_transfer_is_a_structured_error and a_failed_download_transfer_is_a_structured_error prove failures are structured. uploading_to_a_backend_without_devices_reports_the_device_unavailable and downloading_a_buffer_from_another_backend_is_rejected cover the two ownership mistakes that would otherwise become silent corruption.

crates/sciencekit_gpu/src/kernel/kernel_tests.rs — the closed catalogue

the_kernel_catalogue_lists_every_kernel asserts the catalogue has exactly the four documented families. a_supported_kernel_dispatches_and_returns_a_buffer is the happy path; an_unsupported_kernel_names_itself_in_the_error is the important one — the error carries the kernel’s name, so the caller learns what is missing rather than just that something failed. dispatching_without_arguments_is_rejected covers a malformed call, and the two selection tests prove a device is picked (or not) according to the kernel it implements.

crates/sciencekit_common/src/execution/gpu_planning_tests.rs — planning

automatic_plan_selects_the_configured_device_when_available is the primary scenario. automatic_plan_falls_back_to_host_without_a_device and automatic_plan_falls_back_when_the_kernel_is_missing cover the two fallback reasons. automatic_plan_keeps_the_configured_host_backend shows a CPU configuration is left alone. a_context_without_devices_plans_on_the_default_host_backend covers the None context. an_explicit_mode_never_selects_a_device covers ExplicitModeDoesNotSelectDevice. And gpu_planning_is_deterministic is the property the whole design rests on: the same context always yields the same plan.

crates/sciencekit_common/src/observability/gpu_span_tests.rs — the truth on the span

the_selected_device_kind_is_recorded_in_the_span proves the span records the device kind (opencl), never a hardcoded CPU value. the_fallback_reason_is_recorded_on_the_span proves the reason reaches the span. a_device_plan_records_its_backend_and_no_fallback and a_fallback_plan_records_the_reason_it_carries distinguish the two cases: a device plan leaves the field empty, a fallback plan fills it. That is the difference between an honest fallback and a silent one.

crates/sciencekit_common/src/observability/backend_kind_tests.rs — the closed enum

display_names_round_trip_through_parsing, display_names_are_the_documented_spellings and parsing_rejects_an_unknown_name pin the name vocabulary. device_kinds_are_distinguished_from_host_kinds and the_default_kind_is_the_pure_rust_host_backend cover the two families and the default.

crates/sciencekit_gpu/src/backend/concurrency_tests.rs — concurrency

contract_types_are_send_and_sync asserts the contract types are thread-safe. concurrent_discovery_agrees, concurrent_planning_agrees and concurrent_transfers_agree show that several threads doing the same thing get the same answer — the property that makes an inventory safe to share.

The mock device

The only device implementation is SKMockComputeBackend, compiled for tests only. It owns a fixed inventory, can be told to fail discovery (failing_discovery), to fail transfers (failing_transfers) or to cap its capacity (limited_to_elements), and it executes buffers and kernels in host memory. Its purpose is to make the contract testable without a GPU — which is exactly why the core crates stay free of a runtime dependency.

6. Look inside

FileResponsibility
crates/sciencekit_common/src/device/info.rsSKDeviceInfo, the description of one enumerated device
crates/sciencekit_common/src/device/capabilities.rsthe opt-in capability summary
crates/sciencekit_common/src/device/kernel.rsthe closed SKGpuKernel catalogue
crates/sciencekit_common/src/device/selection.rsthe deterministic selection rule
crates/sciencekit_common/src/device/context.rsthe device request an execution context carries
crates/sciencekit_common/src/device/fallback.rsthe fallback vocabulary and the host backend constant
crates/sciencekit_common/src/execution/device_plan.rsthe backend and fallback reason of a plan
crates/sciencekit_common/src/execution/plan.rsthe resolved plan, with its two new fields
crates/sciencekit_common/src/observability/operation_attributes.rsthe closed SKBackendKind and its display/parse surface
crates/sciencekit_common/src/observability/operation_observation.rsrecord_fallback_reason and the span field
crates/sciencekit_gpu/src/backend/contract.rsSKComputeBackend: upload, download, dispatch
crates/sciencekit_gpu/src/backend/discovery.rsSKDeviceDiscovery
crates/sciencekit_gpu/src/buffer/the validated device buffer, its builder and the transfer policy
crates/sciencekit_gpu/src/kernel/the kernel dispatch surface and the borrowed argument buffer
crates/sciencekit_gpu/src/backend/mock_device.rsthe test-only mock device

7. What this unlocks — and what it deliberately does not

This change ships no GPU runtime dependency into the core crates. sciencekit_gpu depends on no vendor SDK and forbids unsafe; the only device implementation is a mock compiled for tests. The concrete OpenCL, CUDA and ROCm backends arrive in their own changes (gpu-opencl-backend, gpu-cuda-backend, gpu-rocm-backend), each behind its own feature flag, each implementing the contracts this change defines.

That separation is the point. A backend written later inherits the vocabulary, the deterministic selection rule, the buffer validation, the closed kernel list and the fallback reporting for free — and it cannot invent its own, because the traits it must implement already say what they mean.

What exists today is honest: a machine with no GPU gets the CPU path, and the span says so, with a reason. When a real backend lands, the same span will say opencl instead.

Randomized SVD: a big factorization from small pieces

Why this chapter exists

Principal component analysis, truncated SVD and incremental PCA all need the same thing: the few directions along which a matrix varies the most. Computing them exactly is possible, and sciencekit_math can do it, but the exact algorithm pays a price that grows with the whole matrix. For a data table with 20 000 columns and a few thousand rows, the exact decomposition wants to hold factors the size of the matrix squared.

The randomized singular-value decomposition avoids that price. Instead of looking at the whole matrix at once, it asks a small number of random questions, watches which directions the answers point to, refines those directions a few times, and then solves a tiny exact problem. The surprising result — proved in the Halko–Martinsson–Tropp paper that the method comes from — is that the answer is extremely close to the exact one whenever the matrix has a dominant part, which is exactly the case in which anyone asks for a truncated decomposition.

This chapter tells the story of the implementation in crates/sciencekit_math/src/decomposition/, the decisions behind it, and the tests that prove it behaves.

The idea in one picture

flowchart TD
  accTitle: The randomized SVD pipeline
  accDescr: An m-by-n matrix is multiplied by a seeded Gaussian sketch to form a smaller matrix. Power iterations alternate a thin QR factorization with products against the input. The final basis is used to project the input to a small matrix, whose exact SVD yields the left singular vectors, right singular vectors and singular values of the result.
    X["X: m x n matrix<br/>(dense or CSR)"] --> O["Omega: n x (k+p)<br/>seeded Gaussian draws"]
    O --> Y["Y = X Omega<br/>m x (k+p)"]
    Y --> P{"power<br/>iterations"}
    P -->|"Q = thin_qr(Y)"| Z["Z = X^T Q<br/>n x (k+p)"]
    Z --> Y2["Y = X Z<br/>m x (k+p)"]
    Y2 --> P
    P -->|done| Q["Q = thin_qr(Y)<br/>m x (k+p) orthonormal"]
    Q --> B["B = Q^T X<br/>(k+p) x n"]
    B --> G["Gram B B^T<br/>(k+p) x (k+p)"]
    G --> S["small exact SVD"]
    S --> U["U = Q U_small<br/>m x k"]
    S --> V["V<br/>n x k"]
    S --> Sg["singular values<br/>k, sorted"]
    U --> R["SKRandomizedSvdResult"]
    V --> R
    Sg --> R

Every intermediate that carries a matrix dimension is m x (k+p) or n x (k+p). The only matrix that is squared is the Gram matrix, and its side is k+p, not m and not n.

The public surface

The kernel is exposed through a builder, as every public operation in this library is:

use sciencekit_common::{SKBackendKind, SKDataView};
use sciencekit_math::decomposition::SKRandomizedSvdBuilder;

let result = SKRandomizedSvdBuilder::new()
    .number_of_components(3)
    .number_of_power_iterations(4)
    .oversampling(10)
    .random_seed(42)
    .backend(SKBackendKind::Faer)
    .compute(SKDataView::Dense(matrix.view()), None)?;

// result.u            m x 3 left singular vectors
// result.singular_values  3 non-increasing values
// result.v            n x 3 right singular vectors

SKRandomizedSvdBuilder::new() starts with one component, one power iteration, an oversampling of ten, the seed 0 and the Faer backend. The builder is a Copy value, so a configured builder can be reused without cloning.

There is also a free function for the common case, with the same defaults for the backend:

pub fn sk_randomized_svd<F: SKBackendSelection>(
    matrix: SKDataView<'_, F>,
    number_of_components: usize,
    number_of_power_iterations: usize,
    oversampling: usize,
    random_seed: u64,
    centering: Option<ArrayView1<'_, F>>,
) -> Result<SKRandomizedSvdResult<F>, SKError>

SKRandomizedSvdResult carries three public fields — u, singular_values and v — plus three helpers: number_of_components, reconstruct (which multiplies the factors back together) and relative_frobenius_error, which compares the reconstruction with a reference matrix and returns $\lVert X - U \Sigma V^{\mathsf T} \rVert_F / \lVert X \rVert_F$.

Why SKBackendSelection and not SKFloat

The kernel needs a backend to run the small algebra, and the backend trait is only implemented for the sealed scalar set (f32 and f64). Using SKBackendSelection as the bound says that precisely. The estimator rule from AGENTS.md — the scalar appears as the only type parameter when the configuration carries scalar values — still holds: the builder itself carries no scalar, and the scalar is chosen at the call site that owns the data.

The backend kind stays a runtime value and is dispatched per call, never in build(). Nothing here is a type parameter over the backend.

Step 1: a random basis that is not really random

The first ingredient is Omega, an n x (k+p) matrix of standard-normal draws. The draws come from the shared deterministic generator (sciencekit_common::random::SKRandomGenerator) seeded through a domain:

let mut generator = SKRandomGenerator::new(sk_derive_seed(
    random_seed,
    SK_RANDOM_DOMAIN_PROJECTION,
    0,
));

Domains are how this library keeps unrelated random decisions from colliding. A forest derives its per-tree seeds in the tree domain, a k-means initialization in the initialization domain, and this kernel in the projection domain. Two subsystems asked for seed 7 therefore get different streams without coordinating.

sk_seeded_projection(rows, columns, random_seed) is public because the property it promises is worth testing on its own: the stream is a pure function of the seed and the shape.

let first = sk_seeded_projection::<f64>(16, 4, 11);
let again = sk_seeded_projection::<f64>(16, 4, 11);
let other = sk_seeded_projection::<f64>(16, 4, 12);
assert_eq!(first, again);          // randomized_projection_is_reproducible_for_the_same_seed
assert_ne!(first, other);          // randomized_projection_differs_across_seeds

The test randomized_projection_is_stable_for_the_single_precision_scalar runs the same shape with f32, so the draw order does not depend on the scalar width.

Step 2: project, refine, orthonormalize

The projection is one sparse or dense product:

$$Y = X \cdot \Omega \quad (m \times (k+p))$$

Y already spans a good approximation of the dominant column space — but a random basis is a noisy approximation. The power iterations sharpen it:

$$\begin{aligned} &\text{repeat } q \text{ times:} \ &\quad Q = \operatorname{thin_qr}(Y) && (m \times r,\ r = k + p) \ &\quad Z = X^{\mathsf T} Q && (n \times r) \ &\quad Y = X Z && (m \times r) \ &Q = \operatorname{thin_qr}(Y) && (\text{final basis}) \end{aligned}$$

Each pass multiplies the components of Y by the squared singular values of X, so the dominant directions grow relative to the rest. That is the whole trick: a small number of matrix products, no factorization of the big matrix.

The test randomized_dense_power_iterations_improve_a_decaying_spectrum builds a low-rank fixture with a decaying spectrum and asserts that seven power iterations do not reconstruct worse than one:

let single = sk_randomized_svd(SKDataView::Dense(matrix.view()), 4, 1, 6, 3, None)?;
let repeated = sk_randomized_svd(SKDataView::Dense(matrix.view()), 4, 7, 6, 3, None)?;
assert!(relative_error(&matrix, &repeated.reconstruct())
        <= relative_error(&matrix, &single.reconstruct()) + 1e-12);

The assertion is deliberately one-sided: power iterations must never hurt, and on a decaying spectrum they help. Demanding a strict improvement in every fixture would make the test a statement about the fixture rather than about the algorithm.

The thin QR decision

The obvious implementation calls the backend’s QR decomposition. That was the first version, and it was wrong for this library’s target sizes: the backend returns the full $m \times m$ orthogonal factor. For a 4 000-row matrix that is 128 MB of f64 that nobody needs; for wider problems it is worse, and the measurement was 161 seconds on a fixture that should take a fraction of a second.

So the kernel owns a small Householder QR (qr.rs) that returns exactly the thin factor, $m \times \min(m, n)$ — here $m \times (k+p)$. A rank-deficient column is completed with a canonical direction so the basis always has k+p orthonormal columns; the algorithm then works on whatever rank the matrix actually has.

This is a deliberate departure from “always delegate to the backend”. The rule is not “the backend does all algebra”; it is “the backend is the selection surface, and heavy algebra goes through it”. A k+p-column Householder sweep is not heavy algebra: it is a handful of vector operations on a matrix with ten or twenty columns.

Step 3: solve a tiny exact problem

With Q in hand, project the matrix from the left:

$$B = Q^{\mathsf T} X \quad ((k+p) \times n)$$

B is the matrix X seen through the random basis. Its row space is the same as the dominant row space of X. Instead of decomposing B (still wide), the kernel forms its Gram matrix:

$$G = B B^{\mathsf T} \quad ((k+p) \times (k+p))$$

and runs an exact symmetric eigendecomposition on G (small_svd.rs). The eigendecomposition of a matrix whose side is k+p is cheap, exact enough, and independent of m and n. The right singular vectors come from B and the left ones are lifted back through the basis:

$$U = Q \cdot U_{\text{small}} \quad (m \times k)$$

Finally the factors are truncated to k, the singular values are sorted non-increasingly, and a sign convention is applied: the entry of each singular vector with the largest absolute value is made positive. Without it, U and V could each flip sign and the reconstruction would still be correct, which makes comparisons and snapshots awkward. The test randomized_dense_sign_convention_makes_the_pivot_entry_positive pins it down.

Sparse input never becomes dense

The kernel takes an SKDataView, so a CSR matrix arrives as a CSR matrix. Two operations need care:

  • X · Omega gathers rows of Omega weighted by the non-zero values. It reads the matrix exactly once and never materializes a dense X.
  • $X^{\mathsf T} \cdot Q$ is the transpose product, implemented over the same CSR structure.

The dense intermediates are $Y$, $Z$ and $Q$, all of shape $m \times (k+p)$ or n x (k+p). The test randomized_sparse_does_not_densify_a_wide_matrix is a guard: it factorizes a wide sparse fixture and checks that nothing the size of the input appeared.

randomized_sparse_keeps_the_dense_intermediates_small_on_a_large_matrix makes that guard quantitative. It builds a 4 000 x 20 000 CSR matrix, instruments the kernel with a test-only counter (instrumentation.rs, compiled only under cfg(test)), and asserts:

let allowed = (components + oversampling) * rows.max(columns);
assert!(sk_largest_dense_intermediate() <= allowed);
assert!(sk_largest_dense_intermediate() < rows * columns);

The second assertion is the one that would have failed before the thin-QR fix: a full 4 000 x 4 000 factor is 16 million cells, far above the 60 000 cells (15 x 4 000) allowed by the first.

The sparse and dense paths are cross-checked by randomized_sparse_matches_the_dense_factorization, which factorizes the same data both ways and compares the singular values within the documented tolerance.

Centering without copying

PCA centers the data: the mean of every feature is subtracted before the decomposition. Doing that literally would turn a sparse matrix dense, because the subtracted mean touches every cell.

Instead the kernel accepts an optional centering: Option<ArrayView1<F>> holding one mean per feature, and applies the centering inside the products: X_c · Omega is computed as X · Omega minus the mean contribution to each row. The same trick applies to the transpose product. The matrix is never materialized in centered form.

Three tests pin the behaviour:

  • randomized_centered_dense_matches_the_explicit_centering compares against a manually centered copy;
  • randomized_centered_sparse_matches_the_centered_dense does the same across representations;
  • randomized_centered_sparse_does_not_densify_the_centered_matrix proves the intermediate stays bounded.

A centering vector whose length differs from the number of features is rejected with a shape mismatch before any work happens.

Validation, determinism and concurrency

The kernel rejects an invalid configuration up front (randomized_validation_*):

ConditionError
zero rows or zero columnsEmptyInput
number_of_components == 0InvalidHyperparameter
number_of_components > min(rows, columns)InvalidHyperparameter
number_of_power_iterations == 0InvalidHyperparameter
oversampling == 0InvalidHyperparameter
centering length $\neq$ number of featuresshape mismatch

oversampling is a usize, so a negative oversampling is not representable; the zero case is what the builder must reject, and it does.

Determinism is a contract, not an accident. Because every draw comes from the seeded generator and the projection is a pure function of the seed, the same configuration gives the same answer:

  • randomized_concurrency_repeated_calls_are_identical;
  • randomized_concurrency_concurrent_calls_agree_with_the_single_threaded_result;
  • randomized_concurrency_does_not_depend_on_the_thread_count — the result is computed with a one-thread rayon pool and with the default pool and compared;
  • randomized_concurrency_result_is_send_and_sync, because the result must be shareable across threads.

Accuracy: what “close enough” means

The kernel does not return an exact decomposition, and it should not pretend to. The documented bound is:

  • the relative error of each retained singular value stays below 1e-6 once the range search has enough power iterations and oversampling;
  • the reconstruction error never exceeds the error of the optimal rank-k truncation by more than 1e-6, relative;
  • the dense and the sparse paths agree within the same tolerance.

The acceptance suite (acceptance_tests.rs, sparse_acceptance_tests.rs) turns that into executable statements. randomized_acceptance_singular_values_match_the_exact_decomposition computes the exact singular values with a reference implementation and compares them. randomized_acceptance_reconstruction_matches_the_exact_decomposition compares the reconstruction, and randomized_acceptance_a_decaying_spectrum_is_recovered checks the case the method is designed for. The helper expected_truncation_error computes the Eckart–Young bound, so the assertion is against the mathematically optimal truncation and not against an arbitrary number.

randomized_acceptance_produces_the_reconstruction_error_metric checks the public relative_frobenius_error helper, including its two edge cases: a zero reference reports zero, and a reference of the wrong shape is rejected.

What the result is used for

The kernel is the heavy lifting behind the decomposition estimators that follow in the roadmap: PCA (with and without centering), truncated SVD and incremental PCA. Those changes add the estimator surface — builders, fit, transform, explained variance — on top of exactly this kernel. Keeping the kernel in sciencekit_math means the estimators do not reimplement the numerics, and the determinism and accuracy guarantees are stated once.

Summary of the decisions

DecisionWhy
Seeded Gaussian basis, domain SK_RANDOM_DOMAIN_PROJECTIONReproducible results without coordinating with other subsystems
Thin Householder QR in the kernelThe backend’s full m x m factor is prohibitive; the kernel only needs k+p columns
Gram matrix of $B$ for the small SVDExact symmetric eigendecomposition on a $(k+p)^2$ matrix, independent of $m$ and $n$
Sign convention on the singular vectorsDeterministic, comparable output despite the sign ambiguity
Implicit centeringPCA semantics without densifying sparse input
SKBackendSelection boundThe kernel needs a backend; the backend exists for the sealed scalar set
Validation before any workA bad configuration fails fast with a structured error

The tests are the specification

The *_tests.rs modules beside the implementation are the executable version of this chapter. When the algorithm changes, they are what says whether the promise still holds:

  • projection_tests.rs — the seeded basis;
  • dense_tests.rs — shapes, ordering, sign, power iterations, wide matrices;
  • sparse_tests.rs — parity with dense, no densification, bounded intermediates;
  • centered_tests.rs — implicit centering;
  • validation_tests.rs — the error table above;
  • concurrency_tests.rs — determinism and thread-count invariance;
  • acceptance_tests.rs and sparse_acceptance_tests.rs — accuracy against the exact decomposition;
  • result_tests.rs — the result container helpers.

Random forests: bootstrap samples, de-correlated splits and honest out-of-bag scores

A single decision tree (Chapter 28) is fast, nonlinear and easy to inspect, yet it has one notorious weakness: high variance. Perturb a handful of training rows and the root split can jump to another feature, rewriting every branch below it. Leo Breiman’s random forest turns that instability into an asset. Grow many trees on independent bootstrap resamples, force each split to choose from a random subset of features so a single dominant column cannot make every tree look alike, and average their predictions. Variance drops, bias stays low, and the rows each tree did not draw give a built-in generalization estimate — the out-of-bag (OOB) score — without holding out a separate validation split.

This chapter introduces crates/sciencekit_ensemble and its first two estimators, SKRandomForestClassifier and SKRandomForestRegressor, implementing the random-forests specification.


1. The problem, in plain words

Suppose you ask one hundred colleagues to estimate a quantity. Averaging their answers only beats a single answer if two things are true:

  1. Each colleague is reasonably accurate on average (low bias).
  2. Their mistakes are not identical (low correlation).

If every CART tree saw the exact same training table and scanned every feature at every node, our deterministic tree builder would grow the exact same tree one hundred times — averaging one hundred copies of one tree changes nothing. Random forests inject controlled diversity in two orthogonal places:

  • Row diversity (bagging): tree $t$ draws $m$ row indices with replacement from the $n$ training rows. On a full-size draw ($m = n$), each row has probability $(1 - 1/n)^n \approx e^{-1} \approx 0.368$ of never being drawn by tree $t$.
  • Feature diversity (subspace selection): at every internal node, the splitter only inspects a seeded random subset of features — by default $\lfloor\sqrt{p}\rfloor$ out of $p$ features (SKMaximumFeatures::Sqrt). Even if feature $8$ is slightly stronger globally, trees whose root draw omits feature $8$ discover informative splits on the remaining columns.

For classification over $C$ canonical classes, if tree $t$ predicts leaf class distribution $\hat{\mathbf{p}}^{(t)}(x) \in [0, 1]^C$, the forest averages the distributions and picks the largest class (breaking ties toward the smallest canonical index):

$$ \bar{p}c(x) = \frac{1}{T} \sum{t=1}^{T} \hat{p}c^{(t)}(x), \qquad \hat{y}(x) = \arg\max{c \in {0,\dots,C-1}} \bar{p}_c(x). $$

For regression, where tree $t$ predicts scalar leaf response $\hat{y}^{(t)}(x)$, the forest predicts the arithmetic mean:

$$ \hat{y}(x) = \frac{1}{T} \sum_{t=1}^{T} \hat{y}^{(t)}(x). $$


2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Delegate CART to sciencekit_tree; own ensemble logic in sciencekit_ensembleSKDecisionTreeClassifier and SKDecisionTreeRegressor already implement sorted dense scans, CSC sparse scans, class weights, feature subsampling and node importances. Reusing them keeps one source of truth for split math.Duplicating a private tree builder inside sciencekit_ensemble — double maintenance and subtle drift between single trees and forests.
Pure per-tree seed derivation via sk_derive_seedTree $t$ derives tree_seed = sk_derive_seed(global_seed, SK_RANDOM_DOMAIN_TREE, t) for node feature draws and folds SK_RANDOM_DOMAIN_STAGE on top for its bootstrap draw. Neither stream collides, and tree $t$ produces the exact same structure whether fitted on 1 thread or 64 threads.Sharing one mutable RNG protected by a Mutex across threads — thread scheduling changes which tree gets which seed, destroying reproducibility.
Lock-free slot fitting(0..number_of_trees).into_par_iter() maps each tree index into its own owned slot; no mutex or shared mutable accumulator exists during fit or predict.Appending trees or summing importances into a locked shared vector — contention and non-associative floating-point order dependence.
Row-copy CSR bootstrap, never densificationSampling sparse rows copies only stored (column, value) slices into a fresh CsMat (O(nnz) memory). Wide text or high-cardinality one-hot matrices never materialize dense zeros.Calling .to_dense() before bootstrapping — a $128 \times 100,000$ sparse batch would explode from kilobytes to gigabytes across trees.
Canonical class table fixed once on full targets, with local-to-forest mapping per treesk_canonicalize_labels orders classes by first occurrence. A bootstrap draw can permute first-occurrence order, omit a rare class, or on tiny data draw a single class. Mapping each tree’s local classes back to the forest’s canonical table (and storing a PureLeaf when a draw has one class) makes every sample size safe and exact.Assuming every bootstrap draw sees all classes in the same order — swaps probability columns when row 0 is not drawn first, and fails on tiny datasets.
Explicit Result<F, SKError> for oob_score()When oob_score is disabled, or when a tiny forest leaves zero rows out of bag, model.oob_score() returns SKError::UnsupportedOperation while model.oob_scored_rows() reports 0.Returning 0.0 or NaN — 0.0 is indistinguishable from a genuine accuracy or $R^2$ of zero, and NaN silently poisons downstream comparisons.

3. The concepts, taught from zero

Deterministic parallelism without locks

Parallelism and determinism often feel at odds: operating-system threads finish work in unpredictable order. The trick is to make every random choice a pure function of coordinates, never of arrival order. From the user’s random_seed, tree $t$ computes two independent 64-bit SplitMix64 seeds (Chapter 21): one for drawing its bootstrap rows and one handed to sciencekit_tree for per-node feature subsampling. Each worker builds its tree in isolation and writes slot $t$ of the output vector. Whether rayon runs on one core (InProcessSynchronous) or across a multi-core pool (Automatic), every slot contains the exact same tree bit-for-bit.

flowchart TD
    accTitle: Parallel lock-free random-forest training and out-of-bag scoring
    accDescr: The global random seed and full dense or CSR dataset feed independent parallel slots 0 through T minus 1. Each slot derives a bootstrap seed and a split seed from its tree index, gathers rows without densifying, records out-of-bag row indices, and fits one CART tree. Fitted slots assemble into the immutable forest model, averaging normalized feature importances and scoring out-of-bag rows using only trees that excluded each row.
    Seed["Global random_seed + full Dense / CSR design"] --> Slot0["Slot 0: sk_derive_seed(seed, TREE, 0)"]
    Seed --> Slot1["Slot 1: sk_derive_seed(seed, TREE, 1)"]
    Seed --> SlotT["Slot T-1: sk_derive_seed(seed, TREE, T-1)"]

    Slot0 --> Boot0["Bootstrap rows + OOB mask 0<br/>Dense gather or CSR row copy"]
    Slot1 --> Boot1["Bootstrap rows + OOB mask 1<br/>Dense gather or CSR row copy"]
    SlotT --> BootT["Bootstrap rows + OOB mask T-1<br/>Dense gather or CSR row copy"]

    Boot0 --> Tree0["CART Tree 0<br/>Sqrt feature subset per split"]
    Boot1 --> Tree1["CART Tree 1<br/>Sqrt feature subset per split"]
    BootT --> TreeT["CART Tree T-1<br/>Sqrt feature subset per split"]

    Tree0 --> Model["Immutable Fitted Forest<br/>Send + Sync"]
    Tree1 --> Model
    TreeT --> Model

    Model --> Imp["Normalized mean<br/>feature_importances()"]
    Model --> OOB["Out-of-bag scorer<br/>Accuracy or R² on excluded rows only"]
    Model --> Pred["Row-parallel prediction<br/>Mean probabilities or mean responses"]

    classDef source fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef worker fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef model fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef output fill:#f3e8ff,stroke:#9333ea,stroke-width:2px,color:#581c87

    class Seed source
    class Slot0,Slot1,SlotT,Boot0,Boot1,BootT,Tree0,Tree1,TreeT worker
    class Model model
    class Imp,OOB,Pred output

How out-of-bag estimation stays honest

Suppose a forest memorizes noisy training rows. Evaluating the whole forest on the training set lets the roughly $63.2%$ of trees that saw row $i$ vote on row $i$, inflating accuracy toward $1.0$. Out-of-bag estimation fixes that leak without splitting the dataset:

  1. While building tree $t$, sk_out_of_bag_rows records every training row index $i \in {0,\dots,n-1}$ that never appeared in tree $t$’s bootstrap draw.
  2. After all $T$ trees finish, row $i$ accumulates predictions only from the subset $\mathcal{O}_i = {t : i \notin \text{bootstrap}(t)}$.
  3. Rows with $|\mathcal{O}_i| = 0$ (possible when $T$ is tiny) are excluded rather than guessed; oob_scored_rows() reports how many rows had $|\mathcal{O}_i| \ge 1$.
  4. Over those scored rows, classification computes sk_accuracy_score and regression computes sk_r2_score from sciencekit_metrics.

If bootstrap(false) is configured, every tree sees every row ($\mathcal{O}_i = \emptyset$), so combining bootstrap(false) with oob_score(true) is rejected immediately in build() with SKError::InvalidHyperparameter { name: "oob_score", .. }.

Aggregating feature importances

Each fitted tree already normalizes its weighted impurity decreases so its feature_importances() sum to one (Chapter 28). The forest averages those per-tree vectors across all $T$ trees and re-normalizes by the total when at least one tree split:

$$ I_j = \frac{\frac{1}{T}\sum_{t=1}^{T} I_j^{(t)}}{\sum_{k=0}^{p-1} \frac{1}{T}\sum_{t=1}^{T} I_k^{(t)}}. $$

When no tree in the forest makes a split (for example maximum_depth(0)), every coordinate of feature_importances() remains 0.0.


4. Each public object, explained

  • SKRandomForestClassifier<F> / SKRandomForestClassifierBuilder<F> and SKRandomForestRegressor<F> / SKRandomForestRegressorBuilder<F> — builder-only estimators exposing number_of_trees (default 100), criterion (Gini / Entropy for classification, SquaredError / AbsoluteError for regression), maximum_depth (default unlimited), minimum_samples_split (default 2), minimum_samples_leaf (default 1), maximum_features (SKMaximumFeatures::Sqrt default), bootstrap (default true), maximum_samples (SKMaximumSamples::All default), random_seed (default 0), class_weight (classifier, default SKClassWeight::None), oob_score (default false), backend (default SKBackendKind::Faer) and execution_mode (default SKExecutionMode::Automatic).
  • SKMaximumSamples<F> — controls how many rows each tree draws: All ($n$ rows), Count(usize) (clamped to $[1, n]$ at fit time, rejected at build if $0$) or Fraction(F) (must be finite and in $(0, 1]$).
  • SKRandomForestClassifierModel<F> — the immutable fitted classification forest implementing SKClassifierPredictor<F> (predict_labels, predict_probabilities) plus probabilities, number_of_trees, feature_count, classes, number_of_classes, feature_importances, oob_score, oob_scored_rows, out_of_bag_rows, tree, criterion, backend and execution_intent.
  • SKRandomForestRegressorModel<F> — the immutable fitted regression forest implementing SKRegressorPredictor<F> (predict) plus predict_values, number_of_trees, feature_count, trees, tree, feature_importances, oob_score, oob_scored_rows, out_of_bag_rows, criterion, backend and execution_intent.
  • Re-exported tree vocabulary — SKTreeCriterion, SKMaximumFeatures and SKClassWeight are re-exported at the sciencekit_ensemble root so callers configure a forest without adding a separate dependency on sciencekit_tree.

5. A real walk-through, using the tests

bootstrap_samples_are_reproducible_per_tree and out_of_bag_rows_are_exact_complement_of_drawn_sample

Located in bootstrap/sampler_tests.rs and bootstrap/oob_tests.rs, these verify the foundation: the same (global_seed, tree_index) pair always draws the exact same multiset of row indices, distinct tree indices diverge, the tree split seed never collides with the bootstrap seed, and the out-of-bag slice is the strictly ascending set complement of the drawn rows.

classifier_builder_defaults_match_contract and oob_score_without_bootstrap_is_rejected

Located in random_forest/forest_builder_tests.rs, these verify every default on both builders and prove that invalid combinations — number_of_trees(0), out-of-range SKMaximumSamples::Fraction, wrong-family criteria, all-zero explicit class weights, and bootstrap(false) paired with oob_score(true) — fail in build() with SKError::InvalidHyperparameter naming the offending field.

parallel_fit_equals_sequential_fit and thread_count_does_not_change_fitted_forest

Located in random_forest/forest_fit_tests.rs, the first fits both forests under SKExecutionMode::InProcessSynchronous and SKExecutionMode::Automatic and asserts sequential.tree(index) == parallel.tree(index) across every slot. The second installs custom 1-thread and 4-thread rayon pools and verifies that the fitted node arrays are identical. In the same module, feature_subsampling_sqrt_and_all_control_candidate_splits uses a nine-feature design to show All picking feature 8 at every root while Sqrt ($\sqrt{9} = 3$ features per split) diversifies the root splits.

hand_computed_two_tree_forest_averages_probabilities and equal_average_probabilities_break_ties_by_smallest_canonical_index

Located in random_forest/forest_classifier_tests.rs, the first builds a two-tree zero-depth forest whose trees carry class-0 probabilities 0.2 and 0.6, confirming the forest predicts 0.4 for class 0 and 0.6 for class 1. The second creates an exact 0.5 / 0.5 tie over nominal labels ["beta", "alpha"] (canonical index 0 is "beta") and confirms predict_labels deterministically chooses 0. configured_backend_is_recorded_in_prediction_span attaches a tracing_subscriber layer to prove SKBackendKind::MatrixMultiply reaches the model’s predict span.

three_tree_forest_predicts_exact_arithmetic_mean

Located in random_forest/forest_regressor_tests.rs, this builds a three-tree forest whose leaves predict 1.0, 2.0 and 6.0, confirming the forest predicts their mean 3.0.

oob_score_covers_rows_and_excludes_in_bag_trees

Located in random_forest/forest_oob_tests.rs, this constructs a memorization trap — unique row IDs paired with alternating labels — where in-bag training accuracy exceeds 0.95, yet oob_score() drops below 0.35 because no tree is allowed to score a row it trained on. On clean regression data, it also recomputes OOB predictions manually from regressor.trees() and regressor.out_of_bag_rows(t) and asserts agreement with oob_score() to $10^{-12}$. Companion tests disabled_oob_score_reports_unsupported_operation and no_scored_oob_rows_reports_unsupported_operation check both UnsupportedOperation paths.

classifier_dense_and_sparse_fit_and_predict_are_equivalent and ultra_wide_sparse_forest_fits_and_predicts_without_densifying

Located in random_forest/forest_representation_tests.rs, these verify all four dense/CSR fit and predict combinations (dense->dense, dense->sparse, sparse->dense, sparse->sparse), plus a $128 \times 100,000$ CSR matrix with two stored entries per row (nnz = 256) that would exceed $1.6\text{ GB}$ across 16 trees if densified.

shared_classifier_serves_concurrent_threads_deterministically and large_forest_is_invariant_across_rayon_thread_counts

Located in random_forest/forest_concurrency_tests.rs and acceptance_tests/large_tests.rs, these share Arc-wrapped models across eight OS threads and fit $20,000$-row dense and CSR problems with sciencekit_metrics accuracy, macro-$F_1$, MSE, MAE and $R^2$.


6. Look inside

PathResponsibility
crates/sciencekit_ensemble/src/lib.rsCrate root, public exports and sciencekit_tree vocabulary re-exports
bootstrap/maximum_samples.rsSKMaximumSamples<F> (All, Count, Fraction) and sample-count resolution
bootstrap/sampler.rssk_tree_seed, sk_bootstrap_seed, sk_sample_indices and dense/CSR row gathers
bootstrap/oob.rssk_out_of_bag_rows set-complement mask
random_forest/classifier_builder.rs, regressor_builder.rsBuilder-only configuration surfaces and defaults
random_forest/validation.rs, input_validation.rsHyperparameter, dimension, CSR, target and finiteness checks
random_forest/execution.rsSequential vs rayon grain-controlled slot and row execution
random_forest/classifier_fit.rs, regressor_fit.rsPer-tree bootstrap fitting, local-to-forest class mapping and model assembly
random_forest/classifier_predict.rs, regressor_predict.rsSingle-dispatch row-parallel probability and response averaging
random_forest/oob_scoring.rsOut-of-bag accuracy and $R^2$ over excluded rows
random_forest/importances.rsNormalized arithmetic mean of per-tree feature importances
random_forest/*_tests.rs, acceptance_tests/Companion unit suites and $20,000$-row end-to-end acceptance tests

7. What this unlocks

sciencekit_ensemble now owns a reusable, thread-count-invariant bootstrap and out-of-bag foundation. Generic bagging (SKBaggingClassifier and SKBaggingRegressor) will reuse the same seeded row sampler and OOB mask over arbitrary base estimators, while gradient boosting will pair the same SK_RANDOM_DOMAIN_TREE sub-seed convention with sequential residual trees.

Support-vector machines: kernels, SMO and calibrated margins

Up to now, every supervised boundary in sciencekit has either been a flat hyperplane (linear regression, ridge, lasso, elastic net, logistic regression, SGD) or a local lookup (nearest neighbours and decision trees). Support-vector machines (SKSVC and SKSVR) bridge those two worlds: they fit a maximum-margin linear boundary, but inside an implicit feature space defined only through pairwise similarities — kernels — and they keep only the handful of training rows that actually hold the boundary in place: the support vectors.

Building that cleanly in pure Rust forces five engineering questions into the open:

  1. Where do kernels live? Kernel PCA and kernel ridge will need the exact same inner products and radial basis functions, over dense, CSR and mixed inputs, without ever densifying a sparse matrix.
  2. How do you solve a quadratic program over $n$ (or $2n$) coupled dual variables without materializing an $n \times n$ matrix? A $10,500$-row dataset has an $880\text{ MiB}$ dense Gram matrix; materializing it up front does not scale.
  3. How can classification and regression share one solver? C-SVC has $n$ variables and two classes; $\varepsilon$-SVR has $2n$ variables and a tube around a continuous curve.
  4. How does a binary margin become multiclass labels and calibrated probabilities? Raw margins are signed distances, not probabilities, and one-vs-one produces $\binom{c}{2}$ pairwise margins that can even tie in a cycle.
  5. What does the fitted model own? It must outlive the caller’s slice, stay Send + Sync for concurrent inference, and preserve CSR sparsity when trained on sparse data.
flowchart LR
    accTitle: End-to-end flow of SKSVC and SKSVR from data views to predictions
    accDescr: Borrowed dense or CSR training views enter kernel resolution in sciencekit_math. A bounded LRU kernel-row cache feeds the pure-Rust second-order SMO solver, producing support-vector-only models in SKOwnedFeatureBlock. SKSVC aggregates one-vs-one binary heads into deterministic majority votes, OvO confidences, or Platt-scaled pairwise-coupled probabilities; SKSVR sums kernel similarities over its epsilon-tube support vectors.
    A["SKDataView<br/>(Dense or CSR, zero-copy)"] --> B["Kernel resolution<br/>Linear · Polynomial · RBF · Sigmoid · Precomputed"]
    B --> C["SKKernelRowCache<br/>(bounded MiB LRU + O(n) diagonal)"]
    C --> D["Second-order SMO<br/>(C-SVC n vars · ε-SVR 2n vars)"]
    D --> E["SKOwnedFeatureBlock<br/>(support vectors only, Dense or CSR)"]
    E --> F["SKSVCModel<br/>OvO votes · decision_function"]
    E --> G["Probability calibration<br/>5-fold Platt + Wu–Lin–Weng coupling"]
    E --> H["SKSVRModel<br/>continuous response"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef solver fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef state fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#4c1d95
    classDef output fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    class A,B input
    class C,D solver
    class E state
    class F,G,H output

This chapter walks through the two capabilities delivered by svm-svc-svr: kernel-functions in crates/sciencekit_math/src/kernels/ and support-vector-machines in the new crates/sciencekit_svm/ crate.


1. The problem, in plain words

Imagine points on a plane where class $0$ sits at $(-1, -1)$ and $(+1, +1)$ while class $1$ sits at $(-1, +1)$ and $(+1, -1)$ — the classic XOR layout. No straight line separates the two classes. Yet if you map every point $x = (x_1, x_2)$ to quadratic combinations of its coordinates, a flat plane in that higher-dimensional space slices the two classes cleanly, and projects back down to a smooth curved boundary.

The kernel trick says you never need to build those higher-dimensional coordinates at all. Whenever a learning algorithm depends on the features only through inner products $\langle \phi(x), \phi(y) \rangle$, you can replace that inner product with a kernel function $K(x, y)$ evaluated directly on the original rows:

  • Linear: $K(x, y) = \langle x, y \rangle$
  • Polynomial: $K(x, y) = (\gamma \langle x, y \rangle + c_0)^d$
  • Radial Basis Function (RBF): $K(x, y) = \exp(-\gamma |x - y|_2^2)$
  • Sigmoid: $K(x, y) = \tanh(\gamma \langle x, y \rangle + c_0)$
  • Precomputed: $K_{ij}$ supplied directly as a validated square matrix

Meanwhile, the maximum-margin objective pushes the separating slab as wide as possible while charging a budget $C$ for points that trespass inside the margin. Points comfortably on the right side of the margin end up with a multiplier $\alpha_i = 0$ — they can be thrown away after training without changing the boundary by a single bit. Only the support vectors ($\alpha_i > 0$) remain.


2. The decisions, and the roads not taken

DecisionWhy we chose itRoads not taken
Kernels live in sciencekit_math::kernelsKernels are general numerical primitives over SKDataView, reused by kernel PCA and kernel ridge. Keeping SKKernel as a closed enum avoids dynamic dispatch in hot loops.Putting kernels inside sciencekit_svm (blocks reuse) or using Box<dyn Kernel> trait objects (virtual calls in inner loops).
Reuse the norm-expanded pairwise distance dispatcher for RBFsk_pairwise_distance_matrix already handles dense, CSR and mixed pairs without densifying sparse matrices; clamping tiny negative cancellation errors $\max(|x - y|_2^2, 0)$ guarantees $K(x, x) = 1$ and finite values in $[0, 1]$.Subtracting dense row copies per pair (allocates and densifies CSR inputs).
One generalized second-order SMO solver for both C-SVC and $\varepsilon$-SVRBoth problems reduce to minimizing $\frac{1}{2}\alpha^\top Q \alpha + p^\top \alpha$ subject to $0 \le \alpha_t \le U_t$ and $y^\top \alpha = 0$ with $y_t \in {-1, +1}$. Second-order working-set selection (Fan, Chen & Lin 2005) cuts iteration counts dramatically on curved kernels.A generic interior-point QP solver (cubic per step and dense $n \times n$ storage) or stochastic subgradient (a different objective contract belonging to SGD).
Bounded in-memory LRU kernel-row cache (cache_size in MiB)SMO touches one pair of rows per iteration while keeping the $O(n)$ kernel diagonal resident. Caching rows in an LRU map capped by cache_size MiB bounds memory; cache_size = 0 recomputes on demand. memmap2 cache spilling, persistence and model export are explicitly deferred to Phase 7 (interop).Materializing the full $n \times n$ Gram matrix (unbounded $O(n^2)$ RAM) or growing a private memmap2 layer inside sciencekit_svm ahead of Phase 7.
One-vs-one (OvO) multiclass with smallest-index tie-breakingFitting $\binom{c}{2}$ binary problems touches only the rows of two classes at a time, parallelizes naturally across rayon, and matches the standard C-SVC decision geometry. Ties break deterministically to the smallest canonical SKLabelTable index.One-vs-rest for kernel SVC (imbalanced full-$n$ QPs per class; SKLinearSVC will use OvR where primal weights collapse $n$).
Opt-in probability calibration (probability(true)): 5-fold Platt + Wu–Lin–Weng couplingCross-validated Platt scaling avoids overfitting the sigmoid to training margins, and pairwise coupling solves the unique distribution consistent with all $\binom{c}{2}$ binary probabilities. Keeping probability false by default avoids $5\times$ fit cost when callers only want labels; calling predict_probabilities when disabled returns UnsupportedOperation.Always running 5-fold CV on every fit, or returning uncalibrated vote ratios as fake probabilities.
Owned SKOwnedFeatureBlock support-vector stateCopying only the support vectors in their native dense or CSR representation lets SKSVCModel and SKSVRModel outlive borrowed inputs, remain Send + Sync, and never densify sparse designs.Borrowing training data with a lifetime parameter or storing dense copies of sparse rows.

3. The concepts, taught from zero

Resolving $\gamma$: Scale, Auto and Value

Three of the kernels multiply inner products or squared distances by a positive scale $\gamma$. What happens if one feature is measured in millimetres ($1,000$) and another in metres ($1.0$)? A fixed $\gamma = 1$ makes $\exp(-\gamma |x - y|_2^2)$ underflow to zero for almost every pair of distinct rows. SKKernelGamma<F> provides three policies resolved at fit time by sk_resolve_kernel_gamma:

$$\gamma_{\text{scale}} = \frac{1}{p \cdot \operatorname{Var}(X)}, \qquad \gamma_{\text{auto}} = \frac{1}{p}, \qquad \gamma_{\text{value}} = \gamma$$

where $p$ is the feature count and $\operatorname{Var}(X)$ is the population variance over all $n \cdot p$ logical entries of $X$ (sk_feature_population_variance). Crucially, CSR implicit zeros are real observed zeros: the sparse variance helper folds the stored values and accounts for the $(n \cdot p - \operatorname{nnz})$ zero entries algebraically in $O(\operatorname{nnz})$ work, so dense and CSR twins resolve to the exact same scalar $\gamma$.

Sequential Minimal Optimization (SMO) in one picture

Both C-SVC and $\varepsilon$-SVR share a single linear equality constraint $\sum_{t=1}^{L} y_t \alpha_t = 0$ alongside box bounds $0 \le \alpha_t \le U_t$ and $y_t \in {-1, +1}$. If you try to nudge just one multiplier $\alpha_i$, the equality constraint breaks immediately. The smallest legal move changes two multipliers $(\alpha_i, \alpha_j)$ together so that $y_i \Delta \alpha_i + y_j \Delta \alpha_j = 0$:

$$\Delta \alpha_i = +y_i \delta, \qquad \Delta \alpha_j = -y_j \delta$$

Because only two coordinates move, minimizing the quadratic objective along $\delta$ is a one-dimensional parabola you can solve in closed form and clip to the box $[0, U_i] \times [0, U_j]$:

$$\delta_{\text{unclipped}} = \frac{-y_i G_i + y_j G_j}{\max(K_{ii} + K_{jj} - 2 K_{ij},; \tau)}$$

where $G_t = (Q\alpha)_t + p_t$ is the gradient at coordinate $t$ and $\tau = 10^{-12}$ guards zero or negative curvature (such as duplicate points or non-PSD sigmoid kernels).

Which pair $(i, j)$ should move next?

  1. Define the upper set $I_{\text{up}}(\alpha)$ of indices free to increase $y_t \alpha_t$ and the lower set $I_{\text{low}}(\alpha)$ free to decrease $y_t \alpha_t$.
  2. Pick $i = \arg\max_{t \in I_{\text{up}}} (-y_t G_t)$. Let $G_{\max} = -y_i G_i$ and $G_{\min} = \min_{t \in I_{\text{low}}} (-y_t G_t)$.
  3. KKT stopping rule: when $G_{\max} - G_{\min} \le \text{tolerance}$, no feasible pair can improve the objective beyond tolerance — the solver has converged! If the iteration counter hits maximum_number_of_iterations first, the solver returns SKError::NotConverged { iterations } rather than silently returning an under-fitted model.
  4. Otherwise, fetch one kernel row $K_{i, \cdot}$ from SKKernelRowCache and pick $j \in I_{\text{low}}$ maximizing the second-order objective gain $\frac{(G_{\max} + y_t G_t)^2}{2 \tilde{a}_{it}}$, breaking ties by the smallest index.
flowchart TB
    accTitle: Unified SMO reduction for binary C-SVC and epsilon-SVR
    accDescr: Binary C-SVC creates n dual variables with signs matching class labels and linear terms -1. Epsilon-SVR creates 2n dual variables, the first n with sign +1 and linear term epsilon minus z, and the second n with sign -1 and linear term epsilon plus z, sharing the same n-row kernel cache via index modulo n. Both enter sk_solve_smo_quadratic_program and recover bias from free support vectors.
    subgraph CSVC["Binary C-SVC (L = n variables)"]
        C1["y_i ∈ {-1, +1}<br/>U_i = C · weight(y_i)<br/>p_i = -1"]
    end
    subgraph ESVR["Epsilon-SVR (L = 2n variables)"]
        R1["t = 0..n: y_t = +1, p_t = ε - z_t<br/>t = n..2n: y_t = -1, p_t = ε + z_{t-n}<br/>U_t = C, kernel row = t mod n"]
    end
    CSVC --> QP["sk_solve_smo_quadratic_program<br/>WSS3 pair selection + LRU cache + shrinking"]
    ESVR --> QP
    QP --> BIAS["Bias b = mean of (-y_t G_t) on free 0 < α_t < U_t<br/>(or midpoint of G_max and G_min)"]
    classDef prob fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef core fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef out fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    class C1,R1 prob
    class QP core
    class BIAS out

Look at why $\varepsilon$-SVR fits the exact same solver with zero special cases: each training point $i$ gets an upper-tube variable $\alpha_i$ ($y_i = +1$, $p_i = \varepsilon - z_i$) and a lower-tube variable $\alpha_i^$ ($y_{n+i} = -1$, $p_{n+i} = \varepsilon + z_i$). Both variables reference the same training row $i = t \bmod n$ in SKKernelRowCache, and after convergence the net dual weight is simply $\alpha_i - \alpha_i^$. Points lying strictly inside the $\pm \varepsilon$ tube have $\alpha_i = \alpha_i^* = 0$ and vanish from the model!

Shrinking without ever sacrificing exactness

During training, many points quickly either drop to $\alpha_t = 0$ (far outside the margin) or saturate at $\alpha_t = U_t$ (deep inside the margin). Active-set shrinking temporarily removes those pinned coordinates from the inner scan. Before declaring convergence, sk_solve_smo_quadratic_program always calls sk_reconstruct_full_gradients and re-evaluates the KKT violation across all $L$ variables — so shrinking(true) and shrinking(false) obey the exact same KKT optimality guarantee.

From margins to calibrated probabilities: Platt scaling and pairwise coupling

A binary SVM outputs a signed margin $f(x) = \sum_{k} c_k K(x, s_k) + b$. When probability(true) is configured on SKSVCBuilder:

  1. Five-fold Platt scaling (sk_calibrate_binary_platt + sk_fit_platt_sigmoid): Using a per-pair seed derived via sk_derive_seed(random_seed, SK_RANDOM_DOMAIN_FOLD, pair_index), each binary pair shuffles its positive and negative indices with SKRandomGenerator into stratified folds, collects out-of-fold margins $f_i$, and fits $P(y = +1 \mid f) = \frac{1}{1 + \exp(A f + B)}$ by regularized Newton steps with a fixed Hessian damping term against Laplace-smoothed targets $t_+ = \frac{N_+ + 1}{N_+ + 2}$ and $t_- = \frac{1}{N_- + 2}$ (Lin, Lin & Weng 2007).
  2. Pairwise coupling (sk_couple_pairwise_probabilities): For $c \ge 3$ classes, the $\binom{c}{2}$ pairwise probabilities $r_{ab} = P(y = a \mid y \in {a, b}, x)$ are coupled into a single class distribution $p \in \Delta^{c-1}$ solving the positive-definite linear system $Q p = 0, \sum_{a=0}^{c-1} p_a = 1$ by the fixed-point iteration of Wu, Lin & Weng (2004).

4. Each public object, explained

Kernel catalogue (sciencekit_math::kernels)

  • SKKernel — closed enum: Linear, Polynomial, RadialBasisFunction (default), Sigmoid, Precomputed.
  • SKKernelGamma<F> — Scale (default), Auto, Value(F).
  • SKKernelParameters<F> — resolved .kernel, .gamma, .degree, .coef0.
  • Resolution & validation — sk_validate_kernel_hyperparameters, sk_resolve_kernel_gamma, sk_resolve_kernel_parameters, sk_feature_population_variance.
  • Matrix functions — sk_linear_kernel_matrix, sk_polynomial_kernel_matrix, sk_radial_basis_function_kernel_matrix, sk_sigmoid_kernel_matrix, sk_precomputed_kernel_matrix, sk_validate_precomputed_query_kernel, sk_kernel_matrix, sk_kernel_matrix_sequential, and SK_KERNEL_PARALLEL_GRAIN ($1,024$ pairs).

SMO and kernel storage (sciencekit_svm::kernel and sciencekit_svm::smo)

  • SKOwnedFeatureBlock<F> — Dense(Array2<F>) or Sparse(CsMat<F>) built via select_rows, borrowing back via .view().
  • SKKernelRowCache<'a, F> — bounded LRU row cache (from_megabytes, with_capacity_bytes, .diagonal(), .row(index), .hits(), .misses(), .cached_rows_count(), .maximum_cached_rows()).
  • SKSmoState<F>, SKSmoWorkingPair<F>, SKSmoTracker<F>, SKSmoOptions<F>, SKSmoSolution<F> — gradient state, WSS3 pair selector (sk_select_first_working_index, sk_select_working_pair), KKT violation and bias recovery (sk_maximal_kkt_violation, sk_recover_smo_bias), active-set shrinking (sk_shrink_active_set, sk_reconstruct_full_gradients), and problem solvers (sk_solve_smo_quadratic_program, sk_solve_binary_c_svc, sk_solve_epsilon_svr).

Estimators, models and calibration (sciencekit_svm)

  • SKSVC<F> & SKSVCBuilder<F> — builder setters .C(1.0), .kernel(SKKernel::RadialBasisFunction), .degree(3), .gamma(SKKernelGamma::Scale), .coef0(0.0), .tolerance(1e-3), .maximum_number_of_iterations(10_000), .cache_size(200), .shrinking(true), .class_weight(SKClassWeight::None), .probability(false), .random_seed(0), .backend(SKBackendKind::Faer), .execution_mode(SKExecutionMode::Automatic).
  • SKClassWeight<F> — None, Balanced, Explicit(Vec<F>), and LabelMap(BTreeMap<String, F>) via SKClassWeight::from_labels.
  • SKSVCModel<F> & SKBinarySVCModel<F> — implements SKClassifierPredictor<F> (predict_labels, predict_probabilities) plus decision_function ((m, 1) for binary, (m, c) OvO confidences for multiclass) and pairwise_decision_function.
  • SKSVR<F>, SKSVRBuilder<F> & SKSVRModel<F> — adds .epsilon(0.1) and implements SKSupervisedFit<F> and SKRegressorPredictor<F> (predict) over support-vector-only state.
  • sciencekit_svm::probability — SKPlattParameters<F>, sk_fit_platt_sigmoid, sk_calibrate_binary_platt, sk_couple_pairwise_probabilities, sk_couple_pairwise_probabilities_with_budget.

5. A real walk-through, using the tests

crates/sciencekit_math/src/kernels/*_tests.rs — the kernel catalogue

  • config_tests.rs: kernel_gamma_resolves_scale_auto_and_explicit_value verifies $\gamma_{\text{scale}} = 0.25$ and $\gamma_{\text{auto}} = 0.5$ on a hand-computed $2 \times 2$ matrix; kernel_gamma_scale_matches_between_dense_and_csr proves implicit CSR zeros yield the exact same variance; kernel_invalid_parameters_are_rejected_with_named_errors checks InvalidHyperparameter for negative $\gamma$, zero degree, NaN coef0 and constant-feature Scale.
  • linear_tests.rs: linear_kernel_matches_across_all_four_dense_and_sparse_pairs checks dense$\times$dense, sparse$\times$sparse, sparse$\times$dense and dense$\times$sparse; linear_kernel_handles_ultra_wide_csr_without_densifying runs a $4 \times 100,000,000$ CSR pair ($3.2\text{ GB}$ if densified) in sub-millisecond time.
  • polynomial_tests.rs, radial_basis_tests.rs, sigmoid_tests.rs, precomputed_tests.rs and parallel_tests.rs: polynomial_kernel_degree_one_with_unit_gamma_and_zero_offset_equals_linear, radial_basis_function_kernel_handles_identical_and_distant_rows_and_cancellation, precomputed_kernel_rejects_non_square_row_mismatch_and_sparse_views, and parallel_kernel_matches_sequential_on_large_dense_and_sparse_inputs close every scenario of kernel-functions.

crates/sciencekit_svm/src/smo/*_tests.rs — the SMO engine and cache

  • working_set_tests.rs: smo_working_set_selects_hand_computed_toy_pair_and_updates_gradients and smo_working_set_maximizes_second_order_gain_among_all_lower_candidates verify that second-order curvature picks the steepest quadratic descent pair rather than the naive first-order heuristic.
  • stopping_tests.rs: smo_stopping_detects_converged_toy_problem_and_recovers_bias and smo_stopping_returns_not_converged_with_exact_iteration_count_on_exhaustion pin KKT optimality and NotConverged { iterations }.
  • cache_tests.rs: cache_tracks_hits_misses_lru_eviction_and_recomputation_on_dense_view caps the cache to two $32$-byte rows, touches row $0$, evicts row $1$, and verifies hit and miss counts; cache_supports_csr_views_and_zero_cache_size_recomputes_every_row verifies cache_size = 0 on a $1,000,000$-column CSR matrix.
  • svc_loop_tests.rs & svr_loop_tests.rs: svc_smo_matches_hand_computed_two_point_dual_solution checks exact $\alpha = [0.5, 0.5]$ and $b = -3.0$; svr_smo_fits_smooth_one_dimensional_response_and_widening_epsilon_reduces_support_vectors verifies both smooth $\sin(x)$ approximation and monotonic support-vector reduction as $\varepsilon$ widens.

crates/sciencekit_svm/src/svc/*_tests.rs, probability/*_tests.rs & svr/*_tests.rs

  • svc_fit_tests.rs & svc_multiclass_tests.rs: svc_fit_binary_separable_retains_support_vectors_and_separates_training_rows verifies support vectors are a strict subset of training rows; svc_multiclass_fits_deterministic_one_vs_one_pairs_using_only_each_pairs_rows proves a three-class fit retains (0, 1), (0, 2) and (1, 2) in canonical order.
  • svc_predict_tests.rs, svc_decision_tests.rs & svc_weights_tests.rs: svc_predict_breaks_hand_built_vote_ties_by_smallest_canonical_index tests a 3-way Condorcet cycle [1, 1, 1] and a 4-class tie; svc_weights_balanced_shifts_decision_boundary_on_imbalanced_fixture and svc_weights_explicit_vector_and_label_map_produce_identical_weighted_models verify Balanced, Explicit and from_labels.
  • platt_tests.rs, coupling_tests.rs & svc_probability_tests.rs: platt_sigmoid_matches_hand_computed_formula_bounds_and_monotonicity, coupling_recovers_exact_three_class_distribution_and_differs_from_vote_counts, and svc_probability_disabled_returns_unsupported_operation verify calibrated probabilities end to end.
  • svr_tests.rs: svr_fits_smooth_one_dimensional_response_and_retains_only_support_vectors and svr_widening_epsilon_band_never_increases_support_vector_count verify the regressor estimator.

Parity, determinism, concurrency and acceptance

  • representation_fit_tests.rs & representation_predict_tests.rs: representation_fit_ultra_wide_csr_succeeds_without_densifying ($50,000,000$ CSR columns) and representation_predict_supports_all_four_fit_and_query_combinations_for_svc / _for_svr cover every dense/CSR combination.
  • determinism_tests.rs & concurrency_tests.rs: determinism_repeated_fits_and_thread_counts_produce_bit_identical_models compares 1-thread and 4-thread rayon pools bit-for-bit; concurrency_shared_models_predict_identically_across_threads shares Arc<SKSVCModel> and Arc<SKSVRModel> across six OS threads; concurrency_large_batch_parallel_prediction_matches_single_row_sequential proves batch rayon parallelism matches single-row evaluation.
  • acceptance_tests/: acceptance_nonlinear_xor_fixture_separates_with_rbf_better_than_linear, acceptance_large_dense_and_csr_svc_fits_and_predicts_over_ten_thousand_rows ($10,500$ rows), acceptance_large_svr_fits_and_predicts_over_ten_thousand_rows ($21,000$ dual variables), and acceptance_metrics_evaluate_svc_labels_probabilities_and_svr_responses (through SKAccuracyScorer, SKF1Scorer, SKLogLossScorer and SKR2Scorer).

6. Recap

  • Kernels live in sciencekit_math::kernels, dispatch once per representation pair, never densify sparse CSR matrices, clamp RBF cancellation errors, and parallelize across rows with rayon.
  • One second-order SMO solver solves both binary C-SVC ($n$ variables) and $\varepsilon$-SVR ($2n$ variables) over a bounded MiB LRU row cache, returning explicit SKError::NotConverged { iterations } when the iteration budget is exhausted.
  • Fitted models (SKSVCModel, SKSVRModel) retain only owned support vectors in their training representation (SKOwnedFeatureBlock), keeping inference zero-copy on queries and Send + Sync across threads.
  • Multiclass & probabilities use deterministic one-vs-one voting with smallest-index tie-breaking, OvO confidence aggregation in decision_function, and opt-in 5-fold Platt scaling plus Wu–Lin–Weng pairwise coupling.
  • Phase 7 boundary: memmap2-backed kernel caches, persistence and model export remain Phase 7 (sciencekit_interop) deliverables.

DBSCAN: density, reachability and honest noise

SKKMeans (Chapter 27) asks two things up front that real datasets often refuse to grant: you must tell it how many clusters exist, and every cluster must look roughly like a round ball around a centre, with every row forced into one of those balls. Give it two concentric rings, two interleaved crescents, or clean groups peppered with stray outliers, and a straight hyperplane between centroids cuts right across the true geometry while outliers drag every centre off course.

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) turns the question upside down. Instead of placing $k$ centres and pulling points toward them, it asks a local question around every point: are there enough neighbours nearby to call this neighbourhood dense? Dense neighbourhoods chain together into clusters of arbitrary shape; isolated points in thin air are labelled as explicit noise rather than forced into the nearest group.

This chapter builds SKDBSCAN: the region query over spatial trees and sparse brute force, the core/border/noise taxonomy, deterministic cluster numbering and border resolution, and the nearest-core predict_clusters extension.

The capability is dbscan; the code lives in crates/sciencekit_cluster/src/dbscan/.

1. The problem, in plain words

Imagine looking at a night-time satellite map of cities and country roads. You do not count the cities beforehand, and cities are not circles — one hugs a curved coastline, another stretches along a river valley, and isolated farmhouses sit miles from any town. Yet your eye separates them effortlessly because towns are dense and open countryside is sparse.

DBSCAN formalises that intuition with just two numbers:

  • $\varepsilon$ (eps): the radius of a “walking-distance” circle around each point, and
  • $m$ (minimum_samples): how many points (counting the point itself) must fall inside that circle for the spot to count as dense.

Everything else — how many clusters exist, what shapes they trace, and which rows are outliers — falls out of chaining overlapping dense circles together.

2. The decisions, and the roads not taken

  1. Reuse the shared searchers from sciencekit_neighbors for the region query. Every point’s inclusive $\varepsilon$-neighbourhood comes from SKNearestNeighborsSearcher::radius_neighbors: SKKDTree for dense inputs up to $20$ features, SKBallTree above $20$ features, and SKBruteForceSearcher whenever the input is sparse CSR or uses cosine distance.
  2. Self-inclusion is unconditional. For any true metric, $d(x_i, x_i) = 0 \le \varepsilon$, so row $i$ naturally appears in its own neighbourhood. Under cosine distance, however, a zero-norm row has convention distance $1 - 0 = 1$, which exceeds $\varepsilon < 1$. sk_radius_neighborhoods therefore guarantees that row $i$ is always sorted into neighborhoods[i], matching scikit-learn’s min_samples definition everywhere.
  3. Typed SKClusterLabel::Noise, never a magic -1 integer. In Python, DBSCAN returns -1 for noise, inviting accidental array indexing (centers[-1] silently reads the last cluster!). Here every row receives SKClusterLabel::Cluster(id) or SKClusterLabel::Noise, a four-byte niche-optimised Rust enum introduced in Chapter 31; external callers that want -1 opt in explicitly via label.to_i64().
  4. Deterministic component IDs and border resolution. Unvisited core points are scanned in ascending training-row order 0..n, and each neighbour list is sorted by training index. As a result, the component containing the smallest core row index always becomes Cluster(0), the next becomes Cluster(1), and a border point reachable from two clusters deterministically joins the cluster seeded first — regardless of how many rayon threads executed the parallel radius query.
  5. A documented nearest-core predict_clusters extension. Classical DBSCAN is transductive: adding new points could bridge two clusters, so scikit-learn omits DBSCAN.predict. In production pipelines, however, scoring or routing new rows against a frozen density partition is genuinely useful. SKDBSCANModel implements SKClustererPredictor by indexing only the fitted core samples and assigning each query row to its nearest core sample’s cluster when $d(q, c^\star) \le \varepsilon$, or SKClusterLabel::Noise otherwise.
  6. Zero densification, plus upfront CSC and metric/tree guards. Sparse CSR designs stay CSR both during the region query and when extracting the core-sample sub-matrix (sk_extract_core_samples). Requesting KdTree or BallTree with Cosine fails immediately at build(), and passing a compressed-column (CSC) view or requesting a tree over CSR fails up front with SKError::UnsupportedRepresentation and actionable guidance.

Roads not taken. Reimplementing a bespoke spatial tree inside sciencekit_cluster (duplicating sciencekit_neighbors); densifying sparse CSR rows to feed a KD-tree (blowing up memory on wide text/one-hot matrices); assigning new queries via nearest border points (which would let new points drift past $\varepsilon$ from actual dense regions); and shuffling or parallelising the BFS expansion itself (the expansion over integer neighbour lists is already linear in the output size and keeping it sequential guarantees exact determinism).

3. The concepts, taught from zero

Core points, border points and noise

Fix a distance $d$, a radius $\varepsilon > 0$ and a threshold $m = \text{minimum_samples} \ge 1$. For each training row $x_i$, define its inclusive $\varepsilon$-neighbourhood:

$$ N_\varepsilon(x_i) = {, j \in {0, \dots, n - 1} \mid d(x_i, x_j) \le \varepsilon ,} \cup {i} $$

Every point falls into exactly one of three roles:

  • Core point: $|N_\varepsilon(x_i)| \ge m$. The neighbourhood around $x_i$ is genuinely dense.
  • Border point: $|N_\varepsilon(x_i)| < m$, and $x_i$ lies inside $N_\varepsilon(x_c)$ for at least one core point $x_c$. It sits on the thin fringe of a dense region.
  • Noise point: $|N_\varepsilon(x_i)| < m$, and no core point lies within $\varepsilon$ of $x_i$.
flowchart LR
    accTitle: Core, border and noise roles in DBSCAN
    accDescr: Core points C0, C1 and C2 each have at least minimum_samples neighbours within eps and expand density to one another and to fringe point B. Border point B joins the cluster because C0 reaches it, yet B does not propagate density onward to nearby point N1, so both N1 and distant point N2 receive SKClusterLabel::Noise.
    subgraph Cluster0["Cluster(0) component"]
        C1["Core row 1<br/>|N| >= m"] <-->|"d <= eps | expands"| C0["Core row 0 (seed)<br/>|N| >= m"]
        C2["Core row 2<br/>|N| >= m"] <-->|"d <= eps | expands"| C0
        C0 -->|"d <= eps | absorbs"| B["Border row 4<br/>|N| < m"]
    end
    B -.->|"not core | stops"| N1["Noise row 5<br/>SKClusterLabel::Noise"]
    N2["Isolated row 6<br/>SKClusterLabel::Noise"]

    classDef core fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef border fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef noise fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
    class C0,C1,C2 core
    class B border
    class N1,N2 noise

Look closely at the dashed arrow between Border row 4 and Noise row 5 in the diagram. Even though row 5 sits within $\varepsilon$ of row 4, row 4 is not a core point, so the breadth-first expansion queue never expands row 4’s own neighbours. That asymmetric rule is what stops two separate clouds from leaking into one giant cluster across a single thin bridge of two stray points.

Why deterministic breadth-first expansion matters

Between core points, density connectivity is symmetric: if core point $a$ and core point $b$ lie within $\varepsilon$, each is in the other’s neighbourhood, so the core-point graph breaks cleanly into connected components regardless of visit order. Two things do depend on order unless we pin them down:

  1. Which cluster gets 0, 1, 2? Scanning seed from 0 to n - 1 means the component whose earliest core point has the smallest row index always gets Cluster(0).
  2. What if a border point touches two clusters? Because Cluster(0) finishes its full breadth-first expansion before Cluster(1) begins, a shared border point’s label flips from Noise to Cluster(0) first and is never overwritten later.

Notice how clean the separation of concerns is: the expensive work — computing distances and collecting $N_\varepsilon(x_i)$ for all $n$ rows — runs in parallel across rayon worker threads inside SKKDTree, SKBallTree or SKBruteForceSearcher, writing each row’s sorted neighbour indices into its own slot neighborhoods[row]. Once those sorted vectors return, sk_expand_clusters walks them deterministically in milliseconds, so $1$ thread and $16$ threads produce bit-for-bit identical SKClusterLabel arrays.

How out-of-sample predict_clusters works

When fit finishes and at least one core point exists, fit.rs slices the core rows out of the training matrix (sk_extract_core_samples — preserving dense Array2 or sparse CsMat without densifying) and builds SKDBSCANCoreSearch:

  • an optional spatial tree (KdTree or BallTree) over those core rows when the fit strategy was a tree, plus
  • a representation-agnostic SKBruteForceSearcher over the same core rows.
flowchart TD
    accTitle: SKDBSCANModel nearest-core assignment pipeline
    accDescr: A query batch enters predict_clusters, passes shape, finiteness and CSR/dense validation, handles an all-noise model by returning Noise, dispatches dense queries on a tree model to k_nearest(1) on the core tree and sparse or brute-force queries to SKBruteForceSearcher over core samples, then compares the nearest core distance against eps to emit Cluster(id) or SKClusterLabel::Noise.
    Q["Query batch<br/>Dense or CSR"] --> V["Validate queries<br/>shape, finite, not CSC"]
    V --> E{"Any fitted<br/>core samples?"}
    E -->|"No (0 clusters)"| ALLN["Return<br/>SKClusterLabel::Noise"]
    E -->|"Yes"| D{"Core tree present<br/>and Dense query?"}
    D -->|"Yes"| T["Core KdTree / BallTree<br/>k_nearest(queries, 1)"]
    D -->|"No | CSR or BruteForce"| BF["SKBruteForceSearcher<br/>k_nearest(queries, 1)<br/>no densification"]
    T --> CMP{"distance <= eps?"}
    BF --> CMP
    CMP -->|"Yes"| CL["Nearest core label<br/>Cluster(id)"]
    CMP -->|"No"| NS["Return<br/>SKClusterLabel::Noise"]

    classDef input fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef guard fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef index fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef outCluster fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef outNoise fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
    class Q input
    class V,E,D,CMP guard
    class T,BF index
    class CL outCluster
    class ALLN,NS outNoise

Notice why indexing only core samples (rather than all training samples) is essential: if a new query lands near a border point of Cluster(0) while sitting farther than $\varepsilon$ from every core point, an index over all training rows would mistakenly report distance $\le \varepsilon$ to that border point and pull the query into Cluster(0)! Querying the core-sample index enforces $d(q, c^\star) \le \varepsilon$ strictly against dense cores.

4. Each public object, explained

  • SKDBSCAN<F> / SKDBSCANBuilder<F> — builder-only estimator configuration: eps (default $0.5$, finite and strictly positive), minimum_samples (default $5$, strictly positive), metric (SKDBSCANMetric::Euclidean default, Manhattan, Chebyshev, Cosine), algorithm (SKDBSCANAlgorithm::Auto default, KdTree, BallTree, BruteForce), leaf_size (default $40$, strictly positive), backend (default SKBackendKind::Faer) and execution_mode (default SKExecutionMode::Automatic).
  • SKDBSCANModel<F> — immutable, Send + Sync fitted state exposing labels(), core_sample_indices(), number_of_clusters(), number_of_features(), eps(), minimum_samples(), metric(), search_strategy(), training_representation(), backend() and execution_mode().
  • SKDBSCANMetric / SKDBSCANAlgorithm / SKDBSCANSearchStrategy — the closed vocabulary of distances, requested search algorithms and resolved fit-time strategies (KdTree, BallTree, BruteForce — never Auto, with is_tree() reporting whether a spatial tree backed the fit).
  • Fit and assignment contracts — SKUnsupervisedFit<F> (fit), SKDBSCAN::fit_predict, and SKClustererPredictor<F> (predict_clusters) returning Array1<SKClusterLabel>.

5. A real walk-through, using the tests

dbscan_fit_identifies_core_border_and_noise_points_on_hand_checked_fixture

In dbscan/dbscan_fit_tests.rs, seven 2D points are clustered with eps = 1.0 and minimum_samples = 4:

  • Rows 0..4 form a $0.5 \times 0.5$ square ([0,0], [0.5,0], [0,0.5], [0.5,0.5]), so every corner sees at least $4$ points within $1.0$ and becomes a core point in core_sample_indices == [0, 1, 2, 3].
  • Row 4 at [-0.9, 0.0] sees only {0, 4, 5} ($3 < 4$), so it is not core — yet because core row 0 reaches it, row 4 receives SKClusterLabel::cluster(0) as a border point.
  • Row 5 at [-1.8, 0.0] sits $0.9 \le 1.0$ from border row 4, and $1.8 > 1.0$ from core row 0. Because border points do not propagate density, row 5 stays SKClusterLabel::Noise alongside isolated row 6 at [10.0, 10.0].

dbscan_fit_assigns_cluster_ids_in_smallest_core_index_order and dbscan_fit_resolves_shared_border_point_to_earliest_seeded_cluster

The first interleaves two blobs after a leading noise point at row 0, placing the (20, 20) blob’s first core row at index 1 and the (0, 0) blob’s first core row at index 2, and verifies (20, 20) gets Cluster(0) while (0, 0) gets Cluster(1). The second places a non-core border point at row 0 equidistant ($0.9 \le 1.0$) from two separate four-point core groups and confirms it joins Cluster(0) — the earlier-seeded component.

dbscan_query_radius_neighborhoods_include_each_point_itself

Tests KdTree, BallTree and BruteForce on dense points, plus Cosine with a [0.0, 0.0] zero-norm row under eps = 0.25, confirming neighbors.contains(&row) holds for every row even when the pairwise cosine convention reports self-distance $1.0$.

dbscan_representation_wide_sparse_design_and_core_extraction_never_densify

Builds a $6 \times 10{,}000{,}000$ CSR matrix directly from six stored entries (densifying it would allocate $480\text{ MB}$), runs the partition and sk_extract_core_samples, and verifies both stay "csr" with csr.nnz() untouched.

dbscan_predict_assigns_nearby_queries_to_nearest_core_cluster_and_distant_to_noise and dbscan_predict_covers_all_four_dense_and_sparse_combinations_without_densifying

In dbscan/dbscan_predict_tests.rs, five queries exercise every branch of predict_clusters: inside Cluster(0), inside Cluster(1), right on the inclusive boundary $d = \varepsilon = 0.9$, within $0.45$ of a border row yet $1.3 > 0.9$ from the nearest core row (confirming it yields SKClusterLabel::Noise), and far away. The companion parity test fits dense and CSR models and queries each with dense and CSR batches, asserting all four combinations return identical assignments.

dbscan_acceptance_large_twenty_thousand_row_fit_recovers_chains_and_noise, dbscan_acceptance_metrics_recovers_non_convex_concentric_rings_where_kmeans_cannot and dbscan_acceptance_metrics_silhouette_excludes_noise_and_scores_fitted_model

In acceptance_tests/, the large-scale test plants $20{,}000$ rows across $4$ elongated, $100$-station density chains plus $200$ isolated noise points ($20{,}200$ rows total) and verifies exact recovery of all $4$ chains and all $200$ Noise labels via SKKDTree. In dbscan_metric_tests.rs, dbscan_acceptance_metrics_recovers_non_convex_concentric_rings_where_kmeans_cannot fits SKDBSCAN and SKKMeans on two concentric rings ($r = 1$ and $r = 4$) with noise: SKDBSCAN achieves sk_adjusted_rand_score == 1.0 and sk_v_measure_score == 1.0 while SKKMeans scores below $0.25$; and dbscan_acceptance_metrics_silhouette_excludes_noise_and_scores_fitted_model verifies that SKSilhouetteScorer evaluates SKDBSCANModel directly via SKUnsupervisedScorer::score while excluding SKClusterLabel::Noise rows.

6. Look inside

FileResponsibility
dbscan/config.rsSKDBSCANMetric, SKDBSCANAlgorithm, SKDBSCANSearchStrategy, validated configuration
dbscan/builder.rs, dbscan/core_implementation.rsSKDBSCANBuilder defaults/validation and immutable SKDBSCAN
dbscan/region_query.rsAuto strategy resolution, SKDBSCANIndex, inclusive sk_radius_neighborhoods
dbscan/expansion.rscore detection, deterministic BFS expansion and representation-preserving sk_extract_core_samples
dbscan/validation.rsempty, shape, finiteness and CSR/CSC guards
dbscan/fit.rs, dbscan/model.rsSKUnsupervisedFit, fit_predict, SKDBSCANModel and SKDBSCANCoreSearch
dbscan/predict.rsnearest-core SKClustererPredictor across all four dense/CSR pairs
acceptance_tests/dbscan_*_tests.rstiny, $20{,}200$-row large, representation, determinism, concurrency and metric suites

7. What this unlocks

sciencekit_cluster now pairs centroid partitioning (SKKMeans) with non-convex density clustering (SKDBSCAN). Both speak the same SKClusterLabel and SKClustererPredictor contracts, and SKDBSCAN gives the spatial trees from Chapter 25 their first real radius_neighbors consumer while proving that noise-aware clustering metrics (Chapter 31) compose end to end without sentinel-integer bugs.

Feature unions: parallel feature branches and honest concatenation

A linear pipeline is a single conveyor belt: stage one transforms the input, stage two transforms stage one’s output, and the final estimator learns from the last stage. Real tabular and text problems rarely fit on a single belt. One branch may standardize continuous measurements, a second branch may one-hot encode categorical codes into a wide sparse indicator matrix, and a third branch may impute missing values and attach a missingness mask — all computed from the same input rows and glued side by side before a classifier or regressor sees them.

This chapter builds SKFeatureUnion in crates/sciencekit_pipeline/src/feature_union/ (capability feature-union): compile-time heterogeneous branches through tuples, a dynamic boxed fallback for runtime lists, CSR-preserving horizontal concatenation, member-indexed error context, and seamless nesting inside SKPipeline.


1. The problem, in plain words

Suppose an input table $X$ has $n$ rows and $p$ columns, and $m$ different feature transformers $T_0, T_1, \dots, T_{m-1}$ each extract a different view of $X$:

$$ Z = \bigl[, T_0(X) ;\big|; T_1(X) ;\big|; \dots ;\big|; T_{m-1}(X) ,\bigr] $$

If branch $k$ produces $w_k$ columns, the combined matrix $Z$ still has $n$ rows and its width is the sum of the branch widths:

$$ W = \sum_{k=0}^{m-1} w_k $$

Four engineering hazards hide behind that simple picture:

  1. Different types per branch. A SKStandardScaler, a SKSimpleImputer<f64> and a SKMissingIndicator<f64> are distinct Rust structs whose fitted models have distinct types. Forcing every branch into Box<dyn ...> erases those types even when the caller knows every branch at compile time.
  2. Dense and sparse outputs side by side. If branch zero emits a 2-column dense matrix and branch one emits a 10,000-column sparse one-hot matrix, converting the sparse branch to dense would allocate $10{,}000 \times n$ zeros and destroy memory.
  3. Silent column-offset bugs. When stacking sparse compressed-row (CSR) matrices horizontally, stored column $c$ of branch $k$ must land at global column $c + \sum_{j < k} w_j$. Off-by-one offsets corrupt downstream weights without crashing.
  4. Opaque errors. When the third branch of a union rejects an input, knowing only “shape mismatch” without knowing which branch failed turns debugging into guesswork.

2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Tuple-based SKFeatureUnionStages<F> up to eight members, plus Vec<Box<dyn SKBlockTransformer<F>>> fallbackMost unions combine two to five branches known at compile time; tuples keep every concrete Fitted model accessible without heap boxing. Runtime-built or larger unions (> 8 branches) drop cleanly to the boxed list over the exact same SKFeatureBlock medium.A boxed-only Vec<Box<dyn ...>> design (loses concrete fitted-stage inspection in the common case) or left-nested pairs like ((A, B), C) (awkward to destructure when all branches are peers).
Any sparse member promotes the union output to CSR; all-dense stays denseConverting a narrow dense branch into CSR entries costs $O(\text{non-zeros})$ work; densifying a wide sparse branch costs $O(n \times w_{\text{sparse}})$ memory. Promoting to CSR preserves sparsity end-to-end.Always emitting dense (memory blow-up on categoricals/text) or always emitting CSR (unnecessary overhead when every branch is dense).
Scalar-free SKFeatureUnion<Stages> configuration + SKFeatureUnionAritySKFeatureUnion holds no floating-point constants of its own. Separating member counting (SKFeatureUnionArity) from SKFeatureUnionStages<F> lets .build() validate non-emptiness without a turbofish scalar, and lets scalar-generic branches serve both f32 and f64.Adding PhantomData<F> to SKFeatureUnion<F, Stages> (forces callers to annotate f64 even before data arrives).
Direct SKPipelineTransformer implementations over sealed f32 and f64sciencekit_pipeline already provides a blanket SKPipelineTransformer<F> implementation for any T: SKUnsupervisedFit<F>. Implementing SKPipelineTransformer<f32> and SKPipelineTransformer<f64> directly for SKFeatureUnion<Stages> and non-empty SKPipelineBuilder satisfies Rust’s orphan/coherence rules because SKFloat is sealed to f32 and f64.Implementing SKUnsupervisedFit on SKFeatureUnion (would clone the input block an extra time at every nested boundary).
Dual error surface (fit / fit_checked and transform / transform_checked)SKError variants that carry messages gain "feature union member {index}: ..." automatically, while structured fixed-field variants (ShapeMismatch, UnsupportedRepresentation) stay intact for pattern matching and also expose .member_index() through SKFeatureUnionMemberError recorded directly on the operation span.Flattening every member failure into SKError::Conversion(String) (breaks callers matching structured SKError variants).

3. The concepts, taught from zero

Fan-out and horizontal concatenation

In a linear pipeline (SKPipeline), data flows serially: stage two sees the output of stage one. In a feature union (SKFeatureUnion), data fans out: every member sees the exact same input block &SKFeatureBlock<F>, fits its own independent model, and transforms the input into its own output block before the union stitches the columns left-to-right.

flowchart LR
    accTitle: Fan-out fitting and horizontal concatenation inside SKFeatureUnion
    accDescr: An input feature block fans out unchanged to three parallel branches: a sub-pipeline that imputes and scales numeric columns, a sparse one-hot encoder, and a missingness indicator. Their outputs are concatenated horizontally in declaration order into one wider block fed to the final estimator.
    IN["SKFeatureBlock<br/>n rows × p cols"] --> B0["Member 0<br/>Imputer → Scaler<br/>width w₀"]
    IN --> B1["Member 1<br/>One-Hot CSR<br/>width w₁"]
    IN --> B2["Member 2<br/>Missing mask<br/>width w₂"]
    B0 --> CAT["Concatenate<br/>width w₀ + w₁ + w₂"]
    B1 --> CAT
    B2 --> CAT
    CAT --> EST["Next Stage or<br/>Estimator"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef violet fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    class IN sky
    class B0,B1,B2 emerald
    class CAT violet
    class EST amber

How CSR horizontal stacking works without densifying

A Compressed Sparse Row (CSR) matrix stores only non-zero entries row by row using three flat arrays:

  • values: each stored non-zero number;
  • column_indices: which column each stored number belongs to;
  • row_pointers: where each row starts and ends inside values and column_indices.

Suppose for row $r$, member $0$ (width $w_0 = 2$, dense) produces $[1.5, 0.0]$ and member $1$ (width $w_1 = 3$, CSR) stores $4.0$ at local column $1$. Rather than expanding member $1$ into $[0.0, 4.0, 0.0]$, the union pre-counts total stored entries across all members, reserves exact buffer capacities once, and walks row $r$ across all members keeping a cumulative column offset:

  • Offset $0$ (member $0$, width $2$): non-zero entry $(0 + 0,; 1.5)$ is appended; the exact zero at column $1$ stays implicit.
  • Offset $2$ (member $1$, width $3$): stored entry $(2 + 1,; 4.0) = (3,; 4.0)$ is appended.

Because each member’s columns are visited in ascending order and each member’s offset shifts past all previous widths, every row’s combined column indices are strictly increasing by construction.

flowchart TB
    accTitle: Representation policy when concatenating member outputs
    accDescr: Before allocating an output buffer, SKFeatureUnion validates that every member returned the expected row count and a supported Dense or CSR representation. If all members emitted Dense, ndarray::concatenate stacks them into a Dense block. If at least one member emitted Sparse CSR, every member is merged row-by-row with cumulative column offsets into a single CSR block.
    V["Validate outputs<br/>rows == n, no CSC"] --> Q{"Any member<br/>Sparse CSR?"}
    Q -->|"No (all Dense)"| D["Axis(1) stack<br/>SKFeatureBlock::Dense"]
    Q -->|"Yes (any Sparse)"| S["Row offset merge<br/>SKFeatureBlock::Sparse"]
    V -->|"Mismatch or CSC"| E["ShapeMismatch or<br/>UnsupportedRepr"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef violet fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    classDef rose fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#7f1d1d
    class V,Q sky
    class D emerald
    class S violet
    class E rose

Object-safe erasure for dynamic unions (SKBlockTransformer)

Why can we not write Vec<Box<dyn SKPipelineTransformer<f64>>> directly? In Rust, a trait with an associated type (type Fitted) requires every trait object in the Vec to share the same Fitted type — which fails as soon as you mix a scaler and an imputer.

SKBlockTransformer<F> solves that cleanly by erasing only the fitted state behind SKBoxedFittedStage (Box<dyn Any + Send + Sync>): fit_block boxes the concrete Stage::Fitted value, and transform_block downcasts it back to &Stage::Fitted inside the blanket implementation. Every Send + Sync pipeline transformer gets SKBlockTransformer<F> for free, without requiring Clone on estimators.


4. Each public object, explained

  • SKFeatureUnion<Stages> — the configured union estimator. Built exclusively via SKFeatureUnion::build() (alias SKFeatureUnion::start()) or SKFeatureUnion::boxed::<F>(). Stores Arc<Stages> internally so .fit(&block) borrows &self without requiring Stages: Clone and transfers shared stage configuration into the fitted model.
  • SKFeatureUnionBuilder<Stages> — configures .stages(tuple_or_vec), incremental .with_stage(stage) (flat tuples up to eight members via SKAppendUnionStage), .with_boxed_stage(stage) (dynamic Vec), .backend(SKBackendKind) (default Faer), and .execution_mode(...) (default Automatic). .build() rejects zero members with SKError::InvalidHyperparameter.
  • SKFeatureUnionArity and SKFeatureUnionStages<F> — SKFeatureUnionArity reports number_of_members(&self) without needing a float parameter; SKFeatureUnionStages<F> fits and transforms tuples (Stage0,) through (Stage0, ..., Stage7) and Vec<Box<dyn SKBlockTransformer<F>>>.
  • SKBlockTransformer<F> and SKBoxedFittedStage — the object-safe dynamic fallback contract and its Send + Sync type-erased fitted state.
  • SKFeatureUnionModel<F, Stages> — the Send + Sync fitted union returned by .fit(&block). Exposes .transform(&block), .transform_checked(&block), .number_of_members(), .member_widths(), .number_of_features() (and .number_of_output_features()), .number_of_input_features(), .stages(), .fitted_stages(), .backend(), and .execution_mode().
  • SKFeatureUnionMemberError — exposes .member_index() (Option<usize>), .error() (&SKError), and .into_sk_error() so callers using fit_checked or transform_checked know both the failing member and the exact SKError variant.

5. Walking through the real companion tests

Every behavior in the feature-union specification is locked down by companion *_tests.rs modules under crates/sciencekit_pipeline/src/feature_union/ and acceptance_tests/:

two_member_scalar_chain_counts_members_and_fits_both_stages & incremental_with_stage_builds_tuples_up_to_eight_members

In union_stages_tests.rs, a (SKStandardScaler, SKMinMaxScaler<f64>) tuple is built and fitted on a $2 \times 2$ block, proving both concrete fitted models (fitted_stages.0 and fitted_stages.1) keep their static types. The second test chains eight .with_stage(...) calls and fits the resulting scalar-generic union on an f32 block without rebuilding.

hand_checkable_two_member_concatenation_preserves_member_order & every_member_sees_the_same_input_rows_and_columns

In union_fit_tests.rs, input [[1.0, 10.0], [3.0, 20.0]] passes through a standard scaler ($[-1, -1]$ and $[1, 1]$) and a min-max scaler ($[0, 0]$ and $[1, 1]$), asserting the exact $2 \times 4$ output [[-1.0, -1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]]. Pairing SKStandardScaler with SKSimpleImputer then proves both members learn raw means [4.0, 20.0] — unlike a serial pipeline, where the second stage would see centered zero means.

all_sparse_members_concatenate_to_csr_with_shifted_column_offsets & mixed_dense_then_sparse_promotes_union_output_to_csr_with_exact_offsets

In union_concatenation_tests.rs, a sparse-only test stage (SKSparseOnlyShiftStage) returns UnsupportedRepresentation if its input is ever densified; pairing it with SKSimpleImputer on a CSR input proves the input remains sparse and the shifted columns land at offsets 0..2 and 2..5. Combining dense SKSimpleImputer output with sparse SKMissingIndicator output (sparse_output(true)) then proves a single sparse member promotes the entire union output to CSR.

boxed_dynamic_union_matches_tuple_union_on_dense_outputs & boxed_dynamic_union_supports_more_than_eight_members

In union_boxed_tests.rs, a Vec<Box<dyn SKBlockTransformer<f64>>> union is compared element-for-element against its tuple twin on both dense and mixed CSR outputs, and a 10-member dynamic union verifies construction beyond the 8-member static tuple ceiling.

empty_tuple_and_empty_boxed_unions_are_rejected_with_invalid_hyperparameter, member_failure_in_fit_wraps_member_index_in_tuple_and_boxed_unions & row_count_mismatch_and_feature_count_mismatch_return_shape_mismatch

In union_validation_tests.rs, empty tuple and empty boxed builders fail at .build() with SKError::InvalidHyperparameter. Failing stages at indices 1 and 2 verify "feature union member k" context and fit_checked / transform_checked structured error preservation, while mismatched member row counts, wrong query column counts, and CSC sparse outputs fail before any output buffer is written.

accessors_report_member_count_widths_and_summed_total_width, non_default_backend_and_execution_mode_propagate_to_fitted_model & concurrent_transform_across_threads_agrees_with_sequential_result

In union_model_tests.rs, a three-branch union with widths [2, 1, 2] verifies that member_widths().iter().sum() equals number_of_features() (5), non-default SKBackendKind::MatrixMultiply and SKExecutionMode::InProcessSynchronous overrides propagate into the fitted model, compile-time Send + Sync bounds hold for both tuple and boxed models, and eight threads transforming concurrently inside std::thread::scope match the sequential result bit-for-bit.

scaler_union_one_hot_encoder_into_classifier_concatenates_columns_and_predicts, sub_pipeline_branch_composes_inside_feature_union_and_regressor_pipeline, nested_feature_unions_and_sub_pipelines_compose_into_regressor_metrics & large_sparse_feature_union_pipeline_fits_without_densification

In union_pipeline_tests.rs and acceptance_tests/feature_union_{small,large}_tests.rs, SKFeatureUnion runs as a stage inside SKPipeline — uniting a continuous scaler with a sparse SKOneHotEncoder ahead of SKLogisticRegression, nesting multi-stage SKPipelineBuilder chains and inner unions ahead of SKLinearRegression ($R^2 > 0.99$), and fitting 600-row sparse designs end-to-end without densification.


6. Look inside

FileResponsibility
crates/sciencekit_pipeline/src/feature_union/mod.rsPure dispatcher declaring submodules, re-exports, and companion test suites.
crates/sciencekit_pipeline/src/feature_union/builder.rsSKFeatureUnion and SKFeatureUnionBuilder, empty-union guard, backend and execution-mode configuration.
crates/sciencekit_pipeline/src/feature_union/append.rsSKAppendUnionStage extending flat tuples from zero up to eight members.
crates/sciencekit_pipeline/src/feature_union/stages.rsSKFeatureUnionArity and SKFeatureUnionStages<F> implemented for tuples of one through eight stages.
crates/sciencekit_pipeline/src/feature_union/boxed.rsSKBlockTransformer<F> and SKBoxedFittedStage dynamic fallback for runtime member lists.
crates/sciencekit_pipeline/src/feature_union/concatenate.rsUpfront shape/representation checks, dense Axis(1) stacking, and pre-sized CSR horizontal concatenation.
crates/sciencekit_pipeline/src/feature_union/errors.rsSKFeatureUnionMemberError and sk_wrap_member_error preserving structured SKError variants with member indices.
crates/sciencekit_pipeline/src/feature_union/model.rsSKFeatureUnionModel<F, Stages>, fit / fit_checked, and transform / transform_checked under sk_run_operation.
crates/sciencekit_pipeline/src/feature_union/accessors.rsWidth, member-count, stage, fitted-stage, backend, and execution-mode accessors.
crates/sciencekit_pipeline/src/feature_union/pipeline_stage.rsSKPipelineTransformer implementations for SKFeatureUnion and nested SKPipelineBuilder branches.

7. Recap

  • SKFeatureUnion fans one input block out to parallel branches and concatenates their outputs left-to-right in declaration order.
  • Static tuples up to eight members keep concrete types; Vec<Box<dyn SKBlockTransformer<F>>> provides an object-safe runtime escape hatch over the same SKFeatureBlock medium.
  • Sparsity is respected end-to-end: all-dense outputs stay dense, any sparse member promotes the concatenated block to CSR with cumulative column offsets, and sparse inputs are never densified.
  • Errors stay structured and indexed: every member failure surfaces its zero-based member index while preserving the underlying SKError variant and recording directly on its observability span.
  • Unions and pipelines nest freely: a union is a stage in SKPipeline, and a multi-stage SKPipelineBuilder is a valid branch inside SKFeatureUnion.

Principal Component Analysis: centering, three solvers and honest sparsity

Most real feature tables carry redundancy: measurements move together along a handful of hidden directions while the remaining coordinates contribute mostly noise. Principal Component Analysis (SKPCA) finds the orthogonal unit axes along which a centered dataset varies the most, orders them by how much variance each axis captures, and projects observations onto the leading $k$ axes.

The algebra looks short on a blackboard, yet turning it into a production estimator forces three engineering choices into the open:

  1. One algorithm, three regimes. Exact full SVD is unbeatable on small or nearly full-rank matrices, symmetric covariance eigendecomposition wins on tall-and-narrow tables, and the seeded randomized SVD from Chapter 39 scales when only a few components are needed from a large matrix.
  2. Centering changes sparsity. Subtracting a non-zero column mean turns every implicit zero of a sparse CSR matrix into a non-zero number. Pretending otherwise silently allocates gigabytes; rejecting all sparse input throws away the implicit-centering capability we just built in sciencekit_math.
  3. Sign and thread-count determinism. Singular vectors and eigenvectors are only defined up to $\pm 1$, and parallel matrix products can re-associate floating-point sums unless row blocks are fixed.

This chapter walks through crates/sciencekit_decomposition/ (capability principal-component-analysis), explaining the mathematics from zero, every public type and method, and the companion tests that pin each guarantee down.


1. The problem, in plain words

Suppose we observe $n$ rows and $d$ numeric features in a matrix $X \in \mathbb{R}^{n \times d}$. Before looking for directions of spread, we shift the cloud so its empirical centre sits at the origin:

$$ \mu_j = \frac{1}{n} \sum_{i=1}^{n} X_{i,j}, \qquad X_c = X - \mathbf{1}\mu^{\top} $$

Given a target dimension $k \le \min(n, d)$, we want $k$ orthonormal row vectors $W \in \mathbb{R}^{k \times d}$ ($W W^{\top} = I_k$) whose projections

$$ Z = X_c W^{\top} \in \mathbb{R}^{n \times k} $$

capture as much of the unbiased sample variance as possible, and reconstruct the original table with minimal Frobenius error via

$$ \widehat{X} = Z W + \mathbf{1}\mu^{\top}. $$


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Dedicated sciencekit_decomposition crate with SKPCA<F> and SKPCAModel<F>Keeps configuration (SKPCA) immutable and separate from learned state (SKPCAModel), matching every estimator in the workspace and preparing a shared home for SKTruncatedSVD and SKIncrementalPCA.Mutating SKPCA in place during fit — makes “not yet fitted” a runtime error instead of a type error.
Three concrete solvers behind SKPCASolver (Full, Randomized, CovarianceEigh) plus deterministic AutoEach regime has a different asymptotic bottleneck: full SVD for small or high-rank requests, $d \times d$ covariance eigh when $n \gg d$, and randomized range finding when $k \ll \min(n, d)$. Recording resolved_solver() on the model makes the heuristic inspectable.Hard-coding full SVD everywhere (too slow on wide or tall tables) or randomized SVD everywhere (unnecessary approximation on a $20 \times 6$ table).
Implicit sparse centering on Randomized; explicit allow_densification(true) gate on Full and CovarianceEighSKRandomizedSvdBuilder folds rank-one mean corrections into its thin products without ever allocating $X_c$. Full and CovarianceEigh genuinely need dense storage, so they reject CSR with UnsupportedRepresentation naming Randomized and SKTruncatedSVD unless the caller opts in, in which case a tracing::warn! reports estimated_dense_bytes.Silently calling to_dense() on CSR inputs — an out-of-memory trap in production pipelines.
Component-row sign convention and orthonormal completion (sk_orient_components)Completing zero-norm directions on rank-deficient inputs via deterministic Gram-Schmidt and making the largest-magnitude coordinate of each row of components non-negative works identically whether the solver computed $U$ (Full, Randomized) or only eigenvectors (CovarianceEigh), so all three solvers satisfy $W W^{\top} = I_k$ and agree in sign.Orienting only by left singular vectors $U$ — CovarianceEigh never materializes $U$, and zero singular values in Randomized would leave zero rows.
Fixed 256-row blocks for dense transform and inverse_transformSplitting row projections into fixed-size 256-row chunks (run sequentially or via rayon depending on the resolved SKExecutionPlan) keeps scratch memory bounded and ensures identical floating-point evaluation across thread counts.Passing a thread-dependent chunk size into GEMM — 1-thread and 4-thread runs could differ by rounding order.
Explicit non-goals for this change. Sparse exact full/eigh solvers, kernel PCA, streaming/incremental PCA (SKIncrementalPCA), GPU kernels, memmap2-backed storage and model export (Wave 7) are intentionally out of scope here and recorded in docs/PRD.md.

3. The concepts, taught from zero

Why SVD and covariance eigendecomposition find the same axes

Write the thin singular-value decomposition of the centered matrix as $X_c = U \Sigma V^{\top}$, where $U$ has orthonormal columns, $\Sigma = \operatorname{diag}(\sigma_1, \dots, \sigma_r)$ has $\sigma_1 \ge \sigma_2 \ge \dots \ge 0$, and $V$ has orthonormal columns in $\mathbb{R}^d$. Form the unbiased sample covariance matrix ($n \ge 2$):

$$ C = \frac{1}{n - 1} X_c^{\top} X_c = \frac{1}{n - 1} V \Sigma^2 V^{\top}. $$

Read that equation from right to left: the columns of $V$ are eigenvectors of $C$, and the corresponding eigenvalues are the explained variances

$$ \lambda_j = \frac{\sigma_j^2}{n - 1}. $$

Dividing each $\lambda_j$ by the total centered variance

$$ \sigma_{\text{total}}^2 = \frac{1}{n - 1} \lVert X - \mathbf{1}\mu^{\top} \rVert_F^2 $$

gives explained_variance_ratio. Computing $\sigma_{\text{total}}^2$ directly from $(X, \mu)$ matters: Randomized only computes the top $k$ singular values, yet its variance ratios still divide by the entire variance of the dataset rather than only the retained $k$ modes.

Non-negative two-pass variance on sparse CSR

For a sparse CSR matrix, expanding $\sum (x - \mu)^2 = \sum x^2 - n\mu^2$ can suffer catastrophic cancellation when $\mu$ is large. Instead, sk_total_centered_variance in centering.rs sums $(v - \mu_j)^2$ over the nnz stored entries in column $j$ and adds $(n - \text{nnz}_j)\mu_j^2$ for the implicit zeros. Every term is non-negative, the cost is $\mathcal{O}(\text{nnz} + d)$, and no dense matrix is allocated.

How Auto picks a solver

flowchart TD
    accTitle: Automatic solver resolution in SKPCA
    accDescr: Given a feature view and component count k, SKPCA checks whether an explicit solver was requested. Under Auto, sparse input without allow_densification routes to Randomized; otherwise k at least four fifths of min(n, d) routes to Full, tall-skinny matrices with n greater than 10d and d at most 1000 route to CovarianceEigh, small matrices with max(n, d) at most 500 route to Full, and remaining large matrices route to Randomized.
    classDef input fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef gate fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef full fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef cov fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef rand fill:#fff7ed,stroke:#ea580c,color:#7c2d12

    In["Input view + k<br/>svd_solver = Auto"]:::input --> Sp{"CSR view and<br/>!allow_densification?"}:::gate
    Sp -->|yes| R1["Randomized<br/>implicit centering"]:::rand
    Sp -->|no| Hi{"5k >= 4 min(n, d)?"}:::gate
    Hi -->|yes| F1["Full SVD"]:::full
    Hi -->|no| Tall{"n > 10d and<br/>d <= 1000?"}:::gate
    Tall -->|yes| C1["CovarianceEigh<br/>d x d covariance"]:::cov
    Tall -->|no| Sm{"max(n, d) <= 500?"}:::gate
    Sm -->|yes| F2["Full SVD"]:::full
    Sm -->|no| R2["Randomized<br/>range finder"]:::rand

Notice the integer test 5 * k >= 4 * min(n, d): it expresses $k \ge 0.8 \min(n, d)$ without floating-point rounding ambiguity at boundaries.

Whitening and near-zero variance safety

When whiten(true) is configured, each projected coordinate $c$ is divided by its spread so every retained axis has unit sample variance:

$$ s_c = \sqrt{\max(\lambda_c, \varepsilon)}, \qquad Z_{\text{white}}[:, c] = \frac{Z[:, c]}{s_c}. $$

Flooring $\lambda_c$ at machine epsilon ($\varepsilon = \text{F::epsilon}()$) before taking the square root prevents rank-deficient or constant columns from producing NaN or $\pm\infty$, while leaving genuine components untouched. inverse_transform multiplies component row $c$ by $s_c$ before adding $\mu$, so whitening remains invertible on full-rank subspaces.


4. Each public object, explained

flowchart LR
    accTitle: Data and state flow across SKPCABuilder, SKPCA and SKPCAModel
    accDescr: SKPCABuilder validates configuration into an immutable SKPCA estimator. Calling fit dispatches to Full, Randomized or CovarianceEigh under a Fit observability span and produces SKPCAModel, which runs transform and inverse_transform under Transform spans carrying the configured backend.
    classDef builder fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef est fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef model fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef op fill:#fff7ed,stroke:#ea580c,color:#7c2d12

    B["SKPCABuilder&lt;F&gt;<br/>defaults + validation"]:::builder -->|build| E["SKPCA&lt;F&gt;<br/>immutable config"]:::est
    E -->|fit| S["Solver portfolio<br/>Fit span + backend"]:::op
    S --> M["SKPCAModel&lt;F&gt;<br/>W, variance, mean"]:::model
    M -->|transform| Z["Projected Array2&lt;F&gt;<br/>m x k"]:::op
    Z -->|inverse_transform| X["Reconstructed Array2&lt;F&gt;<br/>m x d"]:::op

SKPCASolver

What it is — the closed solver enum in pca/config.rs: Auto (default), Full, Randomized and CovarianceEigh.

Why it exists — lets callers either rely on Auto or pin an exact numerical path while reading back the concrete choice from model.resolved_solver().

SKPCABuilder<F> and SKPCA<F>

What they are — the mandatory builder (pca/builder.rs) and immutable estimator (pca/core_implementation.rs), generic over F: SKFloat because tolerance is a scalar.

Defaults and setters:

  • number_of_components(usize) — optional (None by default, resolving to $\min(n, d)$ at fit time);
  • svd_solver(SKPCASolver) — SKPCASolver::Auto;
  • whiten(bool) — false;
  • tolerance(F) — 0.0 (must be finite and $\ge 0$);
  • number_of_power_iterations(usize) — 5 (must be $> 0$);
  • allow_densification(bool) — false;
  • random_seed(u64) — 0;
  • backend(SKBackendKind) — SKBackendKind::Faer;
  • execution_mode(...) — SKExecutionMode::Automatic.

SKPCA<F> implements SKUnsupervisedFit<F, Model = SKPCAModel<F>, Error = SKError> (for F: SKBackendSelection) and provides fit_transform, which fits and projects under a single FitTransform observability span.

SKPCAModel<F>

What it is — the fitted model (pca/model.rs), Clone + Debug + Send + Sync.

Accessors and operations:

  • components() (k × d view), explained_variance(), explained_variance_ratio(), singular_values(), mean();
  • resolved_solver(), number_of_components(), number_of_features(), whiten(), backend(), execution_mode();
  • transform (inherent and via SKFeatureTransformer<F>) accepting both dense and CSR views without densifying sparse inputs — for CSR it computes $X W^{\top} - \mathbf{1}(W\mu)^{\top}$ through sk_csr_dense_product;
  • inverse_transform accepting projected coordinates and mapping back to $\mathbb{R}^{m \times d}$.

Because SKPCA<F> implements SKUnsupervisedFit<F> and SKPCAModel<F> implements SKFeatureTransformer<F, Output = Array2<F>>, SKPCA<F> automatically satisfies sciencekit_pipeline::SKPipelineTransformer<F>.


5. Walking through the real companion tests

Every guarantee above is locked by a companion *_tests.rs module under crates/sciencekit_decomposition/src/:

  1. Zero-mean centering and honest sparse moments (pca_centering_tests.rs). pca_centering_computes_hand_checked_means_and_zero_mean_centered_data checks hand-computed means [4.0, 25.0, 2.0] and verifies every centered column averages to zero. pca_centering_sparse_means_and_total_variance_match_dense_without_densifying proves the two-pass CSR variance equals the dense calculation.
  2. Exact full SVD, randomized SVD and covariance eigh (pca_full_tests.rs, pca_randomized_tests.rs, pca_covariance_tests.rs). pca_full_recovers_diagonal_principal_axes_and_reconstructs_centered_data checks the $(1/\sqrt{2}, 1/\sqrt{2})$ principal axis, orthonormal rows and exact reconstruction. pca_randomized_agrees_with_full_svd_on_low_rank_dense_design and pca_covariance_sorts_eigenvalues_descending_and_matches_full_svd verify that all three solvers agree on components, singular values, variances and ratios.
  3. Solver routing (pca_solver_tests.rs). pca_solver_auto_routes_small_high_rank_covariance_and_large_designs exercises every branch of sk_resolve_pca_solver: small dense $\to$ Full, high rank fraction $\to$ Full, tall-skinny $\to$ CovarianceEigh, large truncated $\to$ Randomized, and default sparse $\to$ Randomized.
  4. Spans, whitening and round-trip reconstruction (pca_fit_tests.rs, pca_transform_tests.rs). pca_fit_transfers_configured_backend_and_records_fit_span and pca_transform_records_model_backend_in_transform_and_fit_transform_spans capture sciencekit.operation spans to prove a configured non-default backend flows from builder to estimator to fitted model spans. pca_transform_whitening_normalizes_component_variance_and_handles_near_zero_variance verifies unit sample variance on full-rank data and finite outputs on collinear data.
  5. Sparse representation policy and warnings (pca_validation_tests.rs). pca_validation_sparse_randomized_matches_dense_without_densifying fits CSR data with zero warnings; pca_validation_full_and_covariance_reject_sparse_by_default_with_alternatives checks the UnsupportedRepresentation error naming Randomized and SKTruncatedSVD; and pca_validation_allow_densification_warns_with_memory_cost_and_matches_dense asserts the warning records estimated_dense_bytes = 400 on a $10 \times 5$ f64 CSR matrix.
  6. Thread-count invariance, concurrency and metrics (pca_concurrency_tests.rs, acceptance_tests/). pca_concurrency_repeated_fits_agree_across_runs_and_rayon_thread_counts runs 1-thread and 4-thread rayon pools and asserts exact assert_eq! equality on components and projections. acceptance_pca_produces_reconstruction_metrics_via_sciencekit_metrics evaluates sk_mean_squared_error and sk_r2_score across $k = 1, 2, 3$ on a planted rank-3 table, confirming reconstruction error drops monotonically and reaches $R^2 > 0.9999$ at $k = 3$.

6. Recap

  • SKPCA<F> centers features, chooses among Full, Randomized and CovarianceEigh (or resolves Auto deterministically), fixes component signs by largest-magnitude coordinate and returns SKPCAModel<F>.
  • Sparse CSR inputs fit natively without densification under Randomized, and fail loudly with actionable alternatives under dense-only solvers unless allow_densification(true) is set.
  • transform and inverse_transform preserve zero-copy input boundaries, support optional epsilon-floored whitening, record the model’s SKBackendKind in observability spans and stay bit-identical across thread counts.

JSON debug format: reading a fitted model with your eyes

1. The problem we were solving

Production model persistence wants binary files: contiguous IEEE-754 buffers, random access by tensor offset and zero text parsing. That is the job of the binary Safetensors adapter. Binary efficiency, however, comes with an immediate tax whenever a human needs to answer a simple question:

  • Did my SKStandardScaler actually center column 2, or did with_mean default to false?
  • Why did two training runs on different machines diverge in the third decimal place?
  • Can I check a tiny golden model fixture into Git and review parameter changes with git diff?

With a binary file, every one of those questions requires a bespoke inspection tool. In sciencekit, fitted estimators already speak a single format-agnostic vocabulary in sciencekit_common: SKExportable produces an SKModelState<F>, and SKImportable reconstructs a fitted estimator from it. Adding a human-readable JSON debug adapter in crates/sciencekit_interop/src/json/ gives every exportable model a diffable, hand-inspectable text representation without touching a single estimator crate.


2. The idea in one picture

flowchart LR
    accTitle: JSON debug export, inspection and validated import pipeline
    accDescr: An SKExportable model produces an SKModelState, which SKJsonDebugWriter validates for finite scalars and renders as deterministic pretty or compact JSON. SKJsonDebugReader parses the JSON, validates format_version, dtypes, unique names and tensor shapes before reconstructing SKModelState and importing back into SKImportable.

    M1["Fitted model<br/>SKExportable"]:::violet --> S1["SKModelState<br/>metadata + BTreeMap"]:::blue
    S1 --> W["SKJsonDebugWriter<br/>Pretty | Compact"]:::green
    W --> J["Deterministic JSON<br/>sorted keys, flat arrays"]:::amber
    J --> R["SKJsonDebugReader<br/>validate before work"]:::orange
    R -->|"valid v1"| S2["SKModelState<br/>exact round-trip"]:::blue
    R -->|"corrupt / mismatch"| E["Structured SKError<br/>no partial model"]:::rose
    S2 --> M2["Reconstructed model<br/>SKImportable"]:::violet

    classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef rose fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

The central state SKModelState<F> sits on both sides of the wire. Fitted models implementing SKExportable and SKImportable (such as SKLinearRegressionModel<F>, and other estimator families as their export contracts land) never know JSON exists; they export and import SKModelState<F>, while sciencekit_interop::json owns the text grammar and every byte of serde_json dependency.


3. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Keep sciencekit_common free of serde and own the wire schema in sciencekit_interop::jsonFormat policy (field names, version envelope, untagged hyperparameters, forward-compatible unknown fields) belongs to the format adapter, not the core trait crate.Deriving Serialize/Deserialize directly on SKModelState — couples internal Rust enum layout to the wire format and leaks serde into sciencekit_common.
Deterministic BTreeMap key order + shortest exact float formattingTwo runs that learn the same parameters emit byte-for-byte identical JSON regardless of insertion order, so git diff only highlights genuine numerical changes. Native f32 slices serialize directly as f32 (0.1 instead of 0.10000000149011612).HashMap maps or casting f32 through f64 on write — scrambles key order across runs and pollutes single-precision fixtures with binary64 conversion noise.
Custom duplicate-preserving map visitor on readStandard serde BTreeMap deserialization silently overwrites duplicate object keys ("w": ..., "w": ...). Reading entries into a sequence first lets validation deterministically reject duplicate tensor or hyperparameter names.Deserializing straight into BTreeMap or serde_json::Value — silently drops the earlier duplicate tensor and hides file corruption.
Check format_version before requiring version-1 fields, ignore unknown fields within version 1If major version 2 renames top-level sections, a version-1 reader still reports UnsupportedRepresentation on the version header rather than a confusing missing-field parse error, while minor additive hints inside version 1 stay forward-compatible.#[serde(deny_unknown_fields)] — breaks older readers whenever an optional diagnostic annotation is added within major version 1.
Document memory expansion for large tensors instead of pretending JSON is a checkpoint formatFlat UTF-8 decimal arrays expand past raw 8-byte binary buffers and materialize in memory. Stating that boundary clearly points production checkpoints at Safetensors while keeping JSON simple and self-contained.Base64-encoding tensor buffers inside JSON — destroys the entire point of reading tensor values with human eyes.

4. The JSON debug schema, taught from zero

When SKJsonDebugWriter serializes a fitted four-feature SKStandardScaler in the default SKJsonFormatMode::Pretty mode, it produces:

{
  "format_version": 1,
  "estimator": "SKStandardScaler",
  "dtype": "f64",
  "feature_count": 4,
  "class_labels": null,
  "hyperparameters": {
    "with_mean": true,
    "with_std": true
  },
  "tensors": {
    "standard_scaler.mean": {
      "dtype": "F64",
      "shape": [
        4
      ],
      "values": [
        1.0,
        2.0,
        3.0,
        4.0
      ]
    }
  }
}

Every field has one job:

  1. format_version (SK_JSON_DEBUG_FORMAT_VERSION = 1): the major version of the JSON debug envelope itself. Any other value is rejected immediately with SKError::UnsupportedRepresentation. When an estimator’s own SKModelMetadata::format_version() differs from 1, an optional estimator_format_version field is emitted so arbitrary metadata versions round-trip losslessly without cluttering version-1 fixtures.
  2. estimator, dtype, feature_count, class_labels: the model identity contract from SKModelMetadata. The top-level "dtype" names the Rust model scalar ("f32" or "f64"), while classifiers populate "class_labels" in canonical index order so SKLabelTable mappings remain reversible.
  3. hyperparameters: a sorted map of untagged JSON booleans, 64-bit signed integers, finite 64-bit floats, strings and nested lists mirroring SKParameterValue. Because serde_json always emits a decimal point on floating-point numbers (1.0) and omits it on integers (1), SKParameterValue::Float(1.0) and SKParameterValue::Integer(1) round-trip without variant wrapper tags.
  4. tensors: a sorted map keyed by stable dotted tensor names ("standard_scaler.mean", "linear.coefficients", "tree.is_leaf"). Each entry carries its element "dtype" ("F32", "F64", "I64" or "Bool"), its dimension vector "shape" ($[s_1, s_2, \dots, s_r]$, with $[]$ for a scalar tensor because the empty product equals $1$), and its flat "values" array whose length $N$ must satisfy:

$$\prod_{d=1}^{r} s_d = N$$

Checked multiplication (usize::checked_mul) guards that product on read so an adversarial shape such as [18446744073709551615, 2] returns SKError::ShapeMismatch rather than overflowing.

Large-tensor memory behavior. Unlike binary Safetensors, JSON formats every scalar as decimal UTF-8 text and materializes flat arrays in memory during serialization and parsing. Use the JSON debug format for inspection, diffs and test fixtures; use Safetensors for large production checkpoints.

5. Each public object, explained

All public types and functions live in sciencekit_interop::json and follow the workspace naming and builder conventions (SK on types, sk_ on free functions, no abbreviations):

  • SK_JSON_DEBUG_FORMAT_VERSION: u32 constant equal to 1.
  • SKJsonFormatMode: Pretty (default, two-space indented multi-line JSON) and Compact (single-line JSON with no insignificant whitespace).
  • SKJsonDebugWriter & SKJsonDebugWriterBuilder: builder-configured writer implementing SKBuilder<SKJsonDebugWriter>, exposing .format_mode(...), .backend(SKBackendKind) (default Faer) and .execution_mode(...) (default Automatic). Its methods write_state_to_string, write_state_to_writer, write_state_to_path, export_to_string and export_to_path validate scalar finiteness up front, borrow tensor slices without copying, and emit a sciencekit.interop.json.write tracing span.
  • SKJsonDebugReader & SKJsonDebugReaderBuilder: builder-configured reader implementing SKBuilder<SKJsonDebugReader>, exposing .backend(SKBackendKind) and .execution_mode(...). Its methods read_state_from_string, read_state_from_reader, read_state_from_path, import_from_string and import_from_path validate headers before materializing tensors and emit a sciencekit.interop.json.read tracing span.
  • Convenience entry points: sk_write_model_state_json, sk_write_model_state_json_pretty, sk_write_model_state_json_compact, sk_write_model_state_json_file, sk_read_model_state_json, sk_read_model_state_json_file, sk_export_model_json and sk_import_model_json.
use sciencekit_interop::json::{
    SKJsonFormatMode, sk_export_model_json, sk_import_model_json,
};

let json = sk_export_model_json(&fitted_model, SKJsonFormatMode::Pretty)?;
let restored: SKLinearRegressionModel<f64> = sk_import_model_json(&json)?;

6. Validation table: every rejection is structured

Validation runs before SKTensor and SKModelState construction so a malformed or mismatched document never leaves a half-built model behind:

Failure conditionReturned SKError
Invalid JSON syntax, wrong root type, trailing bytes, missing required v1 fieldSKError::Conversion
Missing or unreadable file path / stream I/O failureSKError::Io
format_version != 1 (including 0, 2, or evolved schemas)SKError::UnsupportedRepresentation
NaN or ±Infinity in floating tensor or hyperparameter (or f32 overflow on read)SKError::NonFiniteValue { position }
Tensor value count $\neq \prod s_d$, or dimension product overflowSKError::ShapeMismatch
Unknown/mismatched scalar dtype ("f16", or "f32" read into SKModelState<f64>)SKError::InvalidHyperparameter { name: "dtype", .. }
Duplicate tensor names in "tensors": { ... }SKError::InvalidHyperparameter { name: "tensor_names", .. }
Empty tensor nameSKError::InvalidHyperparameter { name: "tensor_name", .. }
Unknown tensor dtype ("U8") or element type disagreeing with tensor dtypeSKError::InvalidHyperparameter { name: "tensor_data_type", .. }
Duplicate hyperparameter keys or unsupported JSON null/object hyperparameterSKError::InvalidHyperparameter { name: "hyperparameters", .. }

7. Walking through the companion tests

The implementation in crates/sciencekit_interop/src/json/ is split into small single-responsibility files (mod.rs pure dispatcher, format_mode.rs, schema.rs, writer_builder.rs, writer.rs, parameter_deserialization.rs, schema_deserialization.rs, tensor_decoding.rs, state_decoding.rs, reader_builder.rs, reader.rs), paired with six companion test suites:

  • Schema & hand-written fixture (json_schema_tests.rs):
    • json_schema_matches_hand_written_standard_scaler_fixture asserts byte-for-byte equality against the documented SKStandardScaler JSON fixture.
    • json_schema_renders_readable_metadata_and_typed_hyperparameters checks f32 single-precision formatting (0.1 rather than 0.10000000149011612), class labels and every SKParameterValue kind including nested lists.
    • json_schema_renders_all_tensor_data_types_and_shapes_as_flat_arrays verifies F64, scalar [] shapes, I64 and Bool tensors.
    • json_schema_rejects_non_finite_values_before_serialization confirms f64::NAN at index 1 fails up front with SKError::NonFiniteValue { position: 1 }.
  • Deterministic writer (json_writer_tests.rs):
    • json_writer_defaults_to_pretty_format_and_deterministic_key_ordering and json_writer_produces_byte_identical_output_across_insertion_orders insert parameters and tensors in forward and reverse order and verify identical output bytes.
    • json_writer_compact_mode_emits_single_line_json and json_writer_writes_to_io_sink_file_and_exportable_model verify single-line compact mode, io::Write sinks, file output and SKExportable.
  • Round-trip fidelity (json_round_trip_tests.rs):
    • json_round_trip_reconstructs_identical_model_state and json_round_trip_preserves_single_precision_state_and_nested_lists verify exact SKModelState equality across f64 and f32.
    • json_round_trip_reconstructs_model_through_export_and_import_traits round-trips a fitted model through SKExportable and SKImportable.
    • json_round_trip_supports_files_streams_and_ignores_unknown_fields verifies stream/file reads and forward compatibility when extra unknown fields appear inside version 1.
  • Validation (json_validation_tests.rs):
    • json_validation_rejects_malformed_json_with_conversion_error, json_validation_rejects_unknown_major_versions, json_validation_rejects_duplicate_tensor_and_hyperparameter_names, json_validation_rejects_invalid_and_mismatched_dtypes and json_validation_rejects_tensor_shape_mismatches pin every row of the error table above.
  • Equivalence, large tensors & concurrency (json_concurrency_tests.rs):
    • json_concurrency_pretty_and_compact_modes_parse_to_identical_state confirms pretty and compact outputs reconstruct identical states.
    • json_concurrency_large_tensor_round_trips_and_validates_shape round-trips a $256 \times 256$ (65,536-element) matrix, checks its text expansion and verifies shape-mismatch rejection.
    • json_concurrency_concurrent_reads_from_same_file_agree spawns eight OS threads reading the same JSON file and re-encoding concurrently, confirming thread-safe determinism.
  • End-to-end acceptance (acceptance_tests/):
    • json_acceptance_tiny_states_round_trip_for_both_scalars, json_acceptance_large_state_preserves_all_dtypes_class_table_and_spans and json_acceptance_imported_regressor_reproduces_predictions_and_zero_error validate tiny/large states, sk_canonicalize_labels class tables, tracing span recording and zero-drift predictions.
    • json_acceptance_truncated_prefixes_return_conversion_without_panicking truncates a valid JSON state at every UTF-8 character offset and proves the reader never panics, paired with json_acceptance_corrupt_metadata_and_missing_files_return_structured_errors.

Generic bagging: composing any learner over bootstrap rows, routed subspaces and honest out-of-bag scores

Random forests (Chapter 40) showed how averaging many decision trees tames high variance. Yet variance is not exclusively a tree problem. A nearest-neighbour classifier with a small $k$, an unregularized logistic regression on noisy features, or a polynomial-expanded linear model can also wobble noticeably when a few training rows move. Leo Breiman’s Bootstrap Aggregating (bagging), Tin Kam Ho’s Random Subspaces and Gilles Louppe and Pierre Geurts’s Random Patches generalize the ensemble recipe beyond trees: take any supervised estimator, fit independent copies on resampled subsets of rows and columns, route each copy’s inputs strictly through the columns it saw at training time, and average their predictions.

This chapter introduces SKBaggingClassifier<B> and SKBaggingRegressor<B> in crates/sciencekit_ensemble/src/bagging/, implementing the bagging-ensembles specification as the library’s first generic meta-estimators over an arbitrary base estimator configuration B.


1. The problem, in plain words

Suppose you already have a working learning algorithm — a CART tree, a logistic classifier, a $k$-NN model or a Ridge regressor — and you want to reduce the variance of its predictions without rewriting a single line of that algorithm. Bagging wraps that learner in a four-step loop:

  1. Draw $T$ resampled training tables. Estimator $t \in {0, \dots, T-1}$ draws $m$ row indices from the $n$ training rows (with replacement when bootstrap is true, without replacement when false) and $d$ feature indices from the $p$ columns (without replacement by default, or with replacement when bootstrap_features is true).
  2. Fit one copy per table in parallel. Every base estimator sees only its $(m \times d)$ sub-table in the caller’s native representation — a dense ArrayView2 or a borrowed compressed sparse row (CsMatView) matrix, never densified.
  3. Remember each estimator’s column map. If estimator $t$ trained on original columns $[0, 2]$ out of $[0, 1, 2]$, column $0$ inside estimator $t$ means original column $0$ and column $1$ inside estimator $t$ means original column $2$. Passing the full three-column matrix at prediction time would either crash with a shape error or feed the wrong numbers into the wrong weights.
  4. Aggregate predictions deterministically. For classification over $C$ canonical classes, the ensemble averages the aligned probability vectors and picks the largest class (breaking ties toward the smallest canonical index):

$$ \bar{p}c(x) = \frac{1}{T} \sum{t=0}^{T-1} \hat{p}c^{(t)}!\left(x{\mathcal{F}t}\right), \qquad \hat{y}(x) = \arg\max{c \in {0, \dots, C-1}} \bar{p}_c(x). $$

For regression, where estimator $t$ predicts scalar response $\hat{y}^{(t)}!\left(x_{\mathcal{F}_t}\right)$ on its feature subset $\mathcal{F}_t$, the ensemble predicts the arithmetic mean:

$$ \hat{y}(x) = \frac{1}{T} \sum_{t=0}^{T-1} \hat{y}^{(t)}!\left(x_{\mathcal{F}_t}\right). $$


2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Two generic structs SKBaggingClassifier<B> and SKBaggingRegressor<B>, not one runtime trait objectIn Rust, a generic type parameter B lets the compiler specialize bagging for the exact base estimator you pass in, keeping zero-copy generic fit inputs and catching supervision mismatches (such as passing a regressor to SKBaggingClassifier) before the program can even compile.A single SKBagging holding Box<dyn SKEstimator> — SKSupervisedFit::fit is generic over zero-copy input types, which prevents dynamic trait-object dispatch and hides wrong-axis mistakes until runtime.
Reuse existing SKSupervisedFit, SKClassifierPredictor and SKRegressorPredictor directlyEvery supervised estimator in sciencekit already implements those contracts (Chapter 2). Requiring no new SKEstimator supertrait means SKDecisionTreeClassifier, SKLogisticRegression, SKKNeighborsClassifier, SKLinearRegression and SKRidge work inside bagging immediately without touching their crates.Inventing a monolithic SKEstimator supertrait — pure boilerplate across every algorithm crate with zero extra expressive power.
Preserve base errors via SKBaggingError<E> (Central vs Base) and SKBaseEstimatorError<E>A base estimator may have its own rich error type E (for example a dense-only rejection). Wrapping central checks in SKBaggingError::Central(SKError) and base failures in SKBaggingError::Base(E) keeps both structured. In Rust, implementing both From<SKError> and a blanket From<E> on the same enum would collide when E = SKError, so SKBaseEstimatorError<E> and SKBaggingError::from_base disambiguate Base, while From<SKBaggingError<SKError>> for SKError plugs bagging straight into central scorers and pipelines.Flattening every base error into a string or forcing B::Error = SKError — loses algorithm-specific diagnostics on custom estimators.
Independent SplitMix64 streams for row draws and feature drawsEstimator $t$ derives sk_tree_seed(global_seed, t) and branches into stage 0 for row indices (reusing bootstrap::sk_sample_indices) and stage 1 for feature indices. Toggling bootstrap_features never perturbs row draws, and slot $t$ is identical on 1 thread or 64 threads.Advancing one shared RNG sequentially across rows then features across all estimators — thread scheduling or changing maximum_samples would scramble every downstream subset.
Strict feature-subset routing at both inference and OOB scoring, including duplicate CSR columnsEach fitted slot stores feature_subsets[t]: Vec<usize>. Inference and OOB scoring slice or project only those columns before calling the base model. For sparse CSR inputs, a sorted (source_column, local_column) lookup projects non-zeros in $O(\text{nnz} \log d)$ without ever materializing zeros, even when bootstrap_features(true) draws duplicate columns such as [3, 0, 3].Passing the full matrix and hoping the base model ignores unused columns, or calling .to_dense() to slice columns — leaks data, breaks dimension checks, and blows up sparse memory.
Single-class bootstrap resilience with a 2-row representation probeOn tiny datasets (say 4 rows), a bootstrap draw has a high chance of landing in one class. Classifiers like CART or logistic regression reject single-class targets, whereas a dense-only classifier rejects sparse storage. When a 1-class draw fails, bagging probes the base estimator on a 2-row mixed-class slice in the same representation: if the probe also fails, the genuine SKBaggingError::Base surfaces; if it succeeds, the slot becomes a ConstantClass leaf predicting probability $1.0$ for that class.Failing whenever a small bootstrap sample hits one class, or blindly swallowing all errors on 1-class draws (which would mask UnsupportedRepresentation on dense-only estimators).

3. The concepts, taught from zero

Compile-time composition without Rust jargon

If you have never used Rust, think of SKBaggingClassifier<B> as a typed recipe frame with one blank slot B for the base learner. When you write:

#![allow(unused)]
fn main() {
let base = SKLogisticRegression::<f64>::build().build()?;
let ensemble = SKBaggingClassifier::build(base)
    .number_of_estimators(25)
    .oob_score(true)
    .build()?;
}

the compiler fills B with SKLogisticRegression<f64> and checks two rules at compile time:

  1. Can B fit supervised features and targets (SKSupervisedFit<F>)?
  2. Does the fitted model B::Model know how to predict class probabilities and labels (SKClassifierPredictor<F>)?

If someone accidentally hands SKDecisionTreeRegressor (which predicts continuous numbers, not class probabilities) to SKBaggingClassifier and calls fit, the program is rejected by the compiler before it can run. No runtime type tags and no virtual-call overhead are needed.

Why feature-subset routing is the main correctness trap

Imagine a dataset with three columns: column $0$ (temperature), column $1$ (sensor ID) and column $2$ (pressure). Suppose estimator $0$ draws the two-feature subset $\mathcal{F}_0 = [0, 2]$. Inside estimator $0$, its world has two columns: local column $0$ is temperature and local column $1$ is pressure.

At prediction time, a new batch arrives with all three columns $[0, 1, 2]$. If bagging passed that batch straight through, estimator $0$ would reject the 3-column shape; worse, if someone truncated to the first two columns $[0, 1]$, estimator $0$ would multiply its pressure weight by the sensor ID! Instead, predict/classifier_routing.rs and predict/regressor_routing.rs project every chunk through feature_subsets[t] before estimator $t$ ever sees it, and when feature_subsets[t] is the full identity $[0, 1, \dots, p-1]$, they pass a zero-copy borrowed view directly.

flowchart LR
    accTitle: Feature-subset routing during bagging fit, OOB scoring and prediction
    accDescr: Full dense or CSR input with columns 0 through p minus 1 enters independent estimator slots. Slot 0 projects rows and columns onto subset F0 such as 0 and 2, while Slot t projects onto subset Ft such as 3, 0 and 3, preserving dense or CSR representation without densifying. Base models produce local predictions aligned back to the canonical class table and averaged across deterministic row chunks.
    Input["Full Input Matrix<br/>Dense ArrayView2 or Sparse CsMatView<br/>Columns [0, 1, ..., p-1]"] --> Router0["Subset Projector 0<br/>feature_subsets[0] = [0, 2]<br/>No column 1 leaked, no densification"]
    Input --> RouterT["Subset Projector t<br/>feature_subsets[t] = [3, 0, 3]<br/>CSR column remap or zero-copy slice"]

    Router0 --> Base0["Fitted Base Model 0<br/>Tree, Logistic, k-NN, Linear or Ridge"]
    RouterT --> BaseT["Fitted Base Model t<br/>Tree, Logistic, k-NN, Linear or Ridge"]

    Base0 --> Align["Canonical Class Alignment<br/>local_to_ensemble remap (Classifier)<br/>or Direct Response (Regressor)"]
    BaseT --> Align

    Align --> Agg["Row-Chunked Mean Aggregation<br/>Fixed 0..T addition order<br/>Smallest-index tie-break"]

    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef route fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef model fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef agg fill:#f3e8ff,stroke:#9333ea,stroke-width:2px,color:#581c87

    class Input input
    class Router0,RouterT route
    class Base0,BaseT model
    class Align,Agg agg

Bit-for-bit thread-count invariance during prediction

Floating-point addition is not associative: $(a + b) + c$ can differ in the last bit from $a + (b + c)$. If parallel threads summed estimator predictions in completion order, 4 threads could disagree with 1 thread in the last ULPs. Bagging avoids that by parallelizing across disjoint contiguous row chunks (sk_map_row_chunks), while inside every chunk the loop over estimators always accumulates in strict slot order $t = 0, 1, \dots, T-1$:

flowchart TD
    accTitle: Two-level error and execution architecture in generic bagging
    accDescr: Bagging validates shapes, finiteness and execution mode up front as SKBaggingError Central, then executes parallel fit or row-chunked prediction where any rejection from the base estimator surfaces intact as SKBaggingError Base.
    Call["Public fit / predict call<br/>Tracing span records configured SKBackendKind"] --> CentralCheck{"Central checks:<br/>non-empty, CSR, finite,<br/>matching columns & mode?"}
    CentralCheck -- "No" --> CentralErr["Err(SKBaggingError::Central(SKError))"]
    CentralCheck -- "Yes" --> Parallel["Lock-free Rayon slots (fit)<br/>or deterministic row chunks (predict)"]
    Parallel --> BaseCall{"Base estimator fit / predict<br/>on native Dense or CSR subset"}
    BaseCall -- "Base rejects (e.g. dense-only on CSR)" --> BaseErr["Err(SKBaggingError::Base(E))"]
    BaseCall -- "Ok" --> Done["Fitted SKBagging*Model<br/>+ optional OOB Accuracy or R²"]

    classDef entry fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef gate fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef ok fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef err fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#881337

    class Call,Parallel entry
    class CentralCheck,BaseCall gate
    class Done ok
    class CentralErr,BaseErr err

4. Each public object, explained

  • SKBaggingClassifier<B> / SKBaggingClassifierBuilder<B> and SKBaggingRegressor<B> / SKBaggingRegressorBuilder<B> — builder-only meta-estimators opened with SKBaggingClassifier::build(base_estimator) / SKBaggingRegressor::build(base_estimator) and finalized via SKBuilder::build. Setters expose base_estimator, number_of_estimators (default 10), maximum_samples (SKMaximumSamples::All default, Count, Fraction), maximum_features (SKMaximumFeatures::All default, Count, Fraction, Sqrt, Log2), bootstrap (default true), bootstrap_features (default false), oob_score (default false), random_seed (default 0), backend (default SKBackendKind::Faer) and execution_mode (default SKExecutionMode::Automatic).
  • SKBaggingClassifierModel<F, M> — immutable Send + Sync fitted classification ensemble implementing SKClassifierPredictor<F> (predict_labels, predict_probabilities), probabilities, number_of_estimators, feature_count, feature_subsets, estimator_features, estimator, classes, number_of_classes, oob_score, oob_scored_rows, out_of_bag_rows, bootstrap, bootstrap_features, backend, execution_intent, and SKExportable<F> whenever M: SKExportable<F>.
  • SKBaggingRegressorModel<F, M> — immutable Send + Sync fitted regression ensemble implementing SKRegressorPredictor<F> (predict), predict_values, number_of_estimators, feature_count, estimators, estimator, feature_subsets, estimator_features, oob_score, oob_scored_rows, out_of_bag_rows, bootstrap, bootstrap_features, backend, execution_intent, and SKExportable<F> whenever M: SKExportable<F>.
  • SKBaggingError<E> and SKBaseEstimatorError<E> — two-variant error enum (Central(SKError) and Base(E)) with from_base, is_central, is_base, as_central, as_base, From<SKError>, From<SKBaseEstimatorError<E>> and From<SKBaggingError<SKError>> for SKError.

5. A real walk-through, using the tests

Every claim in this chapter is pinned by an executable companion test in crates/sciencekit_ensemble/src/bagging/:

central_sk_error_converts_into_central_variant and base_error_converts_into_base_variant_preserving_detail

Located in bagging/bagging_error_tests.rs, these verify that central SKError values convert into SKBaggingError::Central, custom base errors convert into SKBaggingError::Base via SKBaseEstimatorError and SKBaggingError::from_base with full Display and Error::source fidelity, and SKBaggingError<SKError> unwraps back into SKError for central scorers.

classifier_and_regressor_builders_match_documented_defaults and oob_score_without_bootstrap_is_rejected_at_build

Located in bagging/bagging_builder_tests.rs, these build both estimators without calling any setter to verify every default (10 estimators, All samples and features, bootstrap = true, bootstrap_features = false, oob_score = false, seed 0, Faer, Automatic), then verify that number_of_estimators(0), invalid sample/feature counts or fractions (0.0, -0.2, 1.25, NaN), and bootstrap(false) paired with oob_score(true) fail with SKError::InvalidHyperparameter naming the exact field.

classifier_base_configurations_satisfy_bagging_classifier_contract and mismatched_supervision_axis_is_rejected_by_the_type_system

Located in bagging/bagging_bounds_tests.rs (paired with compile_fail doctests on SKBaggingClassifier and SKBaggingRegressor), these prove at compile time that tree, logistic and $k$-NN classifiers satisfy SKBaggingClassifier, tree, OLS, Ridge and $k$-NN regressors satisfy SKBaggingRegressor, and crossing the supervision axis does not implement SKSupervisedFit.

dense_and_sparse_submatrix_gathers_agree_including_duplicate_feature_draws

Located in bagging/bagging_sampling_tests.rs, this gathers rows [2, 0, 3] and duplicate out-of-order columns [3, 0, 3] from both a dense Array2 and a CSR CsMat, proving the resulting CSR submatrix stays valid and equals the dense gather without densifying.

parallel_fit_matches_sequential_fit_and_repeated_fits_are_deterministic and regressor_fit_is_invariant_across_rayon_thread_counts_and_non_tree_bases

Located in bagging/bagging_fit_tests.rs, these verify that InProcessSynchronous and Automatic produce identical feature_subsets() and identical per-slot tree structures, and that installing 1-thread vs 4-thread rayon pools leaves every fitted estimator unchanged.

estimator_fitted_on_columns_zero_and_two_receives_only_those_columns and routed_single_estimator_matches_manually_subsetted_linear_regression

Located in bagging/bagging_routing_tests.rs, the first injects a sentinel 999_999.0 into column 1 of a 3-column dense and sparse query matrix and uses a ColumnSpyRegressor to prove an estimator fitted on subset [0, 2] receives a 2-column matrix containing only columns 0 and 2:

#![allow(unused)]
fn main() {
assert_eq!(bagging_model.estimator_features(0), Some(&[0usize, 2][..]));
// Query row 0 is [10.0, 999_999.0, 30.0]; the base model only sees [10.0, 30.0].
assert_eq!(routed_predictions, Array1::from_vec(vec![40.0, 100.0]));
}

The second compares a 1-estimator bagging wrapper around SKLinearRegression against a standalone SKLinearRegression manually fitted and queried on select(Axis(1), &[0, 2]), confirming agreement to $10^{-10}$.

hand_computed_two_estimator_classifier_averages_probabilities, equal_average_probabilities_break_ties_toward_smallest_canonical_index and three_estimator_regressor_predicts_exact_arithmetic_mean

Located in bagging/bagging_classifier_tests.rs and bagging/bagging_regressor_tests.rs, these verify the exact aggregation formulas: class-0 probabilities 0.2 and 0.6 average to 0.4; an exact 0.5 / 0.5 tie over ["beta", "alpha"] picks canonical index 0 ("beta"); and three base regressors predicting 1.0, 2.0 and 6.0 average to 3.0. A companion tracing_subscriber test confirms SKBackendKind::MatrixMultiply is recorded on the model’s predict span.

classifier_oob_accuracy_excludes_in_bag_rows_on_memorization_trap and regressor_oob_r2_matches_manual_routed_recomputation

Located in bagging/bagging_oob_tests.rs, the first shows full trees memorizing unique row IDs (> 0.90 in-bag accuracy) while oob_score() drops below 0.45 because in-bag estimators are excluded. The second fits SKBaggingRegressor<SKLinearRegression> with 2-column subspaces, manually recomputes OOB predictions over out_of_bag_rows(t) and estimator_features(t), and matches oob_score() to $10^{-12}$, alongside disabled_and_no_scored_rows_oob_report_unsupported_operation.

sparse_capable_base_receives_csr_without_densifying_and_matches_dense and dense_only_base_estimators_surface_error_through_sk_bagging_error_base

Located in bagging/bagging_representation_tests.rs, these confirm a spy regressor observes "csr" at both fit and predict, verify all four dense/CSR fit-predict combinations plus a $64 \times 100,000$ CSR matrix, and verify that dense-only bases (CustomDenseOnlyClassifier, SKLinearRegression, and SKKNeighborsClassifier configured with KdTree) surface their rejections through SKBaggingError::Base.

non_finite_values_target_errors_and_out_of_range_probabilities_are_rejected, shared_classifier_and_regressor_models_serve_eight_threads_identically and acceptance_tests

Located in bagging/bagging_validation_tests.rs, bagging/bagging_concurrency_tests.rs and bagging/acceptance_tests/, these check EmptyInput, ShapeMismatch, NonFiniteValue, ProbabilityOutOfRange and ExecutionModeIncompatible, share Arc-wrapped models across 8 OS threads, export SKBaggingRegressor<SKLinearRegression> via SKExportable::export_state, and validate $12,000$-row dense and CSR ensembles (SKDecisionTreeClassifier, SKDecisionTreeRegressor, SKRidge) with sciencekit_metrics accuracy, macro-$F_1$, MSE, MAE and $R^2$.


6. Look inside

PathResponsibility
bagging/mod.rsPure dispatcher and public re-exports
bagging/error.rsSKBaggingError<E>, SKBaseEstimatorError<E> and SKError conversions
bagging/config.rsShared defaults and hyperparameter validation
bagging/builder/SKBaggingClassifierBuilder<B> and SKBaggingRegressorBuilder<B>
bagging/classifier.rs, regressor.rsEstimator configurations, SKSupervisedFit bounds and compile_fail doctests
bagging/sampling.rsSeeded row/feature draws and non-densifying dense/CSR submatrix projections
bagging/fit/Lock-free rayon slot execution, 1-class bootstrap probe and model assembly
bagging/predict/Feature-subset routing, canonical class alignment and row-chunked aggregation
bagging/oob.rsOut-of-bag accuracy and $R^2$ over excluded bootstrap rows
bagging/export.rsSKExportable<F> state emission over exportable base models
bagging/validation.rsDimension, CSR, finiteness and target canonicalization checks
bagging/*_tests.rs, bagging/acceptance_tests/Companion TDD suites and tiny + $12,000$-row acceptance tests

7. What this unlocks

Every supervised classifier and regressor in sciencekit now gains variance reduction, Random Subspaces, Random Patches and out-of-bag validation without writing ensemble-specific glue, and the same generic estimator contracts are proven composable end-to-end with scorers, pipelines and model selection.

Gradient boosting: fitting trees to residuals, one shrinking step at a time

Random forests (Chapter 40) and bagging (Chapter 46) attack error by averaging many independent learners. They reduce variance, but every member of the ensemble is trained against the same raw target and none of them is told what the previous ones got wrong. With a fixed budget of shallow trees that is a real limitation: if ten trees are not enough to bend the prediction along a curved boundary, adding an eleventh identical-looking tree only smooths the average.

Gradient boosting, introduced by Jerome Friedman in 2001, takes the opposite road. It builds the ensemble sequentially, and each new tree is fitted not to the target but to the residual — the part of the target that the current ensemble still fails to explain. Every stage is a small, shallow correction, and a shrinkage factor keeps each correction deliberately timid so that many stages can accumulate into a precise model without overfitting.

This chapter introduces SKGradientBoostingClassifier<F> and SKGradientBoostingRegressor<F> in crates/sciencekit_ensemble/src/gradient_boosting/, built on the reusable boosting substrate in crates/sciencekit_ensemble/src/boosting/, implementing the gradient-boosting specification.


1. The problem, in plain words

Imagine you have to predict a continuous quantity — say a house price — with a family of very simple trees. A single depth-1 tree (a “stump”) can only split the world in two and predict one constant on each side. It will be wrong almost everywhere. What do you do with the mistake?

The boosting answer is a loop:

  1. Predict with what you have. Start with the single best constant prediction the loss allows — for squared error, the target mean.
  2. Measure the mistake. For every training row, compute the negative gradient of the loss with respect to the current prediction. For squared error this is simply target - prediction, the residual. For log-loss it is target - sigmoid(score). For absolute error it is the sign of the residual.
  3. Fit a small tree to the mistake. Grow a shallow regression tree whose target is that negative gradient. In code, crates/sciencekit_tree/src/structure/ exposes a structure-only build that grows the split geometry on the pseudo-residuals without computing criterion-driven leaf values.
  4. Overwrite the leaf values with a Newton step. Each leaf receives $-\sum g / (\sum h + \lambda)$, built from the first derivative $g$ and second derivative $h$ of the real loss over the rows that fell in that leaf. This is what makes the update correct for losses other than squared error.
  5. Take a small step. Multiply the tree’s output by the learning rate $\nu$ (called shrinkage) and add it to the running raw score. Repeat.

After $T$ stages the regressor predicts

$$ \hat{y}(x) = f_0 + \nu \sum_{t=1}^{T} h_t(x), $$

where $f_0$ is the initial constant and $h_t$ is the tree fitted at stage $t$. Classification reuses the same loop in raw-score space: a binary model accumulates one score per row and turns it into a probability with a sigmoid, while a multiclass model accumulates one score per class and grows one tree per class per stage, turning the score vector into probabilities with a softmax.

flowchart LR
    accTitle: The sequential gradient-boosting loop, from an initial constant to a shrunk ensemble
    accDescr: A target table and the current raw scores produce per-row negative gradients and Hessians. A shallow structure is grown on the negative gradients, its leaves are replaced by Newton steps, and the tree is scaled by the learning rate before being added to the raw scores. The loop repeats for a fixed number of stages or until held-out validation loss stops improving.
    Data["Training table X<br/>dense or CSR, never densified"] --> Init["Initial constant f0<br/>mean, log-odds or log-priors"]
    Init --> Scores["Current raw scores f(x)<br/>one per row, or one per row and class"]
    Scores --> Grad["Loss derivatives<br/>-g = -dL/df and h = d2L/df2"]
    Grad --> Grow["Structure-only tree growth<br/>on the negative gradients"]
    Grow --> Newton["Leaf replacement<br/>value = sum(-g) / (sum(h) + lambda)"]
    Newton --> Shrink["Multiply by learning rate nu"]
    Shrink --> ScoreUpdate["Add nu * h_t(x) to the raw scores"]
    ScoreUpdate --> Check{"Enough stages,<br/>or validation<br/>stopped improving?"}
    Check -- "No, keep boosting" --> Scores
    Check -- "Yes" --> Model["Fitted model<br/>f0 + nu * sum of stage trees"]

    classDef data fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef math fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef tree fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef score fill:#f3e8ff,stroke:#9333ea,stroke-width:2px,color:#581c87
    classDef done fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#881337

    class Data,Init data
    class Grad,Shrink math
    class Grow,Newton tree
    class Scores,ScoreUpdate score
    class Check,Model done

2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
One loss-agnostic stage loop shared by regression, binary and multiclassEvery loss only has to answer five questions: its initial prediction, its negative gradient, its Hessian, its link and its loss value (SKGradientLoss<F> in boosting/loss/contract.rs). The loop, the shrinkage and the early-stopping bookkeeping are written once, so a future histogram booster can reuse them untouched.One bespoke loop per loss — triplicated subsampling, early stopping and multiclass handling, and three places to drift apart.
Grow the split structure on the negative gradient, then replace the leavesThe tree crate’s split criterion is a fast variance-reduction search, which is exactly the right shape heuristic for pseudo-residuals. But the value each leaf should output is loss-specific. Splitting the two concerns lets one structure builder serve squared error, log-loss and Huber while SKTreeStructure::replace_leaf_values writes the Newton step afterwards.Teaching the split criterion every loss, or re-implementing tree growth inside sciencekit_ensemble.
Newton leaves $-\sum g / (\sum h + \lambda)$ instead of leaf meansFor squared error the two coincide exactly, but for log-loss a leaf mean of the residuals would ignore the curvature $p(1-p)$ and overshoot badly on confident rows. The second derivative also gives l2_regularization a mathematically honest home: it damps the step, it is not a penalty on the split search.Plain residual means (Friedman’s original “least squares” tree) — simpler, but wrong for every loss whose curvature varies.
A documented positive Hessian surrogate for AbsoluteError and Huber$\lvert y - f \rvert$ is not twice differentiable: its second derivative is zero almost everywhere and undefined at zero. Using a constant Hessian of 1 makes the leaf step a damped median-like update that stays finite and behaves well in practice, and the choice is written down rather than hidden.Dividing by a zero Hessian, or silently substituting the squared-error loss for the robust ones.
Multiclass via one tree per class per stage with a diagonal HessianThis is the standard gradient-boosting compromise: the true softmax Hessian is a full $C \times C$ matrix, and fitting one tree to a full-matrix direction would require a matrix-valued tree. The diagonal $p_c(1 - p_c)$ keeps the update per-class and keeps the model surface simple.Multivariate trees with vector leaves — far more machinery for a small accuracy gain.
Shrinkage $\nu$ as an explicit builder parameter, default $0.1$A small step is the single most effective regularizer of boosting: it lets many weak stages combine and makes the model far less sensitive to the number of stages. Exposing it (instead of hard-coding 1.0) makes the trade-off between stages and step size a documented contract.Always taking the full Newton step and compensating with a tiny number_of_estimators.
Seeded without-replacement row subsampling per stageStochastic gradient boosting (subsample < 1) de-correlates consecutive stages and shortens each fit. Drawing without replacement avoids duplicate rows, and deriving the seed from (global_seed, stage, class) keeps every stage reproducible and thread-count invariant.Sampling with replacement (duplicates distort the Hessian sums) or using one global RNG advanced in fit order (thread scheduling would change the draw).
Early stopping by truncating back to the best validation stageThe monitor keeps the stage count that achieved the lowest held-out loss and truncates the ensemble to it, so the returned model is the best one seen, not merely the last one before patience ran out. Classification splits are stratified so a rare class is not wiped out of the validation fold.Returning the last stage, or a separate “early-stopped” model family.
No histogram binning, categorical routing, missing-value handling, streaming, memmap or export in this changeEach of those is a substantial subsystem with its own spec. Shipping a correct exact-split booster first gives the later histogram change a validated reference to measure against, instead of debugging binning and gradients at the same time.Bundling everything — a change too large to review and too easy to get subtly wrong.

The last decision is deliberate and recorded in design.md; the deferred items are listed again in Section 7 and in the change’s task list.


3. The concepts, taught from zero

Residuals, gradients and why boosting is called “gradient” boosting

If you have never seen calculus applied to machine learning, read the negative gradient as “the direction in which the prediction should move to make the loss smaller”. For a single row with target $y$ and prediction $f$:

  • Squared error $L = \tfrac12 (y - f)^2$ has derivative $\partial L / \partial f = f - y$, so the negative gradient is $y - f$ — the ordinary residual.
  • Log-loss for a positive row, $L = \log(1 + e^{-f})$, has negative gradient $1 - \sigma(f)$, which is large when the model is confidently wrong and nearly zero when it is confidently right.
  • Absolute error $L = |y - f|$ has negative gradient $\operatorname{sign}(y - f)$: a constant push whose size does not grow with the mistake.

Boosting fits one tree per stage to that per-row direction. When the loss is squared error the tree is literally fitting the residuals, which is why the technique is often explained as “fit trees to the residuals”. For other losses the “residual” is the negative gradient, hence the general name.

Newton leaves, in pictures

A leaf may contain, say, ten rows. The split search decided they belong together, but what number should the leaf output? A gradient step would move by $-g$ scaled by some rate; a Newton step uses the curvature to jump straight to the minimum of a local quadratic model:

$$ \text{leaf value} = \frac{\sum_{i \in \text{leaf}} (-g_i)}{\sum_{i \in \text{leaf}} h_i + \lambda}. $$

boosting/init.rs implements this twice: sk_newton_leaf_value from the raw gradients and sk_newton_leaf_value_from_negative_gradients from the already-negated ones the stage loop produces. Both guard the degenerate case: a leaf whose Hessian sum is zero or negative keeps the value 0.0 so a pathological row can never produce an infinite update. $\lambda$ (l2_regularization) is added to the denominator, which shrinks every leaf — a leaf backed by little curvature information moves less.

For the hand-computed binary fixture in gb_classifier_tests.rs, four balanced rows start at raw score $0.0$. Each row has Hessian $p(1-p) = 0.25$ and negative gradients $-0.5$ (class 0) and $+0.5$ (class 1). A depth-1 split puts two class-0 rows on one side and two class-1 rows on the other: $(-1.0) / 0.5 = -2.0$ and $(+1.0) / 0.5 = +2.0$. With learning_rate(0.25) the raw scores become $\mp 0.5$, and the positive-class probabilities become $\sigma(\mp 0.5)$ — exactly what the test asserts.

The learning rate is not a formality

With $\nu = 1.0$ each stage fully commits to the current Newton step; consecutive trees then chase each other and the ensemble overfits within a handful of stages. With $\nu = 0.1$ the same correction is spread over roughly ten stages, and each stage gets to see a slightly different residual field. This is why the library defaults to $0.1$ and why the acceptance tests pair a small $\nu$ with a larger number_of_estimators instead of a single big step.

Initial predictions: where the additive model starts

A boosted model is $f_0 + \nu \sum h_t$. The constant matters because it is the loss-optimal prediction before any tree exists:

Estimatorinitial_predictionSource
SquaredError, AbsoluteError, Huberarithmetic mean of the targetsboosting/loss/{squared,absolute,huber}.rs
Binary LogLosslog-odds of the positive prior, link(mean(0/1 targets))boosting/loss/log_loss.rs
Multiclass LogLossone log-prior per canonical classSKMulticlassLogLoss::initial_predictions

Binary targets are the canonical class indices mapped to 0.0/1.0, so “positive” means canonical class 1, not “the larger integer label”. The fitted model stores the initial value(s) and adds them before the stage trees during prediction.

Canonical classes and the label-index contract

Targets are canonicalized through sk_canonicalize_targets: integers are stringified and nominal strings are taken as-is, then each new label is assigned the next free index in order of first appearance — not in sorted order. The SKLabelTable remembers the mapping, so model.classes().label_of(index) recovers the original label. SKClassifierPredictor::predict_labels returns those canonical indices (its trait documentation says so); callers that need the raw label must map through classes(). This is precisely the nuance the 20 000-row acceptance test exercises: it canonicalizes the truth labels with sk_canonicalize_labels before comparing, because comparing canonical indices against raw integers would be wrong whenever the first class to appear is not the smallest one.

Stochastic subsampling and deterministic seeds

When subsample < 1, each stage draws clamp(floor(subsample · n), 1, n) distinct training rows. The seed is derived in two steps (boosting/stage.rs::sk_stage_tree_seed): from the global seed and the stage index, then from that stage seed and the class index. The row draw adds a third derivation (SK_RANDOM_DOMAIN_INITIALIZATION) and the tree split search uses the stage seed itself. Consequences worth stating out loud:

  • Changing subsample changes the row draws, but changing maximum_features never does, because the feature draw lives in the tree’s own constraint seed.
  • Any stage’s draw depends only on (global_seed, stage_index, class_index), so it is identical on one thread or sixty-four.
  • A sparse subset is gathered into a new CSR matrix (sk_gather_sparse_rows); the full matrix is never densified.

With subsample >= 1 the full row range is used in order and no randomness is consumed at all.

Early stopping that keeps the best stage

n_iter_no_change(patience) first holds out validation_fraction rows with a seeded draw — stratified for classification so every class is represented — fits on the rest, and after every stage computes the validation loss (mean scalar loss, or mean per-row multiclass cross-entropy). The monitor (boosting/early_stopping.rs) declares an improvement only when the new loss beats the best by more than tolerance (default 1e-4). When patience non-improving stages have elapsed, the loop stops and the stage vector is truncated to the best stage count. The returned model is therefore never worse on the validation split than any shorter prefix of the run.

flowchart TD
    accTitle: Validation split, patience monitor and best-stage truncation in gradient boosting
    accDescr: Fitting with early stopping enabled first draws a seeded validation fold, stratified for classification. Each stage updates both training and validation raw scores, and the monitor records the validation loss. Improvement beyond the tolerance resets patience and remembers the stage count; patience non-improving stages stop the loop, which then truncates the ensemble back to the best stage count.
    Call["fit with n_iter_no_change set"] --> Split["Seeded validation split<br/>validation_fraction rows held out<br/>stratified for classification"]
    Split --> Train["Fit stage on remaining rows<br/>+ update training scores"]
    Train --> Eval["Update validation scores<br/>compute validation loss"]
    Eval --> Monitor{"Better than best<br/>by more than tolerance?"}
    Monitor -- "Yes" --> Reset["Remember this stage count<br/>reset patience"]
    Monitor -- "No" --> Patience{"Patience<br/>exhausted?"}
    Patience -- "No" --> Train
    Patience -- "Yes" --> Truncate["Stop and truncate<br/>to the best stage count"]
    Reset --> More{"Stage budget<br/>left?"}
    More -- "Yes" --> Train
    More -- "No" --> Keep["Keep all fitted stages"]
    Truncate --> Model["Fitted model"]
    Keep --> Model

    classDef entry fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef gate fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef step fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef stop fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#881337

    class Call,Split entry
    class Monitor,Patience,More gate
    class Train,Eval,Reset step
    class Truncate,Model,Keep stop

Representation parity and concurrency

SKDataView already abstracts dense ArrayView2 and borrowed CSR CsMatView (Chapter 2). Boosting dispatches exactly once per operation: fit validates dimensions and finiteness, then either hands the full view to the tree builder or gathers a CSR row subset; prediction maps rows through sk_map_prediction_rows, which parallelizes across rows with a deterministic grain while every single row accumulates its trees in strict stage order. That fixed addition order is what makes predictions bit-identical on one thread and on many. CSC input is rejected up front with a to_csr suggestion rather than silently transposed.


4. Each public object, explained

  • SKGradientBoostingClassifier<F> / SKGradientBoostingClassifierBuilder<F> — builder-only binary/multiclass classifier, opened with SKGradientBoostingClassifier::build() and finalized by SKBuilder::build. Setters: number_of_estimators (default 100), learning_rate (0.1), loss (SKGradientBoostingClassificationLoss::LogLoss, the only variant today), maximum_depth (3), minimum_samples_leaf (1), maximum_features (SKMaximumFeatures::All), subsample (1.0), l2_regularization (0.0), random_seed (0), validation_fraction (0.1), n_iter_no_change (off; without_early_stopping clears it), tolerance (1e-4), backend (SKBackendKind::Faer) and execution_mode (SKExecutionMode::Automatic). The estimator exposes matching getters plus resolve_plan.
  • SKGradientBoostingClassifierModel<F> — immutable fitted classifier implementing SKClassifierPredictor<F> (predict_labels, predict_probabilities) plus probabilities, number_of_stages, trees_per_stage (1 for binary, C for multiclass), stage_trees, stage_tree, initial_predictions, initial_prediction (Some only for binary), learning_rate, classes, number_of_classes, feature_count, feature_importances, stage_feature_importances, loss, backend and execution_intent. It is Send + Sync.
  • SKGradientBoostingRegressor<F> / SKGradientBoostingRegressorBuilder<F> — the regression counterpart, adding loss (SKGradientBoostingRegressionLoss) and huber_delta (default 1.0).
  • SKGradientBoostingRegressorModel<F> — implements SKRegressorPredictor<F> (predict) and exposes number_of_stages, stage_trees, stage_tree, initial_prediction, learning_rate, feature_count, feature_importances, stage_feature_importances, loss, huber_delta, backend and execution_intent.
  • SKGradientBoostingClassificationLoss / SKGradientBoostingRegressionLoss — the two public selectors. Classification has LogLoss; regression has SquaredError (default), AbsoluteError and Huber.
  • crates/sciencekit_ensemble/src/boosting/ — the public substrate: SKGradientLoss<F> (the loss contract), SKSquaredErrorLoss, SKAbsoluteErrorLoss, SKHuberLoss / SKHuberLossBuilder, SKBinaryLogLoss (with sigmoid) and SKMulticlassLogLoss / SKMulticlassLogLossBuilder (with softmax, initial_predictions, stage_gradients_and_hessians, loss_for_row).
  • SKTreeStructure’s advanced surface in crates/sciencekit_tree/src/structure/ — build_structure grows split geometry without criterion-driven leaves, and replace_leaf_values validates the leaf count and swaps in the Newton steps. The public SKDecisionTreeRegressor keeps using its own criterion and is unaffected.

The feature importances are sample-weighted: each stage tree’s normalized importances are multiplied by the number of rows it was fitted on, summed, and the total is renormalized to 1.0 when any split occurred (gradient_boosting/importances.rs). A model whose trees never split returns all zeros rather than dividing by zero.


5. A real walk-through, using the tests

Every claim above is pinned by a companion test. These are the ones worth reading, by name.

newton_leaf_value_matches_hand_computed_step_and_degeneracy_guard

In boosting/boosting_stage_tests.rs. It feeds known gradients and Hessians to sk_newton_leaf_value, checks the exact quotient $-\sum g / (\sum h + \lambda)$ including a non-zero $\lambda$, and checks that a leaf with a zero Hessian sum yields 0.0 instead of an infinite value.

single_stage_stump_and_split_apply_newton_leaves_and_shrinkage and multiclass_single_stage_fits_one_tree_per_class

Also in boosting_stage_tests.rs. The first grows one depth-0 stump and one depth-1 split, verifying that leaf values are Newton steps and that the raw scores are updated by $\text{learning_rate} \times \text{tree}$. The second verifies the multiclass bookkeeping: one tree per canonical class, each column updated from its own tree.

full_subsample_uses_every_training_row and stochastic_row_and_feature_subsampling_are_reproducible_and_diversify

In boosting/boosting_subsample_tests.rs. The first proves that subsample = 1.0 selects 0..n in order and consumes no randomness. The second proves that a stochastic run draws the same rows twice, draws different rows for different stage indices, and that changing maximum_features does not perturb the row draw.

seeded_validation_splits_are_deterministic_disjoint_and_stratified, monitor_stops_after_patience_and_reports_best_stage_count and scalar_binary_and_multiclass_loops_stop_early_and_restore_best_stages

In boosting/boosting_early_stop_tests.rs. Together they cover the whole early-stopping contract: the same seed yields the same disjoint split, the split keeps every class present, the monitor stops exactly after patience non-improving stages and reports the best stage count, and both the scalar and multiclass loops truncate the fitted stages back to that count.

hand_computed_binary_fit_and_zero_score_sigmoid and separable_binary_fixture_and_backend_span_propagation

In gradient_boosting/gb_classifier_tests.rs. The first is the hand calculation described in Section 3: a depth-0 stump leaves the score at 0.0 and the tie breaks toward canonical class 0; a depth-1 stage produces leaves [-2.0, +2.0], shrinks them to ∓0.5, and the probabilities match sigmoid(∓0.5) to 1e-12. The second fits separable nominal classes to 100 % accuracy and records the configured backend on the prediction span.

multiclass_fits_one_tree_per_class_per_stage_and_softmax_sums_to_one and multiclass_equal_scores_break_ties_toward_smallest_canonical_index

In gradient_boosting/gb_classifier_multiclass_tests.rs. The first fits three nominal classes (red, green, blue), asserts trees_per_stage() == 3, that every stage holds three trees, that classes().label_of(..) preserves first-appearance order, and that every softmax row sums to 1.0. The second proves the deterministic tie-break on a depth-0 uniform model.

hand_computed_single_stage_updates_for_all_three_regression_losses and smooth_response_recovered_under_every_regression_loss

In gradient_boosting/gb_regressor_tests.rs. The first pins all three losses against paper arithmetic: squared error gives init = 2.0 and a 0.5 leaf shrunk to 2.05; absolute error turns sign gradients [-1, +1] into predictions [4.5, 5.5]; Huber with delta = 1.0 clips residuals ±10 to ±1 and predicts [9.5, 10.5]. The second recovers a smooth sin(x) + 0.5x response under all three losses and checks that integer targets promote cleanly.

two_stages_with_different_importances_produce_sample_weighted_aggregate and classifier_importances_normalize_and_zero_split_boosters_return_zeros

In gradient_boosting/gb_importances_tests.rs. They check the exact weighted aggregation formula and the normalization and zero-split behaviour of feature_importances.

classifier_and_regressor_dense_and_sparse_fit_and_predict_are_equivalent and ultra_wide_sparse_never_densifies_and_csc_is_rejected

In gradient_boosting/gb_representation_tests.rs. The first compares all four dense/CSR fit and predict combinations, including feature importances and initial predictions, for multiclass and all three regression losses under subsampling and early stopping. The second fits a 128 × 100 000 CSR matrix to prove no densification ever happens, and asserts that a CSC view is rejected with the to_csr suggestion.

gradient_boosting_types_are_send_and_sync and repeated_fits_and_rayon_thread_counts_produce_identical_models

In gradient_boosting/gb_determinism_tests/. The first is a compile-time assertion over builders, estimators, models and loss types. The second runs the same fit twice on a one-thread pool and once on a four-thread pool, then compares stage counts, stage trees, feature importances and predictions for exact equality.

concurrent_prediction_agrees_with_sequential_and_records_regressor_backend

In gradient_boosting/gb_determinism_tests/concurrency_tests.rs. Eight OS threads share one fitted model, predict concurrently, agree with the sequential result, and the span recorder confirms the regressor’s configured backend is on the prediction span.

empty_input_and_shape_mismatches_are_rejected, hyperparameter_bounds_and_early_stop_validation_are_enforced and single_class_non_finite_values_and_streaming_modes_are_rejected

In gradient_boosting/gb_validation_tests.rs. They cover EmptyInput on fit and predict, ShapeMismatch for column and row mismatches, every builder bound (number_of_estimators >= 1, finite positive learning_rate, valid maximum_features, subsample ∈ (0, 1], non-negative finite l2_regularization, validation_fraction ∈ (0, 1), n_iter_no_change >= 1, non-negative tolerance), plus single-class targets, non-finite features and the rejection of OutOfCoreStreaming fit with ExecutionModeIncompatible.

tiny_gradient_boosting_fits_and_scores_in_f32_and_f64 and the 20 000-row acceptance suites

In gradient_boosting/acceptance_tests/ (the folder added for task 7.1). The tiny suite fits a sparse binary classifier in f64, a dense multiclass classifier in f32, and all three regression losses in f32, scoring accuracy $1.0$ and $R^2 > 0.85$ through sciencekit_metrics. large_binary_and_multiclass_gradient_boosting_with_metrics builds a deterministic 20 000 × 5 design, fits with subsampling, Sqrt feature sampling and early stopping, asserts dense and sparse probabilities are identical, and requires accuracy and macro-$F_1$ above $0.85$ and log-loss below $0.40$ for binary, plus accuracy and macro-$F_1$ above $0.82$ for multiclass. large_regression_gradient_boosting_all_losses_early_stop_and_metrics runs the same design through SquaredError, AbsoluteError and Huber, asserts dense/CSR prediction equality, and requires $\mathrm{MSE} < 0.45$, $\mathrm{MAE} < 0.50$ and $R^2 > 0.85$, then explicitly checks that a learning_rate(1.0) run with patience 3 returns fewer than its 30 allowed stages — early stopping measured on real data.


6. Look inside

PathResponsibility
boosting/mod.rsPure dispatcher and public re-exports of the substrate
boosting/loss/contract.rsThe SKGradientLoss<F> trait and the target-mean helper
boosting/loss/{squared,absolute,huber}.rsThe three regression losses, their gradients and Hessians
boosting/loss/log_loss.rsBinary sigmoid log-loss and multiclass softmax log-loss, including per-class gradients/Hessians and loss_for_row
boosting/init.rsInitial raw scores and the Newton leaf step with its degeneracy guard
boosting/stage.rsSeed derivation, one scalar stage, one multiclass stage, leaf replacement
boosting/subsample.rsSeeded without-replacement row draws and non-densifying dense/CSR gathering
boosting/early_stopping.rsValidation splits (plain and stratified) and the patience monitor
boosting/scores.rssk_update_raw_scores, the additive shrunk update used by fit and validation
boosting/scalar_loop.rs, boosting/multiclass_loop.rsThe stage drivers with optional early stopping and truncation
gradient_boosting/classifier.rs, regressor.rsEstimator configurations and getters
gradient_boosting/{classifier,regressor}_builder.rsThe sole construction surfaces and validation
gradient_boosting/config.rsShared defaults, hyperparameter validation and stage-parameter assembly
gradient_boosting/classifier_fit.rs, regressor_fit.rsFit orchestration, loss selection, model assembly
gradient_boosting/{classifier,regressor}_model.rsFitted models and their inspection surface
gradient_boosting/classifier_predict.rs, regressor_predict.rsSigmoid/softmax prediction over dense and CSR input
gradient_boosting/importances.rsSample-weighted aggregation and normalization
gradient_boosting/validation.rsDimensions, finiteness, streaming rejection, target canonicalization, row-parallel prediction
gradient_boosting/*_tests.rs, gradient_boosting/gb_determinism_tests/Companion TDD suites
gradient_boosting/acceptance_tests/gb_tiny_tests.rs, gb_large_tests.rsTiny and 20 000-row acceptance suites
crates/sciencekit_tree/src/structure/build_structure and replace_leaf_values, the advanced tree surface boosting consumes

7. What this unlocks

sciencekit now has the second half of the ensemble story: bagging reduces variance by averaging independent learners, and boosting reduces bias by fitting a sequence of small corrections. The substrate is intentionally loss-agnostic and representation-agnostic, which is the foundation the next steps build on:

  • Histogram gradient boosting can reuse SKGradientLoss, the stage loop, subsampling and early stopping, replacing only the exact split search with binned feature histograms.
  • Categorical and missing-value routing can extend the tree structure builder without touching the boosting drivers.
  • Streaming and out-of-core fitting, memmap datasets and model export are explicitly deferred in this change: fit rejects OutOfCoreStreaming, and the fitted models do not yet implement SKExportable. Those land as their own specs.
  • Quantile and Poisson losses only need new SKGradientLoss implementations plus a public selector variant; the loop does not change.

Until then, the exact-split booster is the reference against which faster approximations can be measured — and every one of the guarantees above is protected by a named test.

Outlier detection: random isolation trees, path length and the contamination offset

Most unsupervised algorithms begin by modeling what normal looks like — fitting cluster centers, estimating local point density, or projecting onto principal directions — and only afterward ask whether a new point sits awkwardly far from that model. Distance and density work well in low dimensions, yet both degrade rapidly as columns multiply or when anomalies hide in sparse, mixed-scale tabular records.

Isolation Forest flips the question upside down. Instead of measuring how dense normal points are, it measures how easy each point is to isolate with purely random axis-aligned cuts. A point far from the crowd lands alone in a leaf after one or two cuts; a point buried inside a tight cluster survives cut after cut before finally separating from its neighbors.

This chapter builds the model-side outlier contract (SKOutlierLabel and SKOutlierPredictor<F>) in crates/sciencekit_common/src/fit_traits/outlier.rs (capability outlier-prediction) and SKIsolationForest<F> in the new sub-crate crates/sciencekit_outlier/ (capability isolation-forest). No prior Rust or numerical-computing background is assumed.


1. The problem, in plain words

Given a table $X$ with $n$ rows and $p$ numeric features — and no ground-truth labels — we want to assign every row both:

  1. a continuous score ranking how anomalous or normal the row looks relative to the training population; and
  2. a clear binary verdict: inlier (normal) or outlier (anomalous).

Four traps make naive anomaly detectors fragile in production:

  1. Distance concentration and feature scale. Euclidean distance treats a column measured in millimeters ($0 \dots 1000$) as a thousand times more important than a column measured in meters ($0 \dots 1$). Random splits drawn uniformly between each feature’s observed minimum and maximum are invariant to monotone linear rescaling of individual columns.
  2. Quadratic or density bottlenecks. Pairwise distances over $n$ rows cost $O(n^2)$ work unless spatial trees apply, and spatial trees break down on wide sparse tables. Growing fixed-budget isolation trees on subsamples of size $\psi = \min(256, n)$ bounds tree depth at $\lceil \log_2 \psi \rceil \le 8$, giving linear $O(T \psi \log \psi)$ fit cost and $O(T \log \psi)$ per-row scoring cost.
  3. Magic integer sentinels (-1 vs 1). Classic libraries return raw integers (-1 for outliers, 1 for inliers), letting callers accidentally pass outlier flags into arithmetic or confuse -1 with class index 0. In Rust, a one-byte enum makes illegal values unrepresentable while keeping explicit -1/1 conversion at external FFI or metric boundaries.
  4. Accidental densification. Expanding a $64 \times 10{,}000$ sparse Compressed Sparse Row (CSR) subsample into $640{,}000$ dense floats just to scan column bounds wastes memory and cache bandwidth.

2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Dedicated sciencekit_outlier crate + shared SKOutlierPredictor<F> in sciencekit_commonAnomaly detection is its own estimator family alongside classifiers, regressors and clusterers. Placing the trait and one-byte SKOutlierLabel { Inlier, Outlier } in sciencekit_common lets pipelines, scorers and future detectors (SKLocalOutlierFactor, SKOneClassSVM) speak one contract, while keeping isolation-tree internals isolated in sciencekit_outlier.Returning raw Array1<i64> with -1/1 sentinels (invites silent confusion with zero-based class indices) or stuffing SKIsolationForest into sciencekit_ensemble (couples unsupervised anomaly scoring to supervised target canonicalization).
Reuse sciencekit_tree::SKTree node storage, write a dedicated random splitterSKTree and SKTreeNode already give a cache-friendly flat node vector (split_feature, threshold, left_child, right_child, sample_count) and zero-allocation traversal (leaf_and_depth_for). Isolation splits pick a random varying feature and a uniform threshold in $[\min, \max)$, which has nothing in common with CART impurity minimization.Reusing CART’s impurity splitter (wrong mathematical objective) or inventing a second pointer-chasing heap tree struct (hurts cache locality during ensemble scoring).
Normalized Liu–Ting–Zhou score $s(x, \psi) = 2^{-E[h(x)] / c(\psi)}$ paired with score_samples = -s and decision_function = score_samples - offsetRaw tree depth depends on the subsample size $\psi$. Dividing expected path length $E[h(x)]$ by the BST unsuccessful-search constant $c(\psi)$ maps every dataset onto a universal $[0, 1]$ anomaly scale ($s \to 1$ for shallow anomalies, $s < 0.5$ for deep inliers). Exposing anomaly_scores ($s \in [0, 1]$), score_samples ($-s \in [-1, 0]$, larger = more normal) and decision_function (score_samples - offset, negative = Outlier) satisfies both the original paper and external tool conventions.Returning unnormalized average edge depth (changes threshold meaning whenever maximum_samples or row count changes).
SKContamination::Auto (-0.5 offset) or SKContamination::Fraction(q) ($q \in (0, 0.5]$)When the user has no prior on anomaly prevalence, Auto applies the paper’s fixed threshold $s > 0.5 \iff -s - (-0.5) < 0$. When a domain contamination rate $q$ is known, Fraction(q) sets offset to the exact linear-interpolated $q$-quantile of the training score_samples.Requiring an explicit fraction on every call (forces users to guess a rate even on clean training sets).
CSR-to-CSC per-tree subsample gathering without densificationTraining inputs arrive row-major (CSR), whereas node splits scan one feature column at a time (feature_bounds and partition_rows). Gathering only the $\psi$ sampled CSR rows directly into a compact Compressed Sparse Column (CSC) matrix keeps storage proportional to stored non-zeros (nnz) while making column min/max and partitioning linear in stored entries plus implicit zeros.Calling to_dense() on sparse subsamples (violates the workspace representation-parity rule and blows up on wide sparse tables).

3. The concepts, taught from zero

How a random isolation tree isolates an outlier early

Imagine eight points on a plane: seven clustered tightly near $(0, 0)$ and one lone anomaly out at $(100, 800)$. To grow one isolation tree on a subsample of $\psi$ rows:

  1. Stop immediately and emit a leaf recording sample_count if the node holds $\le 1$ row, reaches the height limit $L = \lceil \log_2 \psi \rceil$, or has no feature whose values vary across the node’s rows.
  2. Otherwise pick a candidate feature $j$ uniformly at random (retrying across a shuffled fallback list if feature $j$ is constant on this node), read its observed range $[v_{\min}, v_{\max}]$ on the node’s rows, and draw a split threshold $t \sim \text{Uniform}[v_{\min}, v_{\max})$.
  3. Send rows with $x_j \le t$ to the left child and rows with $x_j > t$ to the right child, then recurse with depth + 1.

Because $[v_{\min}, v_{\max}]$ spans $[0, 100]$ on the root node while all seven normal points sit inside $[0, 6]$, roughly $94%$ of the interval $[0, 100)$ falls between the normal cluster and the outlier! Almost every random cut immediately strands $(100, 800)$ alone in a depth-$1$ leaf, while the normal points remain grouped together and require many further cuts.

flowchart TB
    accTitle: Shallow isolation of an anomaly versus deep partitioning of normal points
    accDescr: At the root node containing 8 samples, a random threshold on feature 0 between 6.0 and 100.0 immediately isolates the outlier (100, 800) into a right leaf of size 1 at depth 1. Meanwhile the 7 clustered normal points move together to the left branch, splitting repeatedly until reaching deeper leaves or the depth ceiling ceil(log2(8)) = 3.
    R["Root Node (8 samples)<br/>feature 0 <= 41.2"] -->|"Yes (7 normal rows)"| N1["Internal Node (7 samples)<br/>feature 1 <= 34.8"]
    R -->|"No (isolated!)"| OUT["Outlier Leaf<br/>depth = 1, size = 1<br/>h(x) = 1 + c(1) = 1.0"]
    N1 -->|"Yes"| N2["Internal Node (3 samples)<br/>feature 0 <= 1.4"]
    N1 -->|"No"| N3["Internal Node (4 samples)<br/>feature 1 <= 55.0"]
    N2 --> L1["Leaf (depth = 3, size = 2)<br/>h(x) = 3 + c(2) = 4.0"]
    N2 --> L2["Leaf (depth = 3, size = 1)<br/>h(x) = 3 + c(1) = 3.0"]
    N3 --> L3["Leaf (depth = 3, size = 2)<br/>h(x) = 3 + c(2) = 4.0"]
    N3 --> L4["Leaf (depth = 3, size = 2)<br/>h(x) = 3 + c(2) = 4.0"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef rose fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#7f1d1d
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    class R,N1,N2,N3 sky
    class OUT rose
    class L1,L2,L3,L4 emerald

Unsplit leaves and the harmonic correction $c(m)$

Because tree growth stops at the height limit $L = \lceil \log_2 \psi \rceil$ (for $\psi = 256$, $L = 8$), normal points often land in a leaf that still holds $m > 1$ unseparated rows. We do not need to keep splitting normal clusters to estimate how many additional random cuts those $m$ rows would have taken: random binary partitioning has the same combinatorics as an unsuccessful search in a random Binary Search Tree (BST) of $m$ keys!

The average path length $c(m)$ of an unsuccessful BST search is:

$$ c(m) = \begin{cases} 0 & \text{if } m \le 1, \[4pt] 2 H(m - 1) - \dfrac{2(m - 1)}{m} & \text{if } m > 1, \end{cases} $$

where $H(k) = \sum_{i=1}^{k} \frac{1}{i}$ is the $k$-th harmonic number. In score.rs, harmonic_number sums the exact reciprocals up to $k = 2048$ and switches seamlessly above $2048$ to the Euler–Maclaurin expansion

$$ H(k) \approx \ln k + \gamma + \frac{1}{2k} - \frac{1}{12k^2} + \frac{1}{120k^4}, $$

with Euler–Mascheroni constant $\gamma \approx 0.5772156649015329$, matching all $53$ IEEE-754 f64 mantissa bits without looping millions of times on large explicit Count subsamples.

When query row $x$ reaches a leaf at edge depth $d_t(x)$ containing $m_t(x)$ training samples in tree $t$, its adjusted path length is:

$$ h_t(x) = d_t(x) + c!\bigl(m_t(x)\bigr). $$

From expected depth to anomaly score, score_samples, offset and predict

Averaging $h_t(x)$ across all $T$ trees gives the expected path length $E[h(x)] = \frac{1}{T} \sum_{t=1}^{T} h_t(x)$. Normalizing by $c(\psi)$ — the average path length of the whole $\psi$-row tree — yields the Liu–Ting–Zhou anomaly score:

$$ s(x, \psi) = 2^{-E[h(x)] / c(\psi)} \in [0, 1]. $$

Look at the three landmarks of $s(x, \psi)$:

  • Shallow isolation ($E[h(x)] \ll c(\psi)$): the exponent approaches $0$, so $s(x, \psi) \to 1$ (strong anomaly).
  • Average depth ($E[h(x)] = c(\psi)$): $s(x, \psi) = 2^{-1} = 0.5$ (boundary).
  • Deep isolation ($E[h(x)] \gg c(\psi)$): $s(x, \psi)$ shrinks toward $0$ (clear inlier).

To align with the shared SKOutlierPredictor<F> contract — where higher scores mean more normal and negative decision values flag outliers — SKIsolationForestModel<F> derives three chained quantities:

$$ \text{score_samples}(x) = -s(x, \psi) \in [-1, 0], \qquad \text{decision_function}(x) = \text{score_samples}(x) - \text{offset}, $$

$$ \text{predict}(x) = \begin{cases} \texttt{SKOutlierLabel::Outlier} & \text{if } \text{decision_function}(x) < 0, \ \texttt{SKOutlierLabel::Inlier} & \text{if } \text{decision_function}(x) \ge 0. \end{cases} $$

  • Under SKContamination::Auto (default), $\text{offset} = -0.5$ (SK_ISOLATION_AUTO_OFFSET), so $\text{decision_function}(x) = 0.5 - s(x, \psi)$, flagging rows with $s(x, \psi) > 0.5$.
  • Under SKContamination::Fraction(q) with $q \in (0, 0.5]$, fit scores the training matrix once and sets offset to the exact linear-interpolated $q$-quantile of the sorted training score_samples.
flowchart LR
    accTitle: End-to-end Isolation Forest pipeline from dense or CSR input to typed SKOutlierLabel
    accDescr: Input features enter as Dense ArrayView2 or Sparse CsMatView without densification. During fit, independent SplitMix64 sub-seeds draw subsamples and candidate features for T trees, producing flat SKTree node arrays and a threshold offset. During inference, each row traverses the T trees to compute expected depth E[h(x)], anomaly score s in [0, 1], score_samples = -s, decision_function = score_samples - offset, and finally the 1-byte SKOutlierLabel enum.
    IN["SKDataView<br/>Dense or CSR"] --> SUB["Seeded Subsamples<br/>Dense Array2 or<br/>Sparse CSC (no densify)"]
    SUB --> TREES["T Isolation Trees<br/>SKTree flat nodes<br/>depth <= ceil(log2(psi))"]
    TREES --> DEPTH["Expected Path<br/>E[h(x)] = mean(d + c(size))"]
    DEPTH --> ANOM["anomaly_scores<br/>s = 2^(-E[h]/c(psi)) in [0, 1]"]
    ANOM --> NORM["score_samples = -s<br/>decision = -s - offset"]
    NORM --> LBL["SKOutlierLabel<br/>decision < 0 -> Outlier<br/>decision >= 0 -> Inlier"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef violet fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    class IN,SUB sky
    class TREES,DEPTH violet
    class ANOM,NORM amber
    class LBL emerald

Non-densifying sparse CSC subsamples and thread-count-invariant seeds

How do dense and sparse CSR fits produce bit-for-bit identical trees and scores across $1, 2, 4$ or $8$ Rayon worker threads?

  1. Three independent SplitMix64 sub-seeds per tree. For each tree_index in 0..number_of_trees, sk_prepare_tree_draws derives tree_seed from (random_seed, SK_RANDOM_DOMAIN_TREE, tree_index) and then derives three separate stage streams (SK_RANDOM_DOMAIN_STAGE indices 0, 1, 2) for row subsampling, feature subsampling, and in-tree split thresholds. Tree $t$ never touches another tree’s generator, so Rayon slot scheduling cannot alter a single bit.
  2. Order-preserving CSR-to-CSC gathering. When the input is CSR, SparseSubsample::from_csr_rows counts stored entries per column across the $\psi$ sampled rows and packs them into a compact CsMat::new_csc whose row indices 0..psi are strictly ascending in every column. Merging a sorted active-row slice against a CSC column (for_each_column_value) visits explicit non-zeros and implicit zeros in the exact same row order 0..psi as DenseSubsample, yielding identical (minimum, maximum) bounds and identical (left_rows, right_rows) partitions without ever allocating a dense matrix.

4. Each public object, explained

  • SKOutlierLabel (sciencekit_common, re-exported by sciencekit_outlier) — a Copy, one-byte (size_of::<SKOutlierLabel>() == 1) enum with variants Inlier and Outlier. Exposes .is_inlier(), .is_outlier(), .to_i64() (Inlier -> 1, Outlier -> -1), and SKOutlierLabel::from_i64(code) (rejecting anything other than 1 or -1 with SKError::Conversion).
  • SKOutlierPredictor<F> (sciencekit_common, re-exported by sciencekit_outlier) — the model-side trait exposing .offset(), .score_samples(features), .decision_function(features) and .predict(features) over any dense or CSR input convertible into SKDataView<'a, F>.
  • SKIsolationMaximumSamples<F> — per-tree subsample policy: Auto (default, min(256, row_count) via SK_ISOLATION_DEFAULT_MAXIMUM_SAMPLES), Count(usize) (validated in 1..=row_count), or Fraction(F) in (0, 1].
  • SKContamination<F> — threshold offset policy: Auto (default, fixed offset SK_ISOLATION_AUTO_OFFSET = -0.5) or Fraction(F) in (0, 0.5].
  • SKIsolationForest<F> and SKIsolationForestBuilder<F> — builder-only estimator surface entered via SKIsolationForest::<F>::build(). Configures .number_of_trees(100), .maximum_samples(Auto), .contamination(Auto), .maximum_features(1.0), .bootstrap(false), .random_seed(0), .backend(SKBackendKind::Faer) and .execution_mode(SKExecutionMode::Automatic). Implements SKUnsupervisedFit<F> plus inherent .fit(features) and .fit_predict(features).
  • SKIsolationForestModel<F> — the Send + Sync, Clone, PartialEq fitted detector. Implements SKOutlierPredictor<F> and exposes inherent .anomaly_scores(features), .score_samples(features), .decision_function(features), .predict(features), .offset(), .subsample_size(), .feature_count(), .number_of_trees(), .tree(tree_index), .backend() and .execution_mode().
Explicit scope boundary (PRD §12, Wave 5.4). Local Outlier Factor, One-Class SVM, missing-value routing inside isolation trees, streaming/partial_fit, GPU kernels, memmap2-backed node arrays and model export (Wave 7) are documented non-goals of this change. Any NaN or infinite value is rejected up front with SKError::NonFiniteValue at its exact flat row-major position.

5. Walking through the real companion tests

Every requirement in outlier-prediction and isolation-forest is verified by companion *_tests.rs suites beside the implementation and in crates/sciencekit_outlier/src/acceptance_tests/:

outlier_label_size_is_one_byte_and_variants_report_roles, outlier_label_i64_interop_round_trips_and_rejects_invalid_values & outlier_constant_detector_agrees_across_scalars_representations_and_threads

In crates/sciencekit_common/src/fit_traits/outlier_tests.rs, the contract is proven before any tree is grown: size_of::<SKOutlierLabel>() is asserted equal to 1, 1 and -1 round-trip cleanly while 0, 2, -2, i64::MIN and i64::MAX fail with SKError::Conversion, and a stand-in ConstantRadiusDetector verifies f32/f64 label equality, CSR parity, decision == score - offset, and concurrent std::thread::scope reads.

isolation_tree_single_sample_becomes_immediate_leaf, isolation_tree_splits_stay_within_observed_feature_bounds_and_cap_depth & isolation_tree_skips_constant_features_and_stops_on_identical_rows

In isolation_tree_tests.rs, sk_isolation_depth_limit is checked at power-of-two boundaries (256 -> 8, 257 -> 9), a single-row matrix becomes an immediate depth-$0$ leaf, an $8$-row matrix is walked node-by-node to confirm every split threshold satisfies $\text{observed_min} \le t < \text{observed_max}$ with non-empty children and depth $\le 3$, and a matrix whose first two columns are constant forces the splitter onto column 2.

isolation_path_average_length_matches_hand_computed_harmonic_values & isolation_path_tree_and_forest_reduction_match_hand_built_trees

In isolation_path_tests.rs, sk_average_path_length is checked against exact fractions ($c(2) = 1$, $c(3) = \frac{5}{3}$, $c(4) = \frac{13}{6}$, $c(5) = \frac{77}{30}$) and across the $2049 \to 2050$ Euler–Maclaurin handoff to $10^{-14}$. Two hand-built SKTree instances then prove that outlier $x = 10.0$ gets $E[h] = 1.5$ and score $2^{-1.5 / (77/30)}$, whereas inlier $x = 1.0$ lands in multi-sample leaves with $E[h] = \frac{31}{12}$ and a strictly smaller anomaly score.

#![allow(unused)]
fn main() {
let detector = SKIsolationForest::<f64>::build()
    .number_of_trees(100)
    .contamination(SKContamination::Fraction(0.05))
    .random_seed(42)
    .build()?;

let model = detector.fit(&data)?;
let anomalies = model.anomaly_scores(&data)?;
let scores = model.score_samples(&data)?;
let decisions = model.decision_function(&data)?;
let labels = model.predict(&data)?;
}

isolation_representation_sparse_and_dense_trees_and_scores_match_exactly & isolation_representation_wide_sparse_subsample_never_densifies

In isolation_representation_tests.rs, $16$ seeded trees grown densely and from CSR over positive, negative and implicit-zero entries assert assert_eq!(dense_trees, sparse_trees) and match across all four tree/query combinations to $10^{-15}$. A $64 \times 10{,}000$ sparse matrix with $65$ non-zeros then verifies subsample.stored_entry_count() == 65 — proving zero densification.

isolation_builder_defaults_match_specification, isolation_builder_rejects_invalid_hyperparameters & isolation_validation_rejects_*

In isolation_builder_tests.rs and isolation_validation_tests.rs, every default (100 trees, Auto samples, Auto contamination, 1.0 features, bootstrap == false, seed 0, Faer, Automatic) and every invalid input is exercised: zero trees, zero or out-of-range sample sizes (including Count(10) on a $4$-row matrix at fit time), contamination outside $(0, 0.5]$ (with exact 0.5 accepted), empty dense/CSR matrices, feature-count mismatches, NaN and $\pm\infty$ in standard, transposed and CSR layouts, CSC inputs (UnsupportedRepresentation), and OutOfCoreStreaming (ExecutionModeIncompatible).

isolation_fit_builds_seeded_ensemble_and_transfers_model_state, isolation_score_*, isolation_concurrency_* & acceptance_large_20k_*

In isolation_fit_tests.rs, a tracing layer confirms fit records operation = "fit", dimensions and backend = "matrixmultiply" on its span and transfers that backend onto SKIsolationForestModel. isolation_score_tests.rs verifies Auto (-0.5) and Fraction quantile offsets, f32/f64 label invariance, fit_predict parity, and four-way dense/CSR scoring. isolation_concurrency_tests.rs and acceptance_tests/large_data_tests.rs fit and score $20{,}000$ rows ($19{,}600$ sparse-friendly inliers + $400$ anomalies), proving bit-identical models across 1, 2, 4, 8 Rayon threads, lock-free concurrent Arc serving across $8$ OS threads, and sk_roc_auc_score > 0.99, sk_average_precision_score > 0.95, sk_accuracy_score > 0.99 and sk_f1_score > 0.90 through sciencekit_metrics.


6. Look inside

FileResponsibility
crates/sciencekit_common/src/fit_traits/outlier.rsOne-byte SKOutlierLabel, to_i64 / from_i64 boundary conversions, and SKOutlierPredictor<F>.
crates/sciencekit_outlier/src/lib.rsCrate root (#![forbid(unsafe_code)], #![warn(missing_docs)]) and public re-exports.
crates/sciencekit_outlier/src/isolation_forest/mod.rsPure dispatcher declaring implementation modules and companion *_tests.rs suites.
crates/sciencekit_outlier/src/isolation_forest/config.rsSKIsolationMaximumSamples, SKContamination, SK_ISOLATION_DEFAULT_MAXIMUM_SAMPLES (256) and SK_ISOLATION_AUTO_OFFSET (-0.5).
crates/sciencekit_outlier/src/isolation_forest/builder.rsSKIsolationForestBuilder<F> defaults, setters, SKBuilder implementation and hyperparameter validation.
crates/sciencekit_outlier/src/isolation_forest/core_implementation.rsConfigured SKIsolationForest<F> estimator struct and configuration getters.
crates/sciencekit_outlier/src/isolation_forest/subsample.rsIsolationSampleSource<F>, DenseSubsample, feature-count resolution and SplitMix64 per-tree draw preparation.
crates/sciencekit_outlier/src/isolation_forest/sparse.rsNon-densifying SparseSubsample (CSR-to-CSC gather), sorted column merge and binary-searched CSR row lookup.
crates/sciencekit_outlier/src/isolation_forest/tree.rssk_isolation_depth_limit, uniform in-range split sampling, constant-feature fallback and flat SKTree assembly.
crates/sciencekit_outlier/src/isolation_forest/score.rsHarmonic/Euler–Maclaurin sk_average_path_length, sk_expected_path_length, sk_anomaly_score_from_expected_depth and sk_exact_quantile.
crates/sciencekit_outlier/src/isolation_forest/execution.rsRayon and synchronous slot runners (sk_execute_tree_slots, sk_map_rows) and streaming guard.
crates/sciencekit_outlier/src/isolation_forest/validation.rsRepresentation, empty-input, sample-bound, feature-width and flat-position finiteness checks.
crates/sciencekit_outlier/src/isolation_forest/fit.rsSKUnsupervisedFit<F>, ensemble construction, contamination quantile offset and Fit observability span.
crates/sciencekit_outlier/src/isolation_forest/model.rsSKIsolationForestModel<F> state and inspection accessors.
crates/sciencekit_outlier/src/isolation_forest/predict.rsanomaly_scores, score_samples, decision_function, predict, fit_predict and SKOutlierPredictor<F>.

7. Recap

  • Anomalies isolate shallowly under random cuts: SKIsolationForest needs no distance metric, density estimate, or feature standardization.
  • Harmonic BST normalization makes scores comparable: $s(x, \psi) = 2^{-E[h(x)] / c(\psi)}$ maps expected tree depth onto $[0, 1]$, score_samples = -s orders points from anomalous to normal, and decision_function = score_samples - offset separates outliers (< 0) from inliers (>= 0).
  • Contamination is explicit or hands-off: SKContamination::Auto applies the fixed -0.5 offset; SKContamination::Fraction(q) selects the exact $q$-quantile of training score_samples.
  • Typed one-byte labels replace magic integers: SKOutlierLabel::{Inlier, Outlier} keeps domain code type-safe and confines 1/-1 to to_i64 and from_i64.
  • Dense and sparse CSR stay bit-identical and thread-invariant: per-tree CSC subsamples never densify sparse matrices, and independent SplitMix64 sub-seeds guarantee identical models across any Rayon thread count.

Truncated SVD: uncentered low-rank factorization and the sparse path

Imagine a table of fifty thousand news articles across one hundred thousand vocabulary words. Each row counts how often a word appears in an article, so more than $99.9%$ of the cells are zero. In compressed-sparse-row (CSR) format, only the non-zero word counts are stored — tens of megabytes instead of forty gigabytes.

If you hand that table to Principal Component Analysis (SKPCA), the very first step of textbook PCA subtracts the average frequency of every word from every column. Subtracting a tiny positive number such as $0.002$ from a million zeros turns every single zero into $-0.002$: sparsity vanishes instantaneously. Even though SKPCA’s Randomized solver avoids materializing that dense matrix through implicit rank-one corrections, centering itself is often undesirable on term-document counts or TF-IDF weights, where zero genuinely means “absent” and shifting the origin mixes absence with negative signal.

Truncated Singular Value Decomposition (SKTruncatedSVD) solves the sister problem: find the best $k$-dimensional linear subspace directly on the uncentered matrix $X$, keeping sparse CSR inputs sparse from end to end — the classic foundation of Latent Semantic Analysis (LSA) and sparse dimensionality reduction.

This chapter walks through crates/sciencekit_decomposition/src/truncated_svd/ (capability truncated-svd), teaching every concept from zero, explaining why each engineering decision was taken (and which alternatives were discarded), touring the public Rust types, and tracing the real companion tests that lock the specification down.


1. The problem, in plain words

Given an observation table $X \in \mathbb{R}^{n \times d}$ with $n$ rows (samples or documents) and $d$ numeric features (columns or terms), and a target rank $k$ satisfying $1 \le k \le \min(n, d)$, we want $k$ mutually perpendicular unit directions in feature space — stored as the rows of $W \in \mathbb{R}^{k \times d}$ with $W W^{\top} = I_k$ — so that:

  1. Forward projection (transform) compresses each row $x \in \mathbb{R}^d$ into $k$ numbers without subtracting any mean vector: $$ Z = X W^{\top} \in \mathbb{R}^{n \times k}. $$
  2. Reconstruction (inverse_transform) maps a $k$-vector back to $d$ features without adding any mean vector: $$ \widehat{X} = Z W = X W^{\top} W \in \mathbb{R}^{n \times d}. $$
  3. Among all rank-$k$ approximations, $\widehat{X}$ minimizes the total squared reconstruction error $\lVert X - \widehat{X} \rVert_F^2 = \sum_{i=1}^{n} \sum_{j=1}^{d} (X_{i,j} - \widehat{X}_{i,j})^2$.

By the Eckart–Young–Mirsky theorem, those optimal rows of $W$ are the first $k$ right singular vectors of $X$ itself.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Separate SKTruncatedSVD<F> and SKTruncatedSVDModel<F> with zero centering stateKeeps configuration immutable and distinct from fitted parameters, and omits a mean vector altogether so the type system reflects the uncentered contract directly.Adding a center: bool flag onto SKPCA — blurs two estimators with different defaults, variance definitions and mean() invariants.
Reuse SKRandomizedSvdBuilder with centering = NoneChapter 39 already provides a seeded, sign-deterministic randomized range finder whose matrix operator multiplies dense and CSR views directly without materializing $n \times d$ buffers. Passing None skips the rank-one mean terms cleanly.Duplicating power-iteration loops inside sciencekit_decomposition — violates DRY and risks drifting in sign convention or seed stream.
SKTruncatedSVDAlgorithm (Randomized default, Arpack reserved)Matches the user-facing solver vocabulary while failing fast with InvalidHyperparameter if Arpack is selected before an implicitly restarted Lanczos kernel lands.Silently routing Arpack to Randomized — hides an approximate randomized run behind an exact iterative solver name.
Population variance of $Z = X W^{\mathsf T}$ divided by two-pass sparse column varianceBecause $X$ is uncentered, $\sigma_j^2 / n$ measures squared root-mean-square energy rather than statistical spread! Computing $\operatorname{Var}(Z_{:, c})$ over the projected rows and dividing by $\sum_{j=1}^{d} \operatorname{Var}(X_{:, j})$ measures true variance captured and satisfies $\sum_{c=1}^{k} \text{ratio}_c \le 1$.Computing $\sigma_j^2 / (n - 1)$ as if $X$ were centered — a constant matrix of $4.0$s has $\sigma_1 > 0$ yet zero variance, which would yield ratios exceeding $1$ or division by zero.
Modified Gram-Schmidt orthonormal completion (sk_complete_zero_norm_components)On rank-deficient or constant matrices ($r < k$), trailing singular directions from the small SVD can collapse numerically; completing them with canonical orthogonal unit vectors preserves $W W^{\top} = I_k$ without flipping active kernel signs.Leaving zero rows in components — breaks orthonormality ($W W^{\top} \ne I_k$).
Single-dispatch SKTruncatedInput plus 256-row chunked sk_multiply_view_by_denseEach public operation converts its SKDataView into a borrowed SKTruncatedInput exactly once (Dense or SparseCsr), rejecting CSC up front; validation, variance and multiplication then receive that prepared operand instead of re-dispatching per helper. The product uses backend.gemm(..., 1) on dense 256-row blocks and row-sliced CSR accumulation on sparse blocks, keeping 1-thread and multi-thread rayon runs bit-identical and never densifying CSR inputs.Re-matching SKDataView inside every helper — repeated dispatch, duplicated CSC handling, and error-returning arithmetic helpers that can no longer fail once the view is accepted. Calling sparse.to_dense() before gemm — allocates $\mathcal{O}(n \cdot d)$ memory and defeats the estimator’s reason to exist.
Explicit non-goals recorded in docs/PRD.md. Feature centering (use SKPCA), ARPACK/IRLBA solvers, missing-value routing, GPU kernels, memmap2-backed storage and model export (Wave 7) are intentionally deferred to their dedicated changes.

3. The concepts, taught from zero

What Singular Value Decomposition means geometrically

Any rectangular table $X \in \mathbb{R}^{n \times d}$ can be written as a sum of rank-one layers:

$$ X = \sum_{j=1}^{r} \sigma_j u_j v_j^{\top}, \qquad \sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_r > 0, $$

where:

  • each right singular vector $v_j \in \mathbb{R}^d$ ($\lVert v_j \rVert_2 = 1$) is a “concept” or “topic” — a weighted combination of the original features;
  • each left singular vector $u_j \in \mathbb{R}^n$ ($\lVert u_j \rVert_2 = 1$) gives each row’s relative affinity for that concept;
  • each singular value $\sigma_j \ge 0$ scales the overall strength of layer $j$.

Keeping only the top $k$ layers sets rows $0 \dots k - 1$ of components to $v_1^{\top}, \dots, v_k^{\top}$. Projecting $X$ onto those rows yields $Z = X W^{\top} = U_k \Sigma_k$, and multiplying back by $W$ yields the rank-$k$ approximation $\widehat{X} = U_k \Sigma_k V_k^{\top}$.

Why uncentered variance is subtle — and why ratios never exceed $1$

In SKPCA, subtracting column means guarantees $\bar{Z}_{:, c} = 0$, so the variance of projected column $c$ equals $\sigma_c^2 / (n - 1)$ automatically. Without centering, a matrix can have a huge singular value along a constant offset that carries zero spread across rows! For instance, on a $6 \times 3$ table filled with $4.0$, $\sigma_1 = \sqrt{6 \times 3 \times 16} = \sqrt{288}$, yet every row projects to the exact same value, so its variance is $0$.

SKTruncatedSVD therefore measures population variance directly on the projected coordinates $Z = X W^{\top}$:

$$ \mu_{Z, c} = \frac{1}{n} \sum_{i=1}^{n} Z_{i, c}, \qquad \text{explained_variance}c = \frac{1}{n} \sum{i=1}^{n} (Z_{i, c} - \mu_{Z, c})^2, $$

and divides by the total input column variance $\sigma_{\text{total}}^2 = \sum_{j=1}^{d} \operatorname{Var}(X_{:, j})$.

Why can the sum of explained_variance_ratio never exceed $1$? Let $C = \frac{1}{n}(X - \mathbf{1}\bar{x}^{\top})^{\top}(X - \mathbf{1}\bar{x}^{\top})$ be the population covariance matrix of $X$. Notice shifting $Z = X W^{\top}$ by its column mean gives $Z - \mathbf{1}\mu_Z^{\top} = (X - \mathbf{1}\bar{x}^{\top}) W^{\top}$, so:

$$ \sum_{c=1}^{k} \text{explained_variance}c = \operatorname{tr}(W C W^{\top}) \le \operatorname{tr}(C) = \sigma{\text{total}}^2, $$

because $C$ is positive semidefinite and $W W^{\top} = I_k$ projects onto a $k$-dimensional subspace! In variance.rs, sk_total_input_variance evaluates $\operatorname{tr}(C)$ on CSR inputs in two non-negative passes over stored non-zeros plus $(n - \text{nnz}_j)\bar{x}_j^2$ for the implicit zeros — $\mathcal{O}(\text{nnz} + d)$ work and zero dense allocation — and normalizes any single-ULP floating-point rounding overshoot so the sum of ratios is strictly at most $1$.

End-to-end sparse data flow without densification

flowchart TD
    accTitle: Non-densifying fit and transform pipeline in SKTruncatedSVD
    accDescr: Input features arrive as a Dense or Sparse CSR SKDataView. Validation checks dimensions, hyperparameters and finiteness in O(nnz) for CSR. Fit invokes SKRandomizedSvdBuilder with centering None, orthonormalizes components k by d, projects X onto components transpose via single-dispatch multiplication, and computes two-pass variance to produce SKTruncatedSVDModel.
    classDef input fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef check fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef kernel fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    classDef state fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef out fill:#ede9fe,stroke:#7c3aed,color:#3b0764

    In["SKDataView&lt;F&gt;<br/>Dense or Sparse CSR"]:::input --> Val["sk_validate_fit_input<br/>shape + k + finiteness"]:::check
    Val --> Rnd["SKRandomizedSvdBuilder<br/>centering = None"]:::kernel
    Rnd --> GS["Gram-Schmidt guard<br/>components k x d"]:::kernel
    GS --> Mul["sk_multiply_view_by_dense<br/>Z = X * W^T (n x k)"]:::kernel
    Mul --> Var["sk_variance_and_ratio<br/>O(nnz + d) CSR moments"]:::kernel
    Var --> Mod["SKTruncatedSVDModel&lt;F&gt;<br/>no centering vector"]:::state
    Mod -->|transform| Z["Projected Array2&lt;F&gt;<br/>m x k"]:::out
    Z -->|inverse_transform| Xhat["Reconstructed Array2&lt;F&gt;<br/>m x d"]:::out

At every stage on a sparse $n \times d$ input, the largest dense buffer ever allocated has $n \cdot (k + p)$ or $d \cdot (k + p)$ scalars (where $p = 10$ is the randomized oversampling), never $n \cdot d$.


4. Each public object, explained

flowchart LR
    accTitle: Public builder, estimator and fitted model types of SKTruncatedSVD
    accDescr: SKTruncatedSVDBuilder configures hyperparameters and builds an immutable SKTruncatedSVD estimator. Calling fit produces SKTruncatedSVDModel under a Fit observability span, while fit_transform returns the projected matrix under a single FitTransform span.
    classDef builder fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef est fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef model fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef span fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

    B["SKTruncatedSVDBuilder&lt;F&gt;<br/>defaults + validation"]:::builder -->|build| E["SKTruncatedSVD&lt;F&gt;<br/>immutable estimator"]:::est
    E -->|fit| FSpan["Fit span<br/>records backend"]:::span
    FSpan --> M["SKTruncatedSVDModel&lt;F&gt;<br/>W, sigma, variance"]:::model
    E -->|fit_transform| FTSpan["FitTransform span<br/>projected n x k"]:::span

SKTruncatedSVDAlgorithm and SK_TRUNCATED_SVD_PARITY_TOLERANCE

What they are — SKTruncatedSVDAlgorithm (truncated_svd/config.rs) is a #[non_exhaustive] solver enum with Randomized (the Default variant) and Arpack (reserved non-goal rejected at validation time). SK_TRUNCATED_SVD_PARITY_TOLERANCE (1e-6_f64) is the public constant documenting the dense/CSR equivalence and rank-$k$ reconstruction bound inherited from the randomized SVD kernel.

SKTruncatedSVDBuilder<F> and SKTruncatedSVD<F>

What they are — the mandatory builder (truncated_svd/builder.rs) and immutable estimator (truncated_svd/core_implementation.rs), parameterized only by F: SKFloat (because tolerance is a scalar; backend is a runtime SKBackendKind value).

Documented defaults and builder setters:

  • number_of_components(usize) — default 2 (must satisfy $1 \le k \le \min(n, d)$);
  • algorithm(SKTruncatedSVDAlgorithm) — default SKTruncatedSVDAlgorithm::Randomized;
  • number_of_iterations(usize) — default 5 (must be $> 0$);
  • tolerance(F) — default 0.0 (must be finite and $\ge 0$);
  • random_seed(u64) — default 0;
  • backend(SKBackendKind) — default SKBackendKind::Faer;
  • execution_mode(...) — default SKExecutionMode::Automatic.

Here is the real sparse CSR usage from crates/sciencekit_decomposition/src/lib.rs:

#![allow(unused)]
fn main() {
use sciencekit_common::{SKBuilder, SKUnsupervisedFit};
use sciencekit_decomposition::SKTruncatedSVD;
use sprs::TriMat;

let mut triplet = TriMat::new((4, 5));
triplet.add_triplet(0, 0, 2.0_f64);
triplet.add_triplet(1, 2, 4.0);
triplet.add_triplet(2, 0, 6.0);
triplet.add_triplet(3, 4, 3.0);
let sparse = triplet.to_csr();

let svd_model = SKTruncatedSVD::<f64>::build()
    .number_of_components(2)
    .random_seed(7)
    .build()
    .unwrap()
    .fit(sparse.view())
    .unwrap();
let projected = svd_model.transform(sparse.view()).unwrap();
assert_eq!(projected.dim(), (4, 2));
}

SKTruncatedSVD<F> implements SKUnsupervisedFit<F, Model = SKTruncatedSVDModel<F>, Error = SKError> and provides inherent fit_transform, which returns the projected training matrix directly from the fit pass under a single FitTransform span without projecting a second time.

SKTruncatedSVDModel<F>

What it is — the fitted model (truncated_svd/model.rs), Clone + Debug + PartialEq + Send + Sync, storing no centering vector. Structural equality compares components, singular values, both variance vectors and the transferred builder state, so determinism checks can assert whole models directly.

Accessors and operations:

  • components() — ArrayView2<'_, F> of shape $k \times d$ (rows are orthonormal right singular vectors);
  • singular_values() — non-increasing ArrayView1<'_, F> of length $k$;
  • explained_variance() and explained_variance_ratio() — ArrayView1<'_, F> of length $k$;
  • number_of_components(), number_of_features(), algorithm(), backend(), execution_mode();
  • transform (inherent and via SKFeatureTransformer<F>) and inverse_transform, both accepting dense views and sparse CSR views with a single dispatch per call and recording the transferred SKBackendKind in sciencekit.operation spans.

Because SKTruncatedSVD<F> implements SKUnsupervisedFit<F> and SKTruncatedSVDModel<F> implements SKFeatureTransformer<F, Output = Array2<F>>, SKTruncatedSVD<F> plugs straight into SKPipeline and SKFeatureUnion.


5. Walking through the real companion tests

Every scenario in openspec/changes/truncated-svd/specs/truncated-svd/spec.md is verified by a dedicated companion test module:

  1. Builder defaults and hyperparameter guards (truncated_builder_tests.rs, truncated_model_tests.rs). truncated_builder_defaults_match_the_documented_configuration confirms 2 components, Randomized, 5 iterations, tolerance 0.0, seed 0, Faer and Automatic. truncated_builder_overrides_are_exposed_on_the_estimator_and_via_trait checks every setter and SKBuilder trait dispatch on f32. truncated_builder_rejects_invalid_hyperparameters verifies InvalidHyperparameter for zero components, Arpack, zero iterations, negative tolerance and non-finite tolerances. truncated_model_exposes_uncentered_factorization_parts_and_default_algorithm checks all fitted accessors.
  2. Uncentered reconstruction, variance ordering and backend spans (truncated_fit_tests.rs). truncated_fit_reconstructs_rank_one_matrix_without_centering constructs the outer product $u v^{\top}$ with $u = [1, 2, 3, 4]^{\top}$ ($\lVert u \rVert_2 = \sqrt{30}$) and $v = [0.6, 0.8, 0]^{\top}$, verifying $\sigma_1 = \sqrt{30}$, explained_variance[0] = 1.25, explained_variance_ratio[0] = 1.0, fit_transform == fit + transform, and exact uncentered reconstruction of the non-zero feature means. truncated_fit_reconstructs_rank_two_matrix_with_non_increasing_variance checks row orthonormality ($W W^{\top} = I_2$), non-increasing singular values and explained variances, and $\sum \text{ratio} \le 1$. truncated_fit_completes_orthonormal_components_on_constant_and_rank_deficient_data fits $k = 2$ on a constant $6 \times 3$ matrix of $4.0$s, confirming $W W^{\top} = I_2$, $\sigma_1 = \sqrt{288}$ and zero variance ratios. truncated_fit_transfers_configured_backend_and_records_fit_and_fit_transform_spans captures sciencekit.operation spans to verify NdArrayLinalg and InProcessSynchronous propagate to both fit and fit_transform, then repeats the check on a default-built estimator to confirm the unconfigured Faer backend is recorded rather than a hardcoded kind.
  3. Dense/sparse CSR parity and the no-densification proof (truncated_representation_tests.rs). truncated_representation_sparse_csr_equals_dense_within_documented_tolerance builds a CSR view including an explicit stored zero and verifies components, singular_values, explained_variance, explained_variance_ratio and projections match the dense fit within SK_TRUNCATED_SVD_PARITY_TOLERANCE ($10^{-6}$). truncated_representation_wide_sparse_matrix_fits_without_densification fits and transforms a $1,500 \times 25,000$ CSR matrix ($300\text{ MB}$ if densified, only $6,000$ non-zeros) while asserting zero warnings and a peak materialized projection of only $1,500 \times 3 = 4,500$ scalars. truncated_representation_rejects_csc_up_front_before_scanning_elements embeds a NaN inside a CSC matrix and confirms UnsupportedRepresentation { representation: "csc", .. } fires before any element scan.
  4. All four dense/sparse transform pairs (truncated_transform_tests.rs). truncated_transform_and_inverse_transform_shapes_and_rank_k_reconstruction checks $m \times k$ forward shape, $m \times d$ inverse shape, SKFeatureTransformer dispatch and rank-$k$ reconstruction on unseen query rows. truncated_transform_accepts_dense_and_sparse_views_across_all_combinations verifies dense-fit and sparse-fit models on both dense and CSR queries, plus CSR input to inverse_transform. truncated_transform_and_inverse_transform_record_transferred_backend_in_spans verifies both model operations record MatrixMultiply in their spans.
  5. Input and shape validation (truncated_validation_tests.rs). truncated_validation_rejects_empty_inputs_and_propagates_conversion_failure, truncated_validation_rejects_zero_and_excessive_components_and_invalid_hyperparameters and truncated_validation_rejects_feature_count_mismatch_non_finite_and_csc_views test EmptyInput, InvalidHyperparameter when $k > \min(n, d)$ on tall and wide matrices, ShapeMismatch on mismatched column counts (including $2 \times 0$ queries), and NonFiniteValue with flat row-major positions across dense and CSR inputs. They also pin the single-dispatch boundary: a failing TryInto<SKDataView> adapter must surface its own SKError::Conversion from fit, inverse_transform must reject non-finite projected coordinates, and CSC views must be refused by transform and inverse_transform alike.
  6. Thread-count invariance, concurrency and metrics (truncated_concurrency_tests.rs, acceptance_tests/truncated_svd_acceptance_tests.rs). truncated_concurrency_estimator_builder_and_model_are_send_and_sync checks static Send + Sync bounds for f32 and f64. truncated_concurrency_repeated_fits_agree_across_runs_and_rayon_thread_counts runs 1-thread and 4-thread rayon pools on a $4,096 \times 32$ dense table and a $2,048 \times 64$ CSR table, asserting exact assert_eq! equality on whole models (components, singular values, variances and transferred configuration) and on projections. truncated_concurrency_shared_model_transforms_match_sequential_output shares an Arc<SKTruncatedSVDModel<f64>> across eight threads transforming dense and CSR batches. acceptance_truncated_svd_tiny_matrices_f32_and_component_boundaries and acceptance_truncated_svd_large_dense_and_wide_sparse_concurrency_and_metrics validate $1 \times 3$ boundaries, f32, $2,000 \times 10,000$ wide CSR concurrency, and monotonically decreasing sk_mean_squared_error reaching $R^2 > 0.9999$ (sk_r2_score) on a planted low-rank table.

6. Recap

  • SKTruncatedSVD<F> computes a seeded randomized low-rank SVD on the uncentered design, storing no mean vector and never densifying sparse CSR matrices during fit, fit_transform, transform or inverse_transform.
  • Population explained_variance is measured over the projected training rows and divided by the two-pass $\mathcal{O}(\text{nnz} + d)$ total input variance so explained_variance_ratio sums to at most $1$ on every input.
  • Fixed 256-row chunks, modified Gram-Schmidt completion and runtime SKBackendKind propagation keep every operation deterministic across thread counts, safe under Arc concurrency and observable in sciencekit.operation spans.

Incremental PCA: merging covariance across batches and streams

In Chapter 44, SKPCA found the directions of greatest spread in a feature table by inspecting the whole dataset in memory. That works beautifully until the dataset has fifty million rows on disk or arrives one network chunk at a time. You cannot subtract a global mean before you have seen every row, and you cannot keep fifty million rows in RAM while you wait.

Incremental Principal Component Analysis (SKIncrementalPCA) breaks that deadlock. Instead of holding onto rows, it keeps a tiny, fixed-size statistical summary of everything seen so far: the sample count $n$, the running feature mean $\mu \in \mathbb{R}^d$, and the $d \times d$ centered scatter matrix $S$. Each new batch — whether from an in-memory chunk, a manual partial_fit call, or an out-of-core SKSourceProvider stream — is folded into $(n, \mu, S)$ via the Chan-Golub-LeVeque merge and then discarded immediately. When the model finalizes, a single symmetric eigendecomposition on $S / (n - 1)$ recovers the exact same principal axes that full batch PCA would have found on the concatenated dataset.

This chapter walks through crates/sciencekit_decomposition/src/incremental_pca/ (capability incremental-pca), teaching the algebra and floating-point mechanics from zero, explaining every public type and method, and tracing the real companion tests that prove each guarantee.


1. The problem, in plain words

Imagine measuring $d$ numeric sensors across millions of events. A table with $n = 10^7$ rows and $d = 64$ double-precision columns occupies roughly $5.1\text{ GB}$ of raw numbers, yet its sample mean has only $64$ numbers and its sample covariance matrix has only $64 \times 64 = 4,096$ numbers — barely $32\text{ KB}$!

The catch is centering. Sample covariance measures how features co-vary around the global mean $\mu$:

$$ C = \frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \mu)(x_i - \mu)^{\top}. $$

If batch $A$ has mean $\mu_A$ and batch $B$ has a different mean $\mu_B$, you cannot just add their separate scatter matrices together: both were centered around their local batch means rather than the combined mean $\mu_{AB}$. Throwing batch $A$ away seems to make re-centering impossible — until a clean algebraic identity comes to the rescue.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Exact Chan-Golub-LeVeque $(n, \mu, S)$ covariance state (SKCovarianceAccumulator<F>)Merging $(n_A, \mu_A, S_A)$ and $(n_B, \mu_B, S_B)$ is algebraically exact, associative across batch boundaries, independent of batch order, and requires $\mathcal{O}(d^2)$ memory with zero row retention. Finalizing via $C = S / (n - 1)$ and backend.eigh matches full PCA to machine precision.Approximate rank-$k$ SVD sketches (Ross et al. / scikit-learn’s truncated SVD update) — fast when $d$ is huge, but approximate and sensitive to batch order; kept open as a separate future rank-adaptive change.
Separate dense and sparse CSR batch paths that meet at sk_merge_momentsDense batches center 256-row blocks and call backend.gemm for cache-friendly BLAS speed. Sparse CSR batches accumulate stored non-zeros into column sums and a $d \times d$ Gram matrix with Neumaier compensated summation, then form $S_B = G_B - n_B \mu_B \mu_B^{\top}$ without ever materializing a dense batch.Densifying each sparse batch before centering — violates representation parity (data-view-boundary) and explodes memory on sparse wide streams; or using naive uncompensated $\sum x^2 - n\mu^2$ everywhere — loses precision when means are large.
Shared fit, partial_fit and fit_streaming over one merge kernelfit slices an in-memory view into batch_size blocks (coalescing any trailing remainder smaller than number_of_components); partial_fit merges a new batch into SKIncrementalPCAModel and refreshes the eigendecomposition; fit_streaming drives SKSourceProvider through sk_run_streaming_provider with SKStreamingPassPolicy::Iterative.Separate code paths for in-memory chunking and streaming — risks drift between fit, partial_fit and fit_streaming.
Fixed 256-row reduction chunks folded in index orderBoth dense batch moments and dense transform / inverse_transform split rows into deterministic 256-row blocks (DENSE_MOMENT_ROW_CHUNK, DENSE_TRANSFORM_ROW_CHUNK and DENSE_RECONSTRUCT_ROW_CHUNK), evaluate chunks via rayon when plan.parallelism > 1, and sum chunk partials in strict sequence order. One thread and four threads produce bit-identical arrays (assert_eq!).Letting rayon fold partials in work-stealing tree order — floating-point addition is non-associative, causing thread-count drift.
Format-agnostic SKExportable / SKImportable state including the accumulatorExporting components, mean, scatter, variances, singular values and sample/epoch counters into SKModelState<F> lets an imported SKIncrementalPCAModel<F> both transform immediately and continue learning via partial_fit.Exporting only components and mean — would silently break incremental continuation after model reload.
Explicit non-goals for this change. Missing-value imputation inside PCA, rank-adaptive component counts, GPU kernels and memmap2-backed storage are outside this change and recorded in docs/PRD.md. Binary file persistence is not reimplemented here either: the model exposes format-agnostic SKExportable/SKImportable state, and the shared sciencekit_interop adapters own the concrete on-disk encodings (JSON debug and the extended Safetensors format).

3. The concepts, taught from zero

What a scatter matrix is

For a batch of $n$ rows with empirical mean $\mu = \frac{1}{n}\sum_{i=1}^n x_i$, the scatter matrix $S \in \mathbb{R}^{d \times d}$ sums the outer products of each row’s deviation from $\mu$:

$$ S = \sum_{i=1}^{n} (x_i - \mu)(x_i - \mu)^{\top}. $$

Entry $S_{p, q}$ measures how strongly feature $p$ and feature $q$ move together across the $n$ rows. Dividing by $n - 1$ turns total scatter into average unbiased sample covariance: $C = \frac{1}{n - 1} S$.

The Chan-Golub-LeVeque merge, worked by hand

Suppose we already summarized batch $A$ into $(n_A, \mu_A, S_A)$, and a fresh batch $B$ arrives with $(n_B, \mu_B, S_B)$. Let $n = n_A + n_B$ and write the gap between the two batch means as $\delta = \mu_B - \mu_A$. Algebra shows that the combined mean and combined scatter over $A \cup B$ satisfy:

$$ \mu = \mu_A + \frac{n_B}{n},\delta, \qquad S = S_A + S_B + \frac{n_A n_B}{n},\delta \delta^{\top}. $$

Every term on the right-hand side depends only on the two summaries — none of the individual rows of $A$ or $B$ are needed again!

Let us check this with four tiny 2D rows — the exact fixture locked by incremental_merge_hand_checked_two_batch_mean_and_scatter in incremental_merge_tests.rs:

  • Batch 1: $[1, 2]$ and $[3, 6]$ ($n_A = 2$). Its mean is $\mu_A = [2, 4]$. Deviations are $[-1, -2]$ and $[1, 2]$, so $$ S_A = \begin{bmatrix} 1 + 1 & 2 + 2 \ 2 + 2 & 4 + 4 \end{bmatrix} = \begin{bmatrix} 2 & 4 \ 4 & 8 \end{bmatrix}. $$
  • Batch 2: $[5, 10]$ and $[7, 14]$ ($n_B = 2$). Its mean is $\mu_B = [6, 12]$, and its local deviations are again $[-1, -2]$ and $[1, 2]$, so $S_B = \begin{bmatrix} 2 & 4 \ 4 & 8 \end{bmatrix}$.
  • Merge: $n = 4$, and $\delta = \mu_B - \mu_A = [4, 8]$. The merged mean is $\mu = [2, 4] + \frac{2}{4}[4, 8] = [4, 8]$, and the cross-mean rank-one correction carries weight $\frac{n_A n_B}{n} = \frac{2 \times 2}{4} = 1$: $$ S = \begin{bmatrix} 2 & 4 \ 4 & 8 \end{bmatrix}
    • \begin{bmatrix} 2 & 4 \ 4 & 8 \end{bmatrix}
    • 1 \cdot \begin{bmatrix} 16 & 32 \ 32 & 64 \end{bmatrix} = \begin{bmatrix} 20 & 40 \ 40 & 80 \end{bmatrix}. $$

Check all four rows $[1, 2], [3, 6], [5, 10], [7, 14]$ directly around $[4, 8]$: deviations are $[-3, -6], [-1, -2], [1, 2], [3, 6]$, whose squares sum to $9 + 1 + 1 + 9 = 20$ in column 0 and $36 + 4 + 4 + 36 = 80$ in column 1. They match to the last bit.

flowchart LR
    accTitle: Chan-Golub-LeVeque incremental scatter merge and finalization
    accDescr: Dense batches compute 256-row chunked centered GEMM scatters while sparse CSR batches compute Neumaier-compensated column sums and Gram products without densification. Both feed sk_merge_moments into SKCovarianceAccumulator holding samples_seen, mean and d by d scatter. Finalization divides scatter by n minus 1, runs symmetric eigh, sorts eigenvalues descending and orients components to produce SKIncrementalPCAModel.
    classDef dense fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef sparse fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef state fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef final fill:#f0fdf4,stroke:#16a34a,color:#14532d

    D["Dense batch<br/>256-row centered GEMM"]:::dense --> M["sk_merge_moments<br/>Chan-Golub-LeVeque"]:::state
    S["CSR sparse batch<br/>Neumaier Gram - n mu mu^T"]:::sparse --> M
    M --> A["SKCovarianceAccumulator<br/>(n, mean, scatter d x d)"]:::state
    A -->|"scatter / (n - 1) + eigh"| F["sk_finalize_accumulator<br/>sort + sign orient"]:::final
    F --> P["SKIncrementalPCAModel<br/>components, variance,partial_fit"]:::final

Sparse CSR batches without densification (and Neumaier compensation)

In a Compressed Sparse Row (CsMatView) batch, most entries are implicit zeros. Subtracting $\mu_B$ from every entry would destroy sparsity. Instead, sk_update_sparse in sparse.rs visits only stored non-zeros along each row: for every pair of stored entries $(j, v_j)$ and $(l, v_l)$ in the same row, it accumulates column sums $\sum v_j$ and the uncentered Gram product $G_B = X_B^{\top} X_B$, then applies the identity

$$ S_B = X_B^{\top} X_B - n_B,\mu_B \mu_B^{\top} $$

before handing $(n_B, \mu_B, S_B)$ to sk_merge_moments.

Because subtracting $n_B \mu_B \mu_B^{\top}$ from $X_B^{\top} X_B$ can amplify rounding error when a feature has a large offset (for instance values near $100.0 \pm 0.5$), sk_update_sparse uses Neumaier compensated addition (sk_neumaier_add): alongside every running sum $s$, a companion error term $c$ captures the low-order bits lost when adding a small number to a large one (or vice versa), folding $c$ back in before computing $\mu_B$ and $S_B$. After every merge, sk_symmetrized averages $\frac{1}{2}(S + S^{\top})$ and clamps diagonal entries at $0$ so tiny floating-point asymmetries never disturb the symmetric eigensolver.

Finalization, sign orientation, and whitening

Given $(n, \mu, S)$, sk_finalize_accumulator in finalize.rs:

  1. Forms $C = S / (n - 1)$ when $n \ge 2$ (or the zero matrix when $n = 1$), and sums $\sigma_{\text{total}}^2 = \sum_{j=1}^{d} \max(C_{j,j}, 0)$ along the diagonal;
  2. Calls backend.eigh(C) on the configured SKMathBackend<F>, sorts eigenvalues $\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_k \ge 0$ (breaking ties by ascending feature index), and extracts the top $k$ eigenvectors as rows of $W \in \mathbb{R}^{k \times d}$;
  3. Passes $W$ through sk_orient_components (shared with SKPCA), ensuring $W W^{\top} = I_k$ and making each row’s largest-magnitude coordinate non-negative so SKIncrementalPCA and SKPCA agree in sign as well as subspace;
  4. Derives singular values $\sigma_c = \sqrt{\lambda_c (n - 1)}$, explained_variance_ratio, and whitening scales $s_c = \sqrt{\max(\lambda_c, \varepsilon)}$.

4. Each public object, explained

flowchart TD
    accTitle: Fitting modes and model lifecycle in SKIncrementalPCA
    accDescr: SKIncrementalPCABuilder builds an immutable SKIncrementalPCA estimator. From SKIncrementalPCA, fit chunks an in-memory dense or CSR view into batch_size blocks, fit_transform fits and projects under one span, and fit_streaming drives one-shot or reopenable SKSourceProvider streams across epochs. All produce SKIncrementalPCAModel, which supports chained partial_fit updates, transform, inverse_transform, and SKExportable/SKImportable state persistence.
    classDef builder fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef est fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef stream fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef model fill:#f0fdf4,stroke:#16a34a,color:#14532d

    B["SKIncrementalPCABuilder&lt;F&gt;<br/>batch_size=1024, epochs=1, Faer"]:::builder -->|build| E["SKIncrementalPCA&lt;F&gt;<br/>immutable config (Copy)"]:::est
    E -->|"fit / fit_transform"| C["Row chunker<br/>sk_chunk_ranges"]:::stream
    E -->|"fit_streaming(provider)"| P["Prefetch executor<br/>1 pass or reopenable epochs"]:::stream
    C --> M["SKIncrementalPCAModel&lt;F&gt;<br/>accumulator + W + variance"]:::model
    P --> M
    M -->|"partial_fit(batch)"| M
    M -->|"transform / inverse_transform"| T["Dense or CSR views<br/>zero densification"]:::builder
    M <-->|"export_state / import_state"| X["SKModelState&lt;F&gt;"]:::stream

SKIncrementalPCABuilder<F> and SKIncrementalPCA<F>

What they are — the mandatory builder (incremental_pca/builder.rs) and immutable, Copy estimator (incremental_pca/core_implementation.rs). Direct struct construction is private; SKIncrementalPCA::<F>::build() opens the builder.

Documented defaults and setters:

  • number_of_components(usize) — None by default (resolving to $\min(n, d)$, i.e. all $d$ features whenever $n \ge d$); must be $> 0$ when set;
  • batch_size(usize) — 1024 by default; must be $> 0$ and at least number_of_components;
  • whiten(bool) — false by default;
  • maximum_number_of_epochs(usize) — 1 by default; must be $> 0$; controls how many passes fit_streaming requests from a reopenable SKSourceProvider;
  • backend(SKBackendKind) — SKBackendKind::Faer by default;
  • execution_mode(...) — SKExecutionMode::Automatic by default (inherent and via SKBuilder).

Entry points on SKIncrementalPCA<F> (for F: SKBackendSelection):

  • fit(features) (SKUnsupervisedFit<F>) — validates shape, finiteness and batch_size >= resolved_components, partitions rows via sk_chunk_ranges (merging any short tail block into its predecessor so every chunk has at least $k$ rows), updates the accumulator and finalizes under a Fit span;
  • fit_transform(features) — fits and projects under a single FitTransform span;
  • fit_streaming(provider) — drives SKSourceProvider<F> through sk_run_streaming_provider with SKStreamingPassPolicy::Iterative { maximum_number_of_passes: maximum_number_of_epochs }. A one-shot provider (&mut source) consumes one pass (emitting a tracing::warn! if more epochs were requested); an SKReopenableSource reopens the stream once per epoch and records the count in model.epochs_consumed().

SKIncrementalPCAModel<F>

What it is — the fitted model (incremental_pca/model.rs), Clone + Debug + Send + Sync, carrying both the finalized eigendecomposition and the live SKCovarianceAccumulator<F>.

Accessors and operations:

  • components() ($k \times d$), explained_variance(), explained_variance_ratio(), singular_values(), mean(), scatter_matrix() ($d \times d$);
  • samples_seen(), epochs_consumed(), number_of_components(), number_of_features(), batch_size(), whiten(), backend(), execution_mode();
  • partial_fit(batch) — validates non-empty input, matching feature count (ShapeMismatch), rows >= number_of_components (InvalidHyperparameter), CSR format and finiteness before mutating state, merges the batch under a PartialFit span, refreshes the finalized components, and returns Result<&mut Self, SKError> for chaining;
  • transform(features) (inherent and SKFeatureTransformer<F>) and inverse_transform(projected) — operate on dense and CSR views without densifying sparse matrices, making SKIncrementalPCA<F> compose directly inside SKPipeline and SKFeatureUnion;
  • SKExportable<F> and SKImportable<F> (incremental_pca/export/) — round-trip the full model and accumulator state through SKModelState<F>.

Also note workspace integration: adding fit_streaming and partial_fit registers SKIncrementalPCA in crates/sciencekit_pipeline/src/streaming_coverage/matrix.rs, verified automatically by the_source_scan_matches_the_audited_streaming_surface.


5. Walking through the real companion tests

Every requirement in openspec/changes/incremental-pca/specs/incremental-pca/spec.md is backed by companion tests under crates/sciencekit_decomposition/src/:

  1. Defaults, builder validation and clean state (incremental_accumulator_tests.rs, incremental_builder_tests.rs). incremental_configuration_and_accumulator_start_clean verifies zeroed accumulator arrays and default configuration constants. incremental_builder_carries_documented_defaults, incremental_builder_overrides_every_option_and_trait_execution_mode, and incremental_builder_rejects_zero_components_batch_size_and_epochs lock the builder surface.
  2. Chan-Golub-LeVeque merge and sparse CSR Gram parity (incremental_merge_tests.rs, incremental_sparse_tests.rs). incremental_merge_hand_checked_two_batch_mean_and_scatter verifies the exact $[4, 8]$ mean and $[[20, 40], [40, 80]]$ scatter on the two-batch hand calculation above. incremental_merge_two_batches_equal_one_batch_and_persist_state proves two-batch and six-row-chunked updates match a single pass. incremental_sparse_matches_dense_across_batches_without_densification and incremental_sparse_mixed_with_dense_batches_matches_single_dense_pass verify CSR and alternating CSR/dense batches against shifted features ($100.0 + \dots$) where uncompensated sums would lose precision.
  3. Finalization and equality with SKPCA (incremental_finalize_tests.rs, incremental_fit_tests.rs). incremental_finalize_sorted_components_and_equals_full_pca checks non-increasing explained_variance, orthonormal rows ($W W^{\top} = I_k$), and agreement with SKPCASolver::Full on components, singular values, variances and ratios. incremental_fit_chunks_dense_and_sparse_and_matches_pca exercises trailing-chunk coalescing ($50$ rows with batch_size = 12 and $k = 3$), while incremental_fit_partial_fit_chains_and_records_backend_spans chains dense and CSR partial_fit calls and asserts sciencekit.operation spans record "matrixmultiply" on both fit and partial_fit.
  4. One-pass and multi-epoch streaming (incremental_streaming_tests.rs). incremental_streaming_one_shot_provider_consumes_one_pass_and_matches_fit passes a one-shot source with maximum_number_of_epochs(4), confirming epochs_consumed() == 1, a clamp warning event, and parity with fit. incremental_streaming_reopenable_multi_epoch_reopens_and_preserves_subspace wraps a factory in SKReopenableSource with maximum_number_of_epochs(3), proving the factory opens $3$ times (epochs_consumed() == 3, samples_seen() == 108) while preserving the exact subspace. incremental_streaming_sparse_and_mixed_batches_match_dense_fit streams alternating CSR and dense SKDataBatch blocks.
  5. Projection, whitening and validation (incremental_transform_tests.rs, incremental_validation_tests.rs, incremental_validation_inputs_tests.rs). incremental_transform_shape_roundtrip_and_sparse_dense_parity verifies $(19, 3)$ shapes, fit_transform parity, and full-rank $k = d$ inverse_transform reconstruction within $10^{-9}$ on both dense and CSR coordinates. incremental_transform_whitening_normalizes_unit_variance_and_inverts checks unit sample variance across whitened columns and invertible reconstruction. incremental_validation_rejects_empty_inputs_everywhere, incremental_validation_rejects_excessive_components_and_small_batches, and incremental_validation_rejects_feature_mismatch_non_finite_and_csc verify every error variant and prove failed partial_fit calls leave samples_seen() and mean() untouched.
  6. Thread-count bit-identity, batch-size invariance, export and metrics (incremental_concurrency_tests.rs, acceptance_tests/). incremental_concurrency_repeated_fits_and_thread_counts_are_bit_identical fits an $8,192 \times 32$ matrix under 1-thread and 4-thread rayon pools and asserts exact assert_eq! equality on mean, scatter_matrix, components, transform and inverse_transform. incremental_concurrency_batch_size_invariance_holds_for_dense_and_sparse sweeps batch_size across $7, 19, 32, 64$ against $1,024$. incremental_concurrency_shared_model_transforms_match_sequential shares an Arc<SKIncrementalPCAModel<f64>> across $6$ threads. Finally, acceptance_incremental_pca_tiny_f32_large_dense_and_wide_sparse and acceptance_incremental_pca_streaming_epochs_export_concurrency_and_metrics exercise f32, $3,000 \times 24$ dense and $1,200 \times 160$ wide CSR inputs, export_state / import_state round-tripping followed by continued partial_fit, and monotonic sk_mean_squared_error / $R^2 > 0.9999$ (sk_r2_score) via sciencekit_metrics.

6. Recap

  • SKIncrementalPCA<F> learns exact sample covariance out-of-core in $\mathcal{O}(d^2)$ memory by merging per-batch $(n_B, \mu_B, S_B)$ summaries with the Chan-Golub-LeVeque formula and discarding every batch immediately.
  • Dense batches reduce 256-row blocks via BLAS GEMM; sparse CSR batches accumulate Neumaier-compensated column sums and Gram products without ever densifying sparse storage.
  • fit, chained SKIncrementalPCAModel::partial_fit, and fit_streaming over one-shot or reopenable SKSourceProvider streams all converge on the same sorted, sign-oriented principal components as SKPCA, with bit-identical results across thread counts.

Mini-batch k-means: learning rates, reassignment and honest streaming

Classic k-means — the Lloyd and Elkan algorithm from the k-means chapter — has a comfortable but expensive habit: it wants the whole training table in memory and re-reads every row once per iteration. That is fine for a 100 000-row matrix that fits in RAM, and hopeless for a log file that arrives batch by batch from disk, a network socket or a database cursor. Mini-batch k-means keeps the same center matrix and the same nearest-center prediction contract, but improves each center from small batches instead of a full pass, so it can learn from data it never holds at once.

This chapter builds SKMiniBatchKMeans<F> and SKMiniBatchKMeansModel<F> in crates/sciencekit_cluster/src/minibatch_kmeans/ (capability mini-batch-k-means). No prior knowledge of Rust, linear algebra or streaming systems is assumed.


1. The problem, in plain words

Given a table $X$ with $n$ rows and $p$ numeric columns and a requested number of clusters $k$, we want $k$ center vectors so that every row is close to at least one center. The prediction surface is exactly the k-means one: a row belongs to the cluster of its nearest center, and the model never invents a “noise” label. What changes is the fitting surface:

  1. Bounded memory. Training data may be larger than RAM, so fitting must consume one batch at a time and keep only the centers and a few counters.
  2. Incremental continuation. A user may have a first day of data today and a second day tomorrow; partial_fit must continue from the exact centers and per-center counts instead of restarting.
  3. Streaming, not just chunking. The same algorithm must drive the shared SKSourceProvider executor, including reopenable providers that can be read for several epochs.
  4. Sparse data must stay sparse. A wide one-hot table can have millions of columns and a handful of stored values per row. Materializing it densely would waste gigabytes and break the workspace’s representation-parity rule (spec data-view-boundary).
  5. Determinism. Parallel row assignment must not make repeated runs or different rayon thread counts disagree.

2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Per-center learning rate 1 / (count[c] + 1)New centers should move a lot; mature centers should barely move. Dividing by the number of rows already assigned to that center gives exactly that decay.A global fixed learning rate (destroys mature centers) or a schedule based on wall-clock batches (not reproducible).
Exact closed-form batch updateApplying the row rule sequentially over a batch reduces algebraically to $c \leftarrow \frac{n}{n+m}c + \frac{1}{n+m}\sum x$ with $n$ the prior count and $m$ the batch count. This lets a CSR batch touch only its stored entries — $O(kd + \operatorname{nnz})$ instead of densifying $m \times d$.A row-by-row for loop over dense materialized rows: simpler, but densifies sparse input and is far slower.
Deterministic bounded initialization sampleCenters start from at most initialization_batch_size rows, drawn without replacement from a seeded generator and sorted, then number_of_initializations independent seeds compete on sample inertia.Initializing from the first batch_size rows (positional bias), or random restarts without a seed (irreproducible).
Deterministic low-count reassignmentA center that receives almost no rows is a dead center. After each batch, centers below $\text{reassignment_ratio} \times \text{mean_count}$ steal the batch point currently farthest from its assigned center, with ties broken by the smallest row index, and reset the stolen center’s count to 1.Re-running k-means++ on the whole dataset whenever a center is empty (expensive, not streaming-friendly).
Reuse the shared streaming executorfit_streaming calls sk_run_streaming_provider with a mutable driver, so prefetching, parallelism and the reopenable-provider pass policy are the same code other estimators use.A bespoke while let Some(batch) loop that would duplicate executor behavior and diverge from other streaming estimators.
tolerance = 0 means “use the full budget”Users often want a predictable number of passes. A positive tolerance enables early stopping when the largest center shift (and reassignment activity) is at or below it; zero explicitly disables the stop.Treating zero as “stop immediately” (surprising) or as exact convergence (float equality is unattainable).

3. The concepts, from zero

Centers, counts and one update step

A center is just a vector — the current guess for the middle of a cluster. counts[c] records how many rows have ever been assigned to center c. When a row $x$ is assigned to center $c$:

$$ c \leftarrow c + \frac{x - c}{\text{count}[c] + 1}, \qquad \text{count}[c] \leftarrow \text{count}[c] + 1 . $$

The first row moves the center halfway to itself; after a hundred rows the center moves only $1/101$ of the gap. This is what makes mini-batch fitting stable: early batches shape the centers, later batches refine them.

flowchart LR
    accTitle: One mini-batch update pipeline
    accDescr: A batch is validated, every row is assigned in parallel to its nearest center, centers are updated from the closed form, low-count centers are deterministically reassigned, and the convergence flag is computed.
    B["Validated batch<br/>(dense or CSR)"] --> A["Parallel nearest-center<br/>assignment + distances"]
    A --> U["Per-center closed-form update<br/>c ← n/(n+m)·c + 1/(n+m)·Σx<br/>counts += batch counts"]
    U --> R{"Any count < ratio · mean_count?"}
    R -->|"yes"| S["Move farthest batch row<br/>to the low-count center<br/>reset count to 1"]
    R -->|"no"| C["Check tolerance<br/>max center shift ≤ tol"]
    S --> C
    C --> D["batches_processed += 1<br/>converged flag"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef amber fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef rose fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#7f1d1d
    class B,A sky
    class U,R amber
    class S rose
    class C,D emerald

Why the closed form is exact

Start from count $n$ and a batch of $m$ rows all assigned to the same center. Applying the single-row rule $m$ times gives:

$$ c_{\text{new}} = \left(\frac{n}{n+m}\right)c_{\text{old}}

  • \left(\frac{1}{n+m}\right)\sum_{i=1}^{m} x_i , \qquad \text{count}_{\text{new}} = n + m . $$

The code in update.rs implements exactly these two lines: it accumulates per-center batch sums, scales the old center by prior / total, adds sum / total, and increments the count. For dense input it uses azip! over rows; for CSR it scales the dense center row and then adds only the stored (column, value) entries. No to_dense() call exists on the sparse path.

Sparse distance without densification

For a CSR row, the squared distance to a center is computed by the norm expansion

$$ \lVert x - c \rVert^2 = \lVert x \rVert^2 + \lVert c \rVert^2 - 2,x \cdot c , $$

where the dot product only iterates the stored entries of the row. Center norms are computed once per assignment call. The result is clamped at zero to absorb floating-point round-off.

Initialization on a bounded, seeded sample

sk_sample_initialization_indices draws initialization_batch_size row indices without replacement from a seeded SKRandomGenerator, then sorts them for a stable traversal. If the dataset is already smaller than the bound, every row is used. The sampled rows are gathered — densely into a new matrix, or as a new small CSR matrix without densification — and the KMeans initializer runs there. sk_run_initializations runs the requested number of trials and keeps the one whose sample inertia (sum of squared distances to assigned centers) is smallest.

Reassignment: keeping every center alive

After a batch has been folded into the centers, the estimator computes the mean count over all clusters. A center with $\text{count} < \text{reassignment_ratio} \times \text{mean_count}$ is starving. The estimator ranks every batch row once by squared distance to its currently assigned center, sorted by distance descending and then row index ascending. It then pairs the starving centers, in ascending cluster index, with the most distant rows in that ranking: the first starving center receives the farthest row, the second the next farthest, and so on, so every starving center gets a distinct row. The chosen row is copied into the center and that center’s count is reset to 1. Because the ranking and the pairing order are both total, the same batches and seed always choose the same rows.

Streaming and epochs

fit_streaming does not read the provider directly. It builds a small driver holding an Option<SKMiniBatchState<F>> and hands it to sk_run_streaming_provider with the Iterative pass policy and maximum_number_of_epochs. The first batch initializes the state; every later batch is validated against the fitted feature width and folded in. Returning SKStreamDecision::Stop from the driver stops the pass. A non-reopenable SKLazySource can only be consumed once, so it naturally yields one epoch; an SKReopenableSource is reopened for each pass, and epochs_consumed reflects how many were actually read.

sequenceDiagram
    accTitle: One-shot versus reopenable streaming
    accDescr: The estimator builds a streaming plan, the executor opens the provider, the first batch initializes centers, later batches update them, and reopenable providers repeat the pass until the epoch budget or convergence.
    participant E as SKMiniBatchKMeans
    participant X as Shared streaming executor
    participant P as SKSourceProvider
    participant D as Stream driver/state
    E->>X: plan + Iterative(max epochs)
    loop each epoch allowed by the policy
        X->>P: open source (reopenable returns a fresh source)
        loop each batch
            P-->>X: SKDataBatch (dense or CSR)
            X->>D: process_batch
            alt first batch ever
                D->>D: validate, bounded initialization, first update
            else later batch
                D->>D: validate width, apply batch update, reassign
            end
            D-->>X: Continue or Stop (tolerance met)
        end
    end
    X-->>E: epochs consumed

4. The public objects

SKMiniBatchKMeans<F>

Built only through SKMiniBatchKMeans::build(), which returns SKMiniBatchKMeansBuilder<F>. Every setter returns the builder, build() validates and returns the configured estimator, and Default mirrors new(). The defaults are part of the spec: eight clusters, k-means++, three initializations, batches of 1024, an initialization bound of 3 × batch_size, 100 in-memory iterations, one streaming epoch, tolerance 0, reassignment ratio 0.01, seed 0, Faer backend and Automatic execution mode.

Accessors expose the configured values (number_of_clusters, initialization, number_of_initializations, batch_size, initialization_batch_size, maximum_number_of_iterations, maximum_number_of_epochs, tolerance, reassignment_ratio, random_seed, backend, execution_mode).

Fitting methods:

  • fit implements SKUnsupervisedFit<F>: validates the input, initializes on the bounded sample, walks the data in batch_size chunks for up to maximum_number_of_iterations passes, and returns the model with typed training labels and exact full-data inertia.
  • fit_batch initializes from one batch and performs one update, returning a model that can be continued with partial_fit. This is the streaming-equals-incremental bridge used by the tests.
  • fit_predict fits and returns the typed training assignments.
  • fit_streaming consumes an SKSourceProvider<F> and returns the model with labels() == None, because the training rows are no longer available.

Every public operation records the configured backend and execution mode in its SKOperationAttributes span: Fit for fit and fit_streaming, PartialFit for fit_batch, partial_fit and each streamed batch, FitPredict for fit_predict, Predict for prediction and Transform for distances.

SKMiniBatchKMeansModel<F>

The fitted model stores dense centers, per-center counts, optional typed labels, inertia, batches_processed, epochs_consumed, converged and the original configuration. Its accessors are cluster_centers, counts, labels, inertia, batches_processed, epochs_consumed, converged, number_of_clusters, number_of_features, backend and execution_mode.

It implements:

  • SKClustererPredictor<F>::predict_clusters (and the inherent predict) — nearest-center typed assignments, dense or CSR, never SKClusterLabel::Noise;
  • transform — an (rows, clusters) matrix of Euclidean distances;
  • partial_fit — continues from the exact centers, counts, batch counter and convergence flag, clearing stale training labels because they no longer describe the updated centers;
  • SKExportable<F> / SKImportable<F> — format-agnostic SKModelState emission with the SKMiniBatchKMeans estimator name and schema version 1.

5. Walking through the companion tests

The tests live beside the implementation and are declared from the dispatcher mod.rs.

  • minibatch_update_tests.rs
    • minibatch_update_one_center_closed_form_moves_to_batch_mean_and_sets_count checks the hand-computable case: with one center and a batch assigned entirely to it, the center becomes the batch mean and the count grows by the batch size.
    • minibatch_update_learning_rate_decays_as_one_over_n_plus_one starts with a nonzero count and verifies the exact 1/(n+1) weight.
    • minibatch_update_sequential_single_rows_equal_batch_update_and_sparse_batch proves the closed form equals repeated single-row updates and that the CSR path matches the dense path.
  • minibatch_reassign_tests.rs
    • minibatch_reassign_moves_distant_outlier_to_low_count_center_and_resets_count places a starving center far away and checks that the farthest batch row is copied and the count is reset to 1.
    • minibatch_reassign_breaks_ties_by_smallest_row_index_on_dense_and_sparse builds an exact distance tie and asserts the smallest row index wins in both representations.
    • minibatch_reassign_skips_centers_at_or_above_threshold_and_zero_ratio pins the strict < comparison and the explicit zero-ratio opt-out.
  • minibatch_init_tests.rs
    • minibatch_init_respects_initialization_batch_size_bound_on_dense_and_sparse verifies the bound and the non-densifying sparse gather.
    • minibatch_init_selects_lowest_inertia_across_multiple_initializations checks best-of-n selection.
  • minibatch_state_tests.rs
    • minibatch_state_initializes_zero_counts_and_builds_model_accessors pins the default configuration, the zero-count fresh state and every model accessor.
  • minibatch_partial_tests.rs
    • minibatch_partial_persists_centers_counts_and_batches_across_chained_calls proves that counts and batch counters accumulate across calls and labels are cleared.
    • minibatch_partial_batched_updates_agree_with_full_fit_on_concatenated_data compares repeated partial_fit with fit on the concatenated data within the documented tolerance, including cluster-permutation-insensitive assignments.
  • minibatch_representation_tests.rs
    • minibatch_representation_csr_fit_equals_dense_fit_centers_counts_and_labels, ..._mixed_dense_and_csr_partial_fit_matches_uniform_paths, ..._rejects_csc_sparse_view_up_front and ..._wide_csr_fits_without_densifying_batch cover four-way dense/CSR equivalence, the explicit CSC rejection with guidance, and a million-column sparse design.
  • minibatch_streaming_tests.rs
    • minibatch_streaming_one_shot_provider_consumes_single_pass_and_matches_partial_fit shows a one-shot source is consumed once and equals fit_batch + partial_fit.
    • minibatch_streaming_reopenable_provider_runs_multiple_epochs_and_sparse_batches counts provider opens and checks epochs_consumed and cumulative counts over sparse batches.
    • minibatch_streaming_positive_tolerance_stops_early_and_zero_tolerance_runs_full_budget pins the convergence contract.
  • minibatch_model_tests.rs covers accessors, nearest-center prediction and Euclidean transform, f32/f64 scalar independence, and export/import round-trips.
  • minibatch_builder_tests.rs locks the documented defaults and every rejected hyperparameter, including zero clusters, an undersized initialization sample, non-finite tolerance and an out-of-range reassignment ratio.
  • minibatch_validation_tests.rs checks empty inputs across every operation, small batches, non-finite values (dense and sparse positions), feature-width mismatches, and that a failed partial_fit leaves the existing model untouched.
  • minibatch_determinism_tests/ checks bit-identical repeated fits and streams, invariance between one and four rayon threads, and concurrent prediction equality, plus Send + Sync.
  • acceptance_tests/minibatch_*_tests.rs compare against full SKKMeans, run a 50 000-row one-shot and two-epoch reopenable stream, check a wide sparse design never densifies, and feed the typed labels to sciencekit_metrics (sk_adjusted_rand_score, sk_v_measure_score, sk_silhouette_score, SKSilhouetteScorer).

6. What is deliberately out of scope

Elkan triangle-inequality pruning on streaming batches, missing values, GPU acceleration, memmap2-backed sources and file/ONNX-style export are explicit non-goals of the minibatch-kmeans-streaming change (recorded in docs/PRD.md). Format-agnostic SKModelState export/import is still provided so pipelines can persist the fitted centers; concrete file formats are delivered by their own changes.

The next natural step is automatic selection between full SKKMeans and SKMiniBatchKMeans when a pipeline knows the dataset size, without changing the model contract.

Runtime DAG pipelines: topological fitting, deterministic levels and honest merges

Chapter 24 built SKPipeline, a linear conveyor belt checked by the compiler, and chapter 43 added SKFeatureUnion, a fan-out that stitches parallel branches side by side. Both are composed before any data arrives: the Rust type of the builder records exactly which stages exist. Real feature engineering, however, is rarely a straight line. One input may feed a numeric branch and a categorical branch, a third branch may derive a missingness mask from the raw columns, two of those branches may merge, and the merged result may feed yet another transformer before the estimator. That shape is a directed acyclic graph (DAG) and its structure is often only known at runtime — after reading a configuration file, a UI canvas or a remote experiment definition.

This chapter tells the story of sciencekit_pipeline::graph (capability pipeline-graph): the validated runtime DAG, its mandatory builder, the deterministic topological scheduler, the edge-order merge policy, the node-attributed error surface and the two typed prediction wrappers. It is the first composition layer in sciencekit whose shape is a runtime value while every stage keeps flowing through the same SKFeatureBlock medium built in chapter 19.


1. The problem, in plain words

Think of a factory floor. A linear pipeline is one conveyor belt: each station hands its output to the next. A feature union is a single fan-out station that bolts several sub-assemblies onto the same item at once. A DAG is the whole floor plan: stations can feed several successors, several stations can feed one successor, and the only rule is that material never flows in a circle.

Written down, a DAG is a set of nodes $V$ and directed edges $E \subseteq V \times V$ with no cycle. If an edge points from $u$ to $v$, then $u$ must finish before $v$ starts. A schedule that respects every edge is a topological order. Any DAG has at least one, and when it has several, we must pick one deterministically — otherwise fitting the same definition twice would produce different floating-point results and the whole reproducibility story of the library would collapse.

Three more hazards are specific to this domain:

  1. A missing or duplicated sink. If no node is a supervised estimator, there is nothing to fit. If two are, which one is the model? A validated DAG must end in exactly one final estimator.
  2. Orphan nodes. A node that no input can reach, or that cannot reach the final estimator, is dead weight. It would silently never influence the model, or worse, never be fitted at all.
  3. Ambiguous merge order. When two branches merge, the column order of the concatenated block decides which weight multiplies which feature. Rust’s petgraph stores adjacency in a way that does not preserve insertion order, so “just iterate the neighbours” gives an order that is neither the user’s nor stable across versions.

And one hazard that Rust can eliminate entirely: scalar mixing. Two stages fitted on f32 and f64 cannot exchange a block without a lossy conversion, so the graph must be generic over exactly one SKFloat.


2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Runtime DAG in a new graph folder module, separate from SKPipelineA runtime shape cannot be expressed by the compiler-checked types of chapter 24, and pretending otherwise would force type-level lists for arbitrary graphs. Keeping the two layers side by side lets users choose the stronger compile-time guarantee for linear work and the flexible runtime one for dynamic definitions.Extending SKPipeline with a runtime stage list (mixes two very different error surfaces); generating Rust code from the graph (out of scope).
petgraph::DiGraph as the storageCycle detection, toposort and neighbour queries are already implemented and audited; petgraph is a small, widely used workspace dependency.Hand-rolled adjacency lists (subtle bugs in cycle reporting); a per-node Vec<Box<dyn ...>> with linear scans.
Mandatory builder; direct constructors privateFollows the repository-wide builder rule. Only build() can return a SKPipelineGraph, and only after validation, so every value of the type is guaranteed acyclic, single-sink and fully connected.A public struct with public fields (invalid graphs become representable).
Validation returns SKError::InvalidHyperparameterThe common error taxonomy already covers user-supplied invalid configuration, and callers can match it without learning a new variant for structural mistakes.A dedicated SKGraphError enum (extra surface for no extra information).
Deterministic level order: group by topological level, then ascending node idLevels are the natural parallelisable frontier and also give a stable reading order; the node id is a total order assigned by insertion. Two structurally identical graphs therefore schedule identically even when edges were inserted in a different order.petgraph’s raw toposort order (depends on internal adjacency layout); node-id-only sorting (ignores dependencies).
Merge order = exact connect(source, target) insertion orderThe user’s connect calls are the only declaration of intent we have, so the concatenation must follow them literally. The insertion index is stored as the edge weight.petgraph neighbour iteration (reverse-insertion and unstable); ascending node id (surprising when a branch is declared later).
One SKFloat per graph, enforced at compile timeA graph with mixed scalars is not merely invalid, it is unrepresentable: add_transformer and friends require Stage: SKBlockTransformer<F> where F is the builder’s scalar. A compile_fail doctest on add_transformer pins this guarantee.A runtime scalar check (the impossible state would remain representable and would need an error variant).
Node-attributed errors via SKPipelineGraphNodeError, alongside plain SKError methodsEvery fallible operation exists twice: fit/fit_checked, predict/predict_checked, and so on. The checked variants name the failing node and keep structured variants (ShapeMismatch, UnsupportedRepresentation) intact for pattern matching.Prefixing every message inside SKError (loses the structured variant); only returning SKError (no node context).
Type-erased final model (SKBoxedFinalModel) with typed downcastThe graph must store one of three supervision flavours behind one type, but callers still want the concrete model back. The box keeps an Arc<dyn Any + Send + Sync> plus an erased predictor façade; downcast_reference::<Model>() recovers the concrete type.Making SKPipelineGraph generic over the final estimator type (leaks the estimator type into every accessor and defeats runtime graphs).
Dense, CSR and mixed blocks throughout; no implicit densificationThe layer sits on top of SKFeatureBlock, so the merge simply reuses the CSR-preserving concatenation written for SKFeatureUnion.Densifying before concatenation (memory blow-up on wide sparse branches).

3. The concepts, taught from zero

Nodes, edges and the feature-block medium

A graph node stores a payload — a boxed transformer, a boxed SKFeatureUnion, a Merge marker or a boxed final estimator. The payload is generic over the scalar F that the whole graph shares. Data never lives in the payload: during fitting, each node’s output block is written into an SKNodeBlockStore<F>, a BTreeMap<SKNodeIdentifier, SKFeatureBlock<F>> kept sorted so iteration and equality checks are deterministic.

flowchart LR
    accTitle: Node payloads and the shared feature-block medium of a runtime DAG
    accDescr: A validated SKPipelineGraph holds four kinds of node payload. Transformers and feature unions fit on their incoming block and emit a new block. A merge node concatenates its incoming blocks. The single final estimator node fits a supervised model on the block it receives. Every edge carries a feature block at execution time, resolved from the node block store.
    IN["Input rows<br/>SKDataView"] --> R["Transformer root<br/>SKPipelineGraphNodeKind::Transformer"]
    R --> T1["Transformer<br/>branch A"]
    R --> T2["FeatureUnion<br/>branch B"]
    T1 --> M["Merge<br/>column concatenation"]
    T2 --> M
    M --> T3["Transformer<br/>post-merge"]
    T3 --> F["FinalEstimator<br/>SKBoxedFinalModel"]
    F --> OUT["Labels / probabilities / responses"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef violet fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    class IN,OUT sky
    class R,T1,T2,T3 emerald
    class M violet
    class F amber

Validation: three structural promises

build() calls sk_validate_graph, which performs the promises the spec names:

  1. Every edge endpoint exists. connect refuses to insert an edge whose endpoints are not yet nodes; the offending pair is remembered and reported as InvalidHyperparameter.
  2. No cycles. petgraph::algo::toposort detects them, and a depth-first search then reconstructs one concrete cycle path so the error reads pipeline graph contains a cycle: node 1 -> node 2 -> node 1 instead of a bare “cycle”.
  3. Exactly one final estimator, and it is a sink. Zero or several final estimators, or a final estimator with outgoing edges, are rejected with InvalidHyperparameter naming the node(s).
  4. Full reachability. Every node must be reachable from some input root and must reach the final estimator. Both directions are checked with a breadth-first search, so neither orphaned islands nor dead-end branches survive.

Deterministic levels

sk_topological_level_order starts from petgraph’s toposort and then assigns each node a level: an input root is level 0, and every other node is 1 + max(level of its predecessors). Nodes are finally sorted by (level, node identifier). Two consequences matter:

  • nodes at the same level are independent by construction, so their relative order is a policy choice — ours is ascending identifier;
  • the resulting vector is a total, reproducible schedule, and topological_order() exposes it.
flowchart TB
    accTitle: Level-ordered scheduling of a diamond graph
    accDescr: Node zero is the root at level zero. Nodes one and two are two same-level branches at level one and execute in ascending identifier order. Node three merges them at level two and node four is the final estimator at level three. Sorting by level and then by node identifier yields the deterministic schedule 0, 1, 2, 3, 4 regardless of the order in which the edges were connected.
    L0["Level 0<br/>node 0 · root"] --> L1a["Level 1<br/>node 1 · branch A"]
    L0 --> L1b["Level 1<br/>node 2 · branch B"]
    L1a --> L2["Level 2<br/>node 3 · merge"]
    L1b --> L2
    L2 --> L3["Level 3<br/>node 4 · final estimator"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef violet fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    class L0 sky
    class L1a,L1b emerald
    class L2 violet
    class L3 amber

Edge-order merges

Each connect(source, target) stores a monotonically increasing insertion counter as the edge weight. When a node has several incoming edges, sk_ordered_predecessors sorts them by that counter and sk_resolve_incoming_block applies a three-way policy:

  • zero incoming edges (a root): the caller’s input block is the node’s input;
  • one incoming edge: that predecessor’s block is passed through unchanged — no copy, no densification;
  • several incoming edges: the blocks are concatenated horizontally in exact connect order.

The concatenation itself is the CSR-preserving routine from chapter 43, promoted from pub(super) to pub(crate) so both composition layers share one implementation. All-dense inputs stay dense; if any input is sparse CSR the result is CSR, and no sparse block is ever densified.

flowchart LR
    accTitle: Three-way incoming-block policy for a graph node
    accDescr: A node with no incoming edges receives the caller input block. A node with one incoming edge receives its predecessor's stored block unchanged. A node with several incoming edges receives their blocks concatenated horizontally in exact connect insertion order, promoting the result to CSR when any branch is sparse.
    N["Target node"] --> Q{"Incoming<br/>edge count"}
    Q -->|0| R0["Caller input block"]
    Q -->|1| R1["Predecessor block<br/>unchanged"]
    Q -->|many| R2["Concatenate in<br/>connect order"]
    R2 --> C{"Any sparse<br/>CSR branch?"}
    C -->|no| D["Dense block"]
    C -->|yes| S["CSR block<br/>no densification"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef violet fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    class N,Q amber
    class R0,R1 emerald
    class R2,D,S violet

Widths are re-checked at prediction time

During fit, the width of every incoming branch is recorded in incoming_widths. During predict, sk_resolve_incoming_block receives those recorded widths: a single-predecessor node must still receive exactly the width it was fitted on, and a multi-predecessor merge must still produce the same per-branch widths it concatenated during fitting. A drift is reported as a node-attributed ShapeMismatch. Node outputs are also validated for representation (dense or CSR only, never CSC) and for row count after every stage.


4. The public surface, object by object

SKPipelineGraphBuilder<F> and SKPipelineGraph<F>

SKPipelineGraph::start::<F>() (and the equivalent SKPipelineGraph::build() on a scalar-annotated path) opens the builder. It exposes four node constructors — add_transformer, add_feature_union, add_merge, add_classifier / add_regressor / add_final_estimator — each returning an opaque SKNodeIdentifier whose index() is its zero-based insertion position. connect(source, target) returns &mut Self so chains read naturally. The builder also carries the mandatory backend (default SKBackendKind::Faer) and execution_mode (default SKExecutionMode::Automatic) parameters, and implements the shared SKBuilder trait. build() validates and freezes the topology into an SKPipelineGraph, which exposes node_count, edge_count, topological_order, final_node, node_kind, incoming_nodes, backend and execution_mode.

SKPipelineGraph::fit / fit_checked and SKPipelineGraphModel<F>

fit converts the input into an SKFeatureBlock, then walks the topological order once. For each node it resolves the incoming block, opens a pipeline_graph_node tracing span carrying the node identifier, kind and operation, and dispatches on the payload: transformers and unions fit and then transform; merges validate and store; the final estimator fits and produces an SKBoxedFinalModel. The fitted SKPipelineGraphModel keeps the fitted stages, the recorded incoming widths, the per-node blocks and the final model, and exposes accessors for all of them (fitted_node_blocks, fitted_node_block, incoming_widths, number_of_input_features, number_of_features, final_model). SKPipelineGraphClassifier and SKPipelineGraphRegressor wrap the model to implement the shared SKClassifierPredictor / SKRegressorPredictor contracts, so a DAG can be dropped wherever a classifier or regressor is expected.

SKPipelineGraphNodeError and SKBoxedFinalModel<F>

The checked methods return SKPipelineGraphNodeError, which pairs an Option<SKNodeIdentifier> with the underlying SKError. into_sk_error() prefixes dynamic-message variants with pipeline graph node N: while leaving structured variants matchable; to_string() reads the same way. SKBoxedFinalModel keeps the concrete fitted model inside an Arc<dyn Any + Send + Sync> and stores a type-erased predictor façade for classifiers, regressors, or supervised-only models; is_classifier, is_regressor and downcast_reference::<Model>() let callers inspect or recover it.


5. Walking the real companion tests

Every claim above is pinned by a named test. The suite lives beside the implementation, in crates/sciencekit_pipeline/src/graph/*_tests.rs, plus three acceptance files under crates/sciencekit_pipeline/src/acceptance_tests/pipeline_graph_*.rs.

Construction and configuration — graph_builder_tests.rs. graph_builder_assigns_monotonic_node_identifiers_and_records_edges checks that identifiers are 0, 1, 2, 3 in insertion order, that Display renders node 0, that node_kind reports the right SKPipelineGraphNodeKind, and that node_count/edge_count match. graph_builder_carries_backend_and_execution_mode_overrides proves the builder starts at Faer / Automatic and records explicit overrides.

Validation — graph_validate_tests.rs. cyclic_graphs_are_rejected_with_invalid_hyperparameter_naming_the_cycle builds a two-node cycle and a self-loop and asserts the reason names the nodes involved. zero_or_two_final_estimators_are_rejected_with_invalid_hyperparameter covers both cardinality failures. disconnected_and_dead_end_nodes_are_rejected_with_invalid_hyperparameter covers an island that no input reaches and a branch that never reaches the sink. final_estimator_with_outgoing_edge_and_foreign_node_id_are_rejected checks the sink rule and the out-of-range edge endpoint. valid_diamond_graph_passes_validation is the happy path.

Scheduling — graph_order_tests.rs. topological_order_respects_dependencies_when_nodes_are_inserted_reverse inserts the sink first and proves the schedule still respects dependencies and ascending identifiers. same_level_nodes_execute_in_ascending_node_identifier_order_independent_of_edge_insertion builds the same three-branch graph twice with opposite connect order and asserts identical orders [0, 1, 2, 3, 4]. per_node_block_store_keeps_blocks_sorted_by_node_identifier checks the BTreeMap ordering of SKNodeBlockStore.

Fitting — graph_fit_tests.rs. diamond_graph_fits_both_branches_and_matches_equivalent_linear_chain fits a diamond (imputer → standard scaler / min-max scaler → classifier) and compares predictions node by node with SKPipeline + SKFeatureUnion. regressor_diamond_graph_learns_identical_weights_to_linear_feature_union_chain goes further and compares the fitted coefficients and intercept to 1e-12.

Merges — graph_merge_tests.rs. explicit_merge_node_concatenates_columns_in_exact_edge_insertion_order connects branches three, ten and twenty into the merge in the order [node 2, node 0, node 1] and asserts the first merged row is [30.0, 10.0, 20.0, 20.0] — insertion order, not identifier order. merge_node_feeding_downstream_transformer_and_mismatch_attribution_work places a transformer after the merge and checks that a row-count mismatch is attributed to the right node.

Prediction — graph_predict_tests.rs. classifier_wrapper_predictions_and_probabilities_match_linear_equivalent_on_unseen_rows and regressor_wrapper_predictions_match_linear_equivalent_on_unseen_rows exercise the typed wrappers on held-out rows. wrapper_role_mismatch_and_query_width_mismatch_surface_structured_errors proves that calling predict_labels on a regressor graph, or predicting with the wrong number of input columns, returns structured errors rather than panics.

Representation — graph_representation_tests.rs. sparse_csr_diamond_flows_without_implicit_densification_and_matches_dense_predictions fits the same diamond on CSR and on dense input, asserts sparse nodes stay sparse via SKFeatureBlock::is_sparse, and compares predictions. representation_rejection_surfaces_failing_node_identifier_and_representation_name feeds CSR to a dense-only scaler during fit and during predict, and a custom CscEmittingStage produces a CSC output, asserting that each error names its node and the representation string.

Determinism and concurrency — graph_concurrency_tests.rs. graph_definitions_and_fitted_models_are_send_and_sync is a compile-time assertion. repeated_fits_produce_identical_node_blocks_and_predictions_and_accessors_cover_every_node fits twice and compares every node block, the topological order and the predictions, while checking that the order covers each node exactly once. concurrent_prediction_and_refitting_across_threads_match_sequential_results shares one fitted graph across eight scoped threads and compares every concurrent label, probability and response with the sequential result, including a refit per thread.

Acceptance — acceptance_tests/pipeline_graph_*.rs. On small data, tiny_diamond_graphs_match_linear_equivalents_across_f64_and_f32_and_produce_metrics covers both scalars and produces accuracy, MSE and $R^2$; tiny_sparse_and_mixed_graphs_preserve_csr_without_densification_and_attribute_rejections covers mixed representations; doomed_graph_fixtures_and_single_edge_width_drift_surface_structured_errors covers structural failures and a deliberate width drift. On large data, large_multi_level_dense_dags_fit_predict_and_produce_classifier_and_regressor_metrics builds a multi-level DAG and scores it, large_sparse_csr_dag_fits_without_densification_and_produces_metrics keeps CSR end to end, and large_dag_concurrent_predictions_and_refits_match_sequential_results repeats the concurrency guarantee at scale.


6. What this layer deliberately does not do

  • No persistence of the graph definition itself. The fitted model is a Rust value; exporting it belongs to the model-export changes, not to the scheduler.
  • No parallel execution of same-level nodes. The level order is ready to drive a parallel scheduler, but this change executes deterministically and sequentially; threading is a later, separately measured optimisation.
  • No runtime scalar polymorphism. One graph is one SKFloat; mixing scalars is a compile error, not a validation error.
  • No fit-time densification shortcuts. A branch that cannot accept CSR fails with a node-attributed UnsupportedRepresentation instead of being silently converted.

The next chapter in this book keeps the story going with the composition layers that build on this scheduler; when a new graph feature lands, amend this chapter rather than adding a parallel one.

Successive halving: spend the budget where it pays

Grid search is honest but greedy. It spends the full dataset on every candidate, including the ones that are obviously bad after a handful of rows. Successive halving flips the budget around: evaluate everybody cheaply first, keep the promising fraction, and only then pay for more data.

This chapter builds SKHalvingGridSearchClassifier and SKHalvingGridSearchRegressor: the round scheduler, the seeded resource subsample, the deterministic elimination trace, the aggressive mode, the refit, and the result surface a caller inspects afterwards.

The capability is halving-grid-search; the code lives in crates/sciencekit_model_selection/src/halving/.

1. The problem, in plain words

You have nine candidate configurations. Grid search fits all nine on every fold of the full training set. But if a candidate is clearly worse after thirty rows, the remaining nine hundred rows you spend on it are wasted. Successive halving:

  1. evaluates all nine candidates on a small resource (say ten rows);
  2. ranks them by their cross-validated mean score;
  3. keeps the best ceil(n / factor) — with factor 3, the best three;
  4. multiplies the resource by the factor (ten → thirty);
  5. repeats until one candidate remains or the maximum resource is reached;
  6. optionally refits the winner on all the rows.

Every step has a trap. If each round drew a different random subset with no seed, two runs would rank differently. If ties broke arbitrarily, the trace would not be reproducible. If a small round used a different fold partition than the next, the comparison would mix “better candidate” with “luckier split”. And if the final refit reused the tiny last subsample instead of the whole dataset, the deployed model would be trained on almost nothing.

flowchart TD
    accTitle: Successive halving tournament
    accDescr: Nine candidates are evaluated on ten rows, the best three survive, those three are evaluated on thirty rows, the best one survives, and the winner is refitted on all rows. The elimination trace records every round.
    A["9 candidates<br/>configured estimators"] --> R0["Round 0<br/>resource = 10 rows<br/>3-fold CV"]
    R0 --> K0["keep best ceil(9/3) = 3"]
    K0 --> R1["Round 1<br/>resource = 30 rows<br/>3-fold CV"]
    R1 --> K1["keep best ceil(3/3) = 1"]
    K1 --> F{"refit?"}
    F -->|"yes"| M["winner refitted<br/>on ALL rows"]
    F -->|"no"| N["trace only<br/>prediction disabled"]
    M --> T["elimination trace<br/>9 → 3 → 1"]
    N --> T
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef round fill:#fae8ff,stroke:#a21caf,stroke-width:2px,color:#581c87
    classDef keep fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#166534
    classDef result fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    class A input
    class R0,R1 round
    class K0,K1 keep
    class F,M,N,T result

2. The decisions, and the roads not taken

  1. Rounds are driven by a resource schedule, not by a hard-coded count. The schedule is the geometric sequence minimum_resource * factor^round, clipped to maximum_resource. With a minimum of 10 and a factor of 3 it is 10, 30, 90, …; the loop stops early as soon as only one candidate survives. There is no “number of rounds” knob to get wrong.
  2. The resource is a row budget, and it is a closed enum. SKHalvingResource currently has exactly one variant, NumberOfSamples (the default). Making it an enum rather than a boolean keeps the door open for future resource axes (trees, epochs) without a breaking API change.
  3. Every round draws its own subsample from one seed. The round seed is derived from the configured random_seed and the round index, so round 0 and round 1 never share rows by accident, but rerunning the same search reproduces every draw exactly.
  4. Stratification follows the splitter, not the caller. If the splitter answers requires_stratification() == true (as SKStratifiedKFold does), the subsample preserves class proportions. Group labels, when supplied, are preserved proportionally instead.
  5. The folds are the grid-search folds. Each round reuses the shared sk_evaluate_candidates machinery, so candidates are compared on the same fold partition within a round. Only the rows change between rounds — which is the whole point.
  6. Elimination is deterministic. Candidates are ranked by descending mean score; an exact tie goes to the smaller original candidate index, and NaN ranks below every finite score. The same seed and data therefore produce a byte-identical trace.
  7. Aggressive elimination is opt-in. By default the survivor count is exactly ceil(n / factor); a short resource schedule may therefore end with several survivors. aggressive_elimination(true) prunes down to what the remaining rounds can actually support, so the tournament ends with a single winner.
  8. Refit is explicit. With refit(true) the winner is fitted on all rows and the result exposes prediction; with refit(false) the trace and the winning configuration are still available, but prediction and export return UnsupportedOperation.

Roads not taken. Random or Bayesian search (a different change), resource types such as number of trees or epochs (not yet modelled), re-splitting the folds after subsampling with a different random partition (would break the shared-fold comparison), and refitting at every round (wasted work — only the final winner is deployed).

3. The concepts, taught from zero

Resources and rounds

A resource is how much training data a round is allowed to use. A round is one full cross-validation sweep of the still-alive candidates at one resource. The sequence of resources is computed before the loop starts, by sk_halving_resource_schedule(minimum_resource, maximum_resource, factor). It uses checked_mul and stops at the cap, so a huge factor or a nearly-usize::MAX resource cannot overflow; an invalid schedule (minimum_resource == 0, minimum_resource > maximum_resource, or factor < 2) simply returns an empty vector and the search fails cleanly.

The candidate trajectory is computed by the sibling function sk_halving_candidate_schedule(number_of_candidates, factor): it repeatedly applies ceiling division until one survivor remains. Nine candidates with factor 3 give 9 → 3 → 1; ten give 10 → 4 → 2 → 1, because ceil(10/3) = 4. The real loop does not call this function — it stops when the alive list has one element — but the function is the executable statement of the schedule the spec promises.

Ceiling division, from zero

Integer division truncates: 10 / 3 = 3. Successive halving must not over-eliminate, so it rounds up: ceil(10/3) = 4. Rust spells this 10_usize.div_ceil(3). The one-survivor case is special: ceil(1/3) = 1, but the loop must stop, so the schedule function only continues while current > 1.

Seeded subsampling

To evaluate on exactly resource rows, the search shuffles row indices with a deterministic generator and truncates. The seed is derived, not reused:

round_seed = sk_derive_seed(random_seed, SK_RANDOM_DOMAIN_STAGE, round_index)

SK_RANDOM_DOMAIN_STAGE keeps this draw in its own random stream, so adding a future consumer of the same base seed cannot change the halving trace. When the resource is already the whole dataset, the search returns 0..total_rows in order — no shuffle, no allocation of a different ordering.

Stratified and grouped subsampling share a proportional allocator. Class (or group) sizes are allocated with sk_allocate_class_counts, then each class or group is shuffled with its own derived seed (SK_RANDOM_DOMAIN_FOLD plus the group position) and truncated; the union is shuffled once more. A 70/30 binary target subsampled to 30 rows therefore contains exactly 21 and 9 rows, as the tests assert for both integer and nominal labels.

The score matrix, reused

sk_evaluate_candidates returns the same SKGridSearchResults<F> that grid search uses: a candidates × folds matrix with per-candidate means and population standard deviations. A halving round wraps that matrix together with its bookkeeping — round number, resource, evaluated indices, survivors, eliminated indices, aggressively pruned indices — in SKHalvingRound<F>.

Ranking, ties and NaN

sk_rank_candidate_indices sorts positions by sk_compare_scores(right, left), so a larger mean comes first. When means compare equal, the original candidate index decides, not the position in this round’s evaluated list. That last detail matters: in round 1 the surviving candidates are no longer stored in their original order, and the trace must still prefer candidate 3 over candidate 8 if they tie. NaN compares below every finite score, so a candidate that failed under SKErrorScore::Value(NaN) can never win.

Aggressive elimination, precisely

A standard round keeps ceil(alive / factor) candidates regardless of how much budget is left. If the resource schedule has only two rounds, a tournament that starts with 27 candidates will still have 3 survivors after the last round — no single winner. Aggressive mode caps the survivor count at what the remaining rounds can reduce to one:

$$\begin{aligned} \text{future_rounds} &= \text{number_of_resources_from_here_to_the_cap} - 1 \ \text{capacity} &= \text{factor}^{\text{future_rounds}} && (\text{checked, saturating}) \ \text{survivors} &= \min(\lceil \text{alive} / \text{factor} \rceil, \text{capacity}) \end{aligned}$$

With 27 candidates, factor 3, and the schedule $[10, 30]$, $\text{future_rounds} = 1$, so capacity is 3: round 0 keeps three candidates, prunes the other six early, and round 1 finishes with one. The pruned six are still named in aggressively_pruned_candidate_indices() — pruning is recorded, never hidden.

4. Each public object, explained

  • SKHalvingGridSearchClassifier<F, E> / SKHalvingGridSearchRegressor<F, E> — the search estimators. Construction goes only through SKHalvingGridSearchClassifierBuilder / SKHalvingGridSearchRegressorBuilder, reached with SKHalvingGridSearchClassifier::build(). The builders expose candidates, splitter, scoring, factor, minimum_resource, maximum_resource, resource, aggressive_elimination, random_seed, refit, error_score, groups, backend and execution_mode. Defaults: factor 3, minimum resource 1, maximum resource = all rows, NumberOfSamples, no aggressive elimination, seed 0, refit true, SKErrorScore::Raise, backend Faer, execution mode Automatic.
  • SKHalvingGridSearchClassifierModel<F, E> / SKHalvingGridSearchRegressorModel<F, E> — the fitted result. It exposes elimination_trace(), number_of_rounds(), candidate_count_trajectory(), resource_schedule(), best_candidate_index(), best_score(), best_parameters() (the winning configured candidate), best_model(), is_refitted(), scoring(), execution_mode() and backend(). The classifier additionally delegates predict_labels / predict_probabilities; the regressor delegates predict.
  • SKHalvingRound<F> — the immutable record of one round: round(), resource(), evaluated_candidate_indices(), surviving_candidate_indices(), eliminated_candidate_indices(), aggressively_pruned_candidate_indices(), ranked_candidate_indices(), mean_scores(), standard_deviations(), fold_scores() and the underlying results().
  • SKHalvingResource — the closed, #[non_exhaustive] resource axis; NumberOfSamples is the default and the only variant today.
  • SKHalvingScoring — the family-safe scoring wrapper. The builders accept either a SKClassifierScoring or a SKRegressorScoring through Into<SKHalvingScoring>; the wrong family fails at construction with InvalidHyperparameter instead of mis-scoring at fit time.
  • sk_halving_resource_schedule / sk_halving_candidate_schedule — the free functions that make the schedule visible and testable without fitting anything.
  • SKExportable — implemented by both fitted models by delegating export_state() to the refitted winner; without refit it returns UnsupportedOperation naming the refit(false) configuration.

5. A real walk-through, using the tests

halving_scheduler_tests.rs — the schedule, by hand

halving_scheduler_nine_candidates_shrink_nine_three_one pins the spec’s headline sequence. halving_scheduler_non_multiple_candidate_counts_use_ceiling_division proves 10 → 4 → 2 → 1 and that a single candidate stays [1]. halving_scheduler_resource_grows_geometrically_up_to_maximum checks 10, 30, 90 and 10, 30, 90, 270. The boundary test — halving_scheduler_handles_overflow_and_boundary_resources_cleanly — exercises a resource equal to the cap, a near-usize::MAX minimum, and every invalid schedule (zero minimum, inverted bounds, factor 1), which must all return an empty vector rather than panic or loop.

halving_trace_tests.rs — deterministic elimination

halving_trace_ranks_by_descending_mean_and_breaks_ties_by_original_index ranks [7, 2, 5, 1, 4] with means [0.80, 0.80, NaN, 0.95, 0.80] and expects [1, 2, 4, 7, 5]: candidate 1 wins on score, 2 and 4 tie and beat 7 by original index, and candidate 5 (NaN) sinks to last even though its index is smaller than 7. halving_trace_splits_survivors_and_eliminated_candidates_cleanly builds a six-candidate, two-fold matrix and checks every accessor of SKHalvingRound at once. halving_trace_tie_in_later_round_still_prefers_smaller_original_index is the subtle one: it feeds the round a list [8, 3] and equal scores, and asserts candidate 3 survives — proving the tie-break uses the original index, not the position in the current round.

halving_subsample_tests.rs — seeded, stratified, sparse-aware

halving_subsample_draws_exact_resource_count_and_is_reproducible_per_seed_and_round draws 30 of 100 rows four ways: the same seed and round must be identical, a different round must differ, and a different base seed must differ. halving_subsample_stratified_preserves_class_proportions_for_integer_and_nominal_targets uses a 70/30 target and asserts exactly 21 and 9 rows, for integer labels and for string labels. halving_subsample_preserves_sparse_csr_representation_and_groups subsamples a CSR matrix and checks the result is still SKDataView::Sparse with the same nonzero payload as sk_gather_rows, and that three equal groups each receive five of the fifteen rows. halving_subsample_full_budget_returns_all_rows_and_stratified_splitter_signals_requirement pins the no-op case — all rows, original order — and confirms that SKStratifiedKFold, unlike SKKFold, reports requires_stratification() == true.

halving_evaluation_tests.rs — the loop itself

halving_evaluation_runs_nine_three_one_and_selects_true_target_constant uses nine mock regressors and ninety rows: round 0 at resource 10 evaluates all nine and keeps three; round 1 at resource 30 evaluates three and keeps one; the winner is the candidate whose constant equals the target. halving_evaluation_stops_at_maximum_resource_and_picks_highest_mean_with_tie_break stops at the cap with two survivors and resolves a tie to the smaller index. The error-policy test, halving_evaluation_respects_raise_and_value_error_score_policies, shows Raise propagating the mock’s failure and Value(NaN) letting the healthy candidate win. Finally, halving_evaluation_single_candidate_still_evaluates_one_round proves a one-candidate search does not return an empty trace.

halving_aggressive_tests.rs — pruning what the budget cannot support

halving_aggressive_prunes_candidates_early_when_budget_cannot_support_survivors runs 27 candidates against a two-round schedule with and without aggressive mode: the standard run keeps nine survivors after round 0 and finishes with three, while the aggressive run keeps three, records six aggressively pruned candidates, and finishes with one. halving_aggressive_is_a_no_op_when_budget_supports_all_rounds_and_breaks_ties_deterministically shows that a one-round schedule prunes extra candidates (9 → 1) while a full [10, 30, 90] schedule prunes nothing extra and still resolves ties by index.

halving_refit_tests.rs — the winner, refitted on everything

halving_refit_classifier_trains_winner_on_all_rows_and_delegates_predictions fits a threshold classifier over nine candidates, checks candidate_count_trajectory() == [9, 3, 1], resource_schedule() == [18, 54], the winning threshold, and — crucially — training_rows() == 90, proving the final fit used the whole dataset rather than the last 54-row round. It also checks that backend(MatrixMultiply) and execution_mode(InProcessSynchronous) survive into the model, and that labels and probabilities are delegated to the winner. The regressor twin, halving_refit_regressor_trains_winner_on_all_rows_and_delegates_predict, repeats the story with 27 candidates, three rounds [10, 30, 90], trajectory [27, 9, 3, 1], and a refit on all 100 rows.

halving_concurrency_tests.rs and halving_representation_tests.rs

halving_concurrency_no_refit_blocks_regressor_and_classifier_predictions proves that refit(false) yields best_model().is_none() and that predict, predict_labels and predict_probabilities all return UnsupportedOperation naming the operation. halving_concurrency_parallel_fits_and_thread_pools_produce_identical_traces fits the same search under a one-thread and a four-thread rayon pool and demands identical traces, then shares one model across eight threads and compares predictions. Representation parity lives in halving_concurrency_representation_dense_sparse_and_mixed_match_without_densification, which fits dense and CSR designs and asserts identical traces, cross-representation prediction, and — with a sparse-only mock — that neither subsampling nor the final refit densified the CSR. halving_concurrency_rejects_non_finite_rows_even_outside_sampled_budget is the validation guard: a NaN in row 39 of 40 is rejected even though the configured resource only samples six rows.

builder/ and validation_tests.rs

halving_builder_* pins the defaults, rejects factor < 2, invalid resource bounds, empty candidates, a missing splitter and a scorer from the wrong family — including an explicit check that every optional setter and the SKBuilder trait dispatch are honoured. halving_acceptance_rejects_empty_mismatched_non_finite_and_oversized_resource_inputs covers the fit-time guards: empty data, target-length mismatch, dense and sparse non-finite values, a maximum_resource larger than the dataset, and a minimum_resource above the effective cap.

The acceptance suite

acceptance_tests/halving/ is the executable contract at the public surface. halving_acceptance_tiny_classifier_and_regressor_select_refitted_and_exportable_winners covers small data, export metadata and the no-refit export error; the f32 companion, halving_acceptance_f32_scalar_pipeline_runs_without_f64_detour, proves scalar genericity. halving_acceptance_large_classifier_runs_multi_round_schedule_and_refits_full_dataset runs 1,080 rows, checks [40, 120, 360] and [27, 9, 3, 1], and verifies every fold score is finite. halving_acceptance_large_regressor_supports_factor_two_three_and_four_schedules pins the schedules for factors 2, 3 and 4; and halving_acceptance_thirty_row_resource_evaluates_exact_thirty_rows_across_every_fold instruments the estimator to prove all nine fold evaluations saw exactly 30 rows. halving_acceptance_kfold_and_imbalanced_stratified_kfold_preserve_fold_contracts, halving_acceptance_group_kfold_respects_groups_and_rejects_invalid_group_configurations and halving_acceptance_aggressive_mode_prunes_early_on_public_estimator_surface exercise the splitters, groups and aggressive mode through the builders. The scoring-policy sweep halving_acceptance_every_classifier_and_regressor_scoring_policy_produces_finite_traces visits every SKClassifierScoring and SKRegressorScoring variant, while halving_acceptance_determinism_error_score_and_held_out_metrics_compose ties the whole story together: a seeded train/test split, a deterministic halving search, ErrorScore::Value(NaN) recovery, and held-out accuracy, F1, MSE and $R^2$ produced by sciencekit_metrics.

6. Why this shape scales

The total work is dominated by the first round, not the last. Nine candidates at resource 10 cost 90 candidate-rows; three candidates at resource 30 cost another 90; one candidate at resource 90 costs 90. A full grid search would have spent $9 \times 90 = 810$ candidate-rows. The saving is roughly a factor of the elimination ratio per round, and it compounds on large grids — exactly the regime where exhaustive search stops being practical.

The price is statistical: an early round sees fewer rows, so its ranking is noisier. That is why the seed, the stratification and the deterministic tie-break all matter, and why the trace is exposed rather than hidden. You can inspect every round, see which candidates were eliminated and which were aggressively pruned, and decide whether the budget was too small.

7. Recap

  • Successive halving evaluates all candidates cheaply, keeps ceil(n / factor), grows the resource geometrically, and repeats until one survivor or the cap.
  • The resource and candidate schedules are pure functions; the loop is a thin driver over the shared grid-search evaluator.
  • Subsamples are seeded per round, stratified when the splitter requires it, group-aware when groups are supplied, and never densify a sparse design.
  • Ranking is descending by mean, ties by original candidate index, NaN last.
  • Aggressive elimination prunes to what the remaining rounds can support and records what it pruned.
  • Refit trains the winner on all rows; without it, prediction and export are rejected, not silently wrong.

Extended Safetensors format: safe binary checkpoints, sharding, in-place padding and compression

1. The problem we were solving

A fitted machine-learning model is more than code: it is the learned numbers (weights, split thresholds, centroids, feature masks) plus the identity and configuration that give those numbers meaning (which estimator wrote them, how many features it expects, what class labels map to indices $0, 1, \dots, K-1$, and which hyperparameters were active).

Historically, Python libraries reached for pickle to save fitted models. pickle is a stack-based virtual machine: loading an untrusted file can execute arbitrary code before a single prediction runs. On the other end of the spectrum, the human-readable JSON debug format (Chapter 45) is completely safe and great for git diff, but converting millions of 64-bit floating-point numbers into UTF-8 decimal text inflates file sizes and forces full-document parsing before you can inspect one tensor.

HuggingFace’s Safetensors format solves the core binary problem cleanly: a file begins with an 8-byte little-endian integer $H$, followed by $H$ bytes of UTF-8 JSON describing each tensor’s data type, shape and byte offsets, followed immediately by a flat contiguous buffer of raw little-endian tensor bytes. No executable opcodes exist anywhere in the specification.

For sciencekit’s internal checkpoint format (PRD §8.2, spec safetensors-format), plain single-file Safetensors needed four careful extensions — without breaking standard Safetensors readers on the single-file path:

  1. Rich estimator metadata in the standard "__metadata__" string map: container format version, estimator name and version, scalar data type, feature count, canonical class labels and typed hyperparameters.
  2. Sharding (SKShardPlan) for large models: splitting tensors across immutable .safetensors shard files paired with an atomically updated .safetensors.index.json manifest that the reader merges transparently.
  3. Header and payload padding for small incremental additions (such as attaching an out-of-bag score or a low-rank adapter): reserving slack in both the JSON header and a __padding__ byte region so new tensors can be written in place by seeking, without rewriting existing tensor payloads — and automatically spilling into a new shard the moment reserved space runs out.
  4. Whole-file compression (.safetensors.gz, .safetensors.brotli, .snappy.safetensors) behind optional Cargo features, detected automatically from magic bytes on read.

2. The architecture in one picture

flowchart LR
    accTitle: Extended Safetensors export, sharding, padding, compression and validated import pipeline
    accDescr: An SKExportable model produces an SKModelState, which SKSafetensorsWriter encodes into standard Safetensors bytes with optional header and payload padding, splits across immutable shards with an atomic index when SKShardPlan is exceeded, and optionally wraps in Gzip, Brotli or Snappy. SKSafetensorsReader auto-detects magic bytes to decompress, validates duplicate keys, version, shapes and contiguous offsets, merges any shards, excludes padding, and rebuilds SKModelState for SKImportable.

    M1["Fitted model<br/>SKExportable"]:::violet --> S1["SKModelState<br/>metadata + BTreeMap"]:::blue
    S1 --> W["SKSafetensorsWriter<br/>shard_plan · padding · codec"]:::green
    W -->|"single / padded"| F1[".safetensors<br/>8B len + JSON + LE bytes"]:::amber
    W -->|"exceeds threshold<br/>or padding overflows"| F2["Immutable shards +<br/>atomic .index.json"]:::amber
    W -->|"optional feature"| F3[".gz · .brotli · .snappy<br/>magic-byte wrapper"]:::orange
    F1 --> R["SKSafetensorsReader<br/>magic detect + wire check"]:::teal
    F2 --> R
    F3 --> R
    R -->|"valid v1"| S2["SKModelState<br/>exact round-trip"]:::blue
    R -->|"corrupt / missing feature"| E["Structured SKError<br/>no partial model"]:::rose
    S2 --> M2["Reconstructed model<br/>SKImportable"]:::violet

    classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef teal fill:#ccfbf1,stroke:#0d9488,color:#134e4a
    classDef rose fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

Just like the JSON debug adapter, everything lives in crates/sciencekit_interop/src/safetensors/. Estimator crates never depend on safetensors, flate2, brotli or snap; they only speak SKModelState<F> from sciencekit_common.


3. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Standard Safetensors wire encoding on the single-shard pathAny unsharded, uncompressed file written by SKSafetensorsWriter can be opened directly by safetensors::SafeTensors::deserialize in Rust or safetensors.safe_open in Python.Inventing a custom binary header — forfeits ecosystem tooling and HuggingFace interoperability.
Safe little-endian byte conversion (to_le_bytes / chunks_exact + from_le_bytes) under #![deny(unsafe_code)]sciencekit_interop forbids unsafe. Explicit little-endian byte conversion avoids unaligned pointer Undefined Behavior on arbitrary Vec<u8> slices, stays portable on big-endian targets, and compiles down to vectorized moves on little-endian CPUs.std::slice::from_raw_parts pointer casts — requires unsafe, panics or triggers UB on unaligned buffers, and silently writes wrong endianness on big-endian hosts.
Dual-region padding: ASCII space (0x20) header slack + reserved __padding__ U8 payload tensorThe Safetensors specification allows trailing 0x20 bytes in the JSON header, and requires tensor data_offsets to cover the payload buffer contiguously with zero unreferenced trailing bytes. Declaring unused payload capacity as a "__padding__" U8 tensor keeps the file 100% valid to external Safetensors readers while our reader strips "__padding__" automatically.Leaving unreferenced zero bytes after the last tensor — rejected by SafeTensors::deserialize as an incomplete/mismatched metadata buffer.
Sequential shard names (<stem>.shard-00001.<ext>) + atomic temp-and-rename .index.jsonAppending a new shard when padding overflows never renames or mutates existing shard files, and fs::rename ensures concurrent readers never observe a half-written JSON manifest.<stem>-00001-of-00002.safetensors naming — adding a third shard would force renaming every previous shard, violating shard immutability and racing concurrent readers.
Duplicate-preserving serde header visitor before SafeTensors::deserializeStandard HashMap JSON deserialization silently overwrites duplicate keys ("w": ..., "w": ...). A streaming MapAccess visitor catches duplicate tensor and metadata keys deterministically and checks sciencekit.format_version before typing version-1 fields.Relying solely on SafeTensors::read_metadata — collapses shape mismatches and duplicate keys into opaque parse strings or silent overwrites.
Deterministic magic-byte detection (0x1F 0x8B, "βρ", \xff\x06\x00\x00sNaPpY) with explicit UnsupportedOperationSKSafetensorsReader recognizes compressed streams even from in-memory &[u8] slices with no filename, and tells the caller which Cargo feature (compression-gzip, compression-brotli, compression-snappy) to enable when compiled without it.Silent fallback or opaque header-parse errors when reading a compressed file without its codec feature.

4. The concepts, taught from zero

4.1 Numbers in memory vs bytes on disk

If you have never worked with binary file formats before, start with one question: how does a computer store a 64-bit floating-point number like 1.5_f64?

In text (JSON), 1.5 is three ASCII characters: '1' (0x31), '.' (0x2E), '5' (0x35). A number like -0.3333333333333333 takes 19 bytes of text and requires a decimal parser to recover the IEEE-754 bits. In binary IEEE-754 little-endian form, every f64 is always exactly 8 bytes, with the least-significant byte stored at the lowest address. A tensor of $N$ f64 values therefore occupies an exact, predictable $8N$ bytes on disk — no delimiters, no escaping, and $O(1)$ random access to any tensor by slicing payload[begin..end].

sciencekit maps its four SKTensorDataType variants onto standard Safetensors element types with fixed byte widths $w(\text{dtype})$:

SKTensorDataTypeSafetensors dtypeByte width $w$Encoding rule
F32"F32"$4$ bytesIEEE-754 binary32 little-endian (f32::to_le_bytes), finite values required
F64"F64"$8$ bytesIEEE-754 binary64 little-endian (f64::to_le_bytes), finite values required
I64"I64"$8$ bytesTwo’s-complement signed 64-bit little-endian (i64::to_le_bytes)
Bool"BOOL"$1$ byte0x00 for false, 0x01 for true (any byte $> 1$ is rejected as corrupt)

For a tensor of shape $[s_1, s_2, \dots, s_r]$ (where a scalar tensor has empty shape $[]$ and empty product $\prod_{d=1}^{0} s_d = 1$), its [begin, end] slice in data_offsets must satisfy:

$$\text{end} - \text{begin} = w(\text{dtype}) \times \prod_{d=1}^{r} s_d$$

Every multiplication in that check uses usize::checked_mul, so an adversarial header like "shape": [18446744073709551615, 2] cannot wrap around usize::MAX to impersonate a tiny buffer; it is immediately rejected with SKError::ShapeMismatch.

4.2 The metadata header contract

Safetensors reserves a top-level "__metadata__" key in the JSON header whose values must all be strings (Map<String, String>). sciencekit_interop::safetensors stores seven well-known keys inside "__metadata__":

  • "sciencekit.format_version": container major version ("1", exposed as SK_SAFETENSORS_FORMAT_VERSION). Checked first on read; a future major version such as "2" returns SKError::UnsupportedRepresentation with guidance to re-export.
  • "sciencekit.estimator_name": stable estimator identifier (for example, "SKLinearRegression" or "SKLogisticRegression").
  • "sciencekit.estimator_format_version": the estimator’s own SKModelMetadata::format_version() integer as a decimal string (defaulting to 1 when omitted by external writers).
  • "sciencekit.scalar_data_type": "F32" or "F64", checked against the caller’s target Rust scalar F.
  • "sciencekit.feature_count": decimal feature count fitted by the estimator.
  • "sciencekit.class_labels" (classifiers only): JSON array string of canonical class names in index order, e.g. ["setosa","versicolor","virginica"].
  • "sciencekit.parameters": deterministic JSON object string encoding the BTreeMap of SKParameterValue booleans, 64-bit integers, finite floats, strings and nested lists.

Any extra "__metadata__" keys written by third-party tools (such as "format": "pt" or custom provenance tags) are ignored cleanly while preserving all known fields.

4.3 Header padding, in-place seek appends, and shard overflow

Why would you ever modify a checkpoint after writing it? Suppose a model finishes training and writes 200 MiB of tree arrays, and a post-fit step computes a scalar out-of-bag score or attaches a small lora.adapter_a matrix. Rewriting all 200 MiB just to add 32 bytes wastes disk bandwidth.

flowchart TB
    accTitle: Byte layout of a padded Safetensors file during in-place append and shard overflow
    accDescr: Diagram comparing initial padded file layout with 8-byte header size H, JSON header plus 0x20 space slack, existing tensor bytes and __padding__ U8 zero bytes. When a small tensor fits in both header slack and __padding__, seek writes update only the header and the start of the padding region without touching existing tensor bytes. When an addition exceeds remaining padding, the original file stays untouched and a new immutable shard plus atomic .index.json manifest are written.

    subgraph L1["1. Initial padded file (H fixed, 8-byte aligned)"]
        direction LR
        P0["Bytes 0..8<br/>u64 LE = H"]:::violet --> P1["Bytes 8..8+J<br/>JSON header"]:::blue
        P1 --> P2["Bytes 8+J..8+H<br/>0x20 space slack"]:::teal
        P2 --> P3["Payload 0..U<br/>Existing tensors"]:::green
        P3 --> P4["Payload U..U+P<br/>__padding__ (U8)"]:::amber
    end

    subgraph L2["2a. Small append fits (SKAppendOutcome::InPlace)"]
        direction LR
        A0["Bytes 0..8<br/>unchanged H"]:::violet --> A1["Bytes 8..8+H<br/>updated JSON + 0x20"]:::blue
        A1 --> A2["Payload 0..U<br/>UNTOUCHED on disk"]:::green
        A2 --> A3["Payload U..U+B<br/>New tensor sought in"]:::orange
        A3 --> A4["Payload U+B..U+P<br/>shrunk __padding__"]:::amber
    end

    subgraph L3["2b. Large append overflows (SKAppendOutcome::NewShard)"]
        direction LR
        O1["Original .safetensors<br/>100% immutable"]:::green --> O3["model.safetensors.index.json<br/>atomic temp + rename"]:::violet
        O2["model.shard-00001.safetensors<br/>holds overflow tensor"]:::orange --> O3
    end

    L1 -->|"B <= P and J_new <= H"| L2
    L1 -->|"B > P or J_new > H"| L3

    classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef teal fill:#ccfbf1,stroke:#0d9488,color:#134e4a

When SKSafetensorsWriter::builder().padding_bytes(P) writes a file:

  1. The JSON header (length $J$) is padded with trailing ASCII spaces (0x20) to an 8-byte aligned capacity: $$H = \left\lceil \frac{J + P_{\text{header}}}{8} \right\rceil \times 8$$ Because $8 + H$ is fixed from the start, the byte offset where tensor payloads begin never shifts.
  2. At the end of the real tensor payloads $[0, U)$, a reserved tensor named "__padding__" (SK_SAFETENSORS_PADDING_TENSOR_NAME) of dtype "U8" and shape $[P]$ covers $[U, U + P)$, accompanied by "__padding_bytes__": "P" in "__metadata__".
  3. When append_tensor_to_path adds a tensor of $B$ payload bytes, it checks both conditions ($B \le P$ and new JSON length $J_{\text{new}} \le H$). If both hold, it opens the file for read/write without truncation, seeks to byte 8 to overwrite the $H$-byte padded header, and seeks to byte $8 + H + U$ to write the $B$ new tensor bytes — leaving bytes $[8 + H, 8 + H + U)$ completely untouched on disk (SKAppendOutcome::InPlace).
  4. The moment $B > P$ or $J_{\text{new}} > H$, the original file is left byte-for-byte untouched, the new tensor is written to <stem>.shard-00001.safetensors, and <file>.index.json is written via a temporary file + atomic fs::rename (SKAppendOutcome::NewShard). Subsequent reads of <file> automatically notice the companion .index.json and merge every shard!

4.4 Sharding large states from the start

When a single model state already exceeds a desired file-size budget at initial export time, SKShardPlan (configured via .maximum_shard_bytes(threshold)) partitions tensors in deterministic BTreeMap name order into greedy buckets bounded by threshold. Each bucket becomes an immutable <stem>.shard-NNNNN.<ext> Safetensors file carrying the model metadata, and <path>.index.json records format_version, metadata (including "total_size"), the ordered shards array, and the weight_map dictionary mapping every tensor name to its shard filename.

4.5 Whole-file compression and magic bytes

Behind optional Cargo features (compression-gzip, compression-brotli, compression-snappy), SKSafetensorsWriter wraps encoded Safetensors files (and shards) in:

  • Gzip (SKSafetensorsCompression::Gzip, .safetensors.gz, magic 0x1F 0x8B),
  • Brotli (SKSafetensorsCompression::Brotli, .safetensors.brotli, 4-byte "βρ" framing magic 0xCE 0xB2 0xCF 0x81, plus .brotli/.br suffix fallback for raw RFC 7932 streams),
  • Snappy (SKSafetensorsCompression::Snappy, .snappy.safetensors, standard 10-byte framing header \xff\x06\x00\x00sNaPpY).

sk_detect_safetensors_compression(bytes) inspects those leading magic bytes without needing any compression feature compiled in. If a caller reads a compressed file without enabling its matching feature, SKSafetensorsReader immediately returns SKError::UnsupportedOperation naming the exact Cargo feature to enable.


5. Each public object, explained

Everything below is exported from sciencekit_interop::safetensors:

  • SK_SAFETENSORS_FORMAT_VERSION (1) and SK_SAFETENSORS_PADDING_TENSOR_NAME ("__padding__") — container major version and reserved padding tensor identifier.
  • SK_GZIP_MAGIC, SK_BROTLI_MAGIC, SK_SNAPPY_MAGIC and sk_detect_safetensors_compression(&[u8]) — leading magic-byte constants and pure byte-slice compression detector.
  • SKSafetensorsCompression — None (default), Gzip, Brotli, Snappy, exposing .file_extension(), .feature_flag() and SKSafetensorsCompression::from_path(&Path).
  • SKShardPlan & SKShardPlanBuilder (plus SK_DEFAULT_MAXIMUM_SHARD_BYTES = 512 MiB) — builder-only sharding plan exposing .maximum_shard_bytes(...) (rejecting 0), .backend(SKBackendKind) (default Faer), .execution_mode(...) (default Automatic) and .build().
  • SKShardIndex, sk_safetensors_index_path(&Path) and sk_read_safetensors_shard_index(&Path) — validated read-only view of a .safetensors.index.json manifest exposing .format_version(), .metadata(), .shards() and .tensor_to_shard().
  • SKAppendOutcome — InPlace vs NewShard { shard_file }, returned by append operations so callers can observe whether reserved padding absorbed the write.
  • SKSafetensorsWriter & SKSafetensorsWriterBuilder — builder-only writer exposing .shard_plan(...), .maximum_shard_bytes(...), .padding_bytes(...), .header_padding_bytes(...), .payload_padding_bytes(...), .compression(...), .backend(...) and .execution_mode(...). Provides write_state_to_bytes, write_state_to_writer, write_state_to_path, append_tensor_to_path, append_tensors_to_path, export_to_bytes and export_to_path, emitting structured sciencekit.interop.safetensors.write tracing spans.
  • SKSafetensorsReader & SKSafetensorsReaderBuilder — builder-only reader exposing .backend(...) and .execution_mode(...). Provides read_state_from_bytes, read_state_from_reader, read_state_from_path, import_from_bytes and import_from_path, transparently decompressing and merging shards while emitting sciencekit.interop.safetensors.read tracing spans.
  • Convenience functions — sk_write_model_state_safetensors, sk_write_model_state_safetensors_file, sk_read_model_state_safetensors, sk_read_model_state_safetensors_file, sk_export_model_safetensors, sk_export_model_safetensors_file, sk_import_model_safetensors, sk_import_model_safetensors_file and sk_append_safetensors_tensor.
use sciencekit_interop::safetensors::{
    SKAppendOutcome, SKSafetensorsWriter, sk_read_model_state_safetensors_file,
};

let writer = SKSafetensorsWriter::builder()
    .padding_bytes(256)
    .build()?;
writer.export_to_path(&fitted_model, &checkpoint_path)?;

let outcome = writer.append_tensor_to_path(&checkpoint_path, &extra_tensor)?;
assert_eq!(outcome, SKAppendOutcome::InPlace);

let state = sk_read_model_state_safetensors_file::<f64>(&checkpoint_path)?;

6. Validation table: every rejection is structured

Failure conditionReturned SKError
Truncated prefix ($< 8$ bytes), truncated JSON header, truncated tensor payload, inverted/gapped/overlapping data_offsets, or corrupt compressed payloadSKError::Conversion
Missing file or missing referenced shard file on diskSKError::Io (ErrorKind::NotFound)
Shard manifest with an empty shards: [] listSKError::EmptyInput
Newer or incompatible major version (sciencekit.format_version != 1 or index format_version != 1)SKError::UnsupportedRepresentation
Reading or writing .gz / .brotli / .snappy when its Cargo feature is disabledSKError::UnsupportedOperation (names the missing Cargo feature)
Tensor byte slice length $\neq w(\text{dtype}) \prod s_d$, or shape product overflowSKError::ShapeMismatch
NaN or $\pm\infty$ in floating tensor payload or hyperparameterSKError::NonFiniteValue { position }
Duplicate tensor names in JSON header, across shards, or on appendSKError::InvalidHyperparameter { name: "tensor_names", .. }
Unsupported wire dtype ("F16"), invalid BOOL byte ($> 1$), or scalar mismatch (F32 read as f64)SKError::InvalidHyperparameter { name: "tensor_data_type" | "scalar_data_type", .. }
Duplicate shard entries, path-traversal shard names ("../..."), or cross-shard metadata disagreementSKError::InvalidHyperparameter { name: "shards", .. }

7. Walking through the companion tests

The module under crates/sciencekit_interop/src/safetensors/ keeps mod.rs as a pure dispatcher over focused single-responsibility files (header.rs, parameter_codec.rs, tensor_codec.rs, wire_header_deserialization.rs, wire_validation.rs, single_file.rs, shard_plan.rs, shard_index.rs, shard_io.rs, padding_encode.rs, padding_append.rs, compression_types.rs, compression.rs, writer_builder.rs, writer.rs, writer_functions.rs, reader_builder.rs, reader.rs), verified by nine companion test suites:

  • Module & SKBuilder wiring (safetensors_wiring_tests.rs):
    • safetensors_wiring_exposes_format_constants_and_safetensors_dependency verifies SK_SAFETENSORS_FORMAT_VERSION, SK_SAFETENSORS_PADDING_TENSOR_NAME and the SKBuilder trait contract on SKSafetensorsWriterBuilder, SKSafetensorsReaderBuilder and SKShardPlanBuilder.
  • Single-file & metadata round-trips (safetensors_round_trip_tests.rs, safetensors_round_trip_io_tests.rs):
    • safetensors_round_trip_preserves_classifier_metadata_and_all_tensor_dtypes round-trips a multi-class SKLogisticRegression state carrying F64 (2-D and 0-D scalar), I64 and Bool tensors plus nested SKParameterValue::List hyperparameters, and proves safetensors::SafeTensors::deserialize opens the emitted bytes directly.
    • safetensors_round_trip_preserves_single_precision_f32_dtype verifies F32 preservation and custom backend/execution_mode configuration.
    • safetensors_round_trip_ignores_unknown_metadata_fields injects third-party keys into "__metadata__" and confirms known sciencekit.* fields survive untouched.
    • safetensors_round_trip_supports_files_streams_and_exportable_models exercises io::Write/io::Read streams, file paths and SKExportable/SKImportable traits.
  • Wire corruption & offset validation (safetensors_validation_tests.rs):
    • safetensors_validation_rejects_truncated_files, safetensors_validation_rejects_inconsistent_offsets, safetensors_validation_rejects_shape_and_offset_length_mismatch, safetensors_validation_rejects_duplicate_tensor_names_in_header and safetensors_validation_rejects_unsupported_and_mismatched_dtypes forge malformed binary headers (inverted/gapped/overlapping offsets, usize::MAX shape overflow, duplicate "w" keys, "F16" tensors and F32-as-f64 reads) and verify every structured error.
  • Sharding & shard validation (safetensors_shards_tests.rs, safetensors_shards_validation_tests.rs):
    • safetensors_shards_plan_validates_threshold_and_preserves_builder_options, safetensors_shards_large_state_splits_into_immutable_shards_and_merges_identically, safetensors_shards_state_below_threshold_stays_single_file and safetensors_shards_overwriting_sharded_path_with_single_file_clears_stale_index verify threshold splitting, standalone shard validity, lossless merging from both base and .index.json paths, and clean bidirectional transitions when overwriting between sharded and single-file checkpoints.
    • safetensors_shards_rejects_missing_shard_and_empty_shard_manifest, safetensors_shards_rejects_duplicate_shards_duplicate_tensors_and_mismatched_metadata and safetensors_shards_and_single_files_reject_future_major_versions verify missing shard Io(NotFound), EmptyInput, path-traversal rejection, duplicate shard/tensor detection, cross-shard metadata checks and version-2 UnsupportedRepresentation.
  • Header padding & in-place append (safetensors_padding_tests.rs):
    • safetensors_padding_reserves_space_excludes_padding_tensor_and_appends_in_place proves two small adapter tensors append in place without changing file size, shifting the header boundary, or modifying existing payload bytes, while "__padding__" stays hidden from reconstructed states.
    • safetensors_padding_overflow_creates_new_shard_and_updates_index and safetensors_padding_header_slack_overflow_spills_to_shard_cleanly prove exhausting either payload padding or JSON header slack leaves the base file byte-for-byte immutable, spills into sequential shards, updates .index.json atomically, and rejects duplicate tensor names.
  • Compression & magic-byte detection (safetensors_compression_tests.rs, safetensors_compression_detection_tests.rs):
    • safetensors_compression_variants_report_expected_extensions, safetensors_compression_gzip_round_trips_bytes_files_and_shards, safetensors_compression_brotli_round_trips_bytes_and_files and safetensors_compression_snappy_round_trips_bytes_and_files verify compressed size reduction and transparent round-trips across all three codecs.
    • safetensors_compression_detects_magic_bytes_and_path_extensions, safetensors_compression_missing_feature_returns_unsupported_operation_with_guidance and safetensors_compression_corrupt_streams_and_compressed_append_behave_cleanly verify magic-byte identification, explicit feature guidance when disabled, corrupt-stream SKError::Conversion reporting, and shard spill when appending to compressed files.
  • End-to-end acceptance (acceptance_tests/):
    • safetensors_acceptance_tiny_states_round_trip_for_both_scalars, safetensors_acceptance_large_state_sharded_padded_compressed_and_traced and safetensors_acceptance_exported_regressor_reproduces_dense_and_sparse_metrics verify zero-tensor f32/f64 states, 70,000-element ensembles with sk_canonicalize_labels, tracing span recording, and identical dense + CSR predictions with zero MSE drift.
    • safetensors_acceptance_concurrent_reads_agree_for_single_and_sharded_files and safetensors_acceptance_corrupt_and_truncated_inputs_never_panic run eight concurrent reader threads over padded and sharded files and sweep every truncated byte prefix plus NaN and invalid-boolean byte injections without panicking.

OpenTelemetry export: three signals, bounded cardinality and an honest lifecycle

1. The problem we were solving

Back in Chapter 4, sciencekit_common taught every public estimator operation — fit, partial_fit, fit_transform, transform, predict, fit_predict and score — to open a structured tracing span (sciencekit.operation) through sk_run_operation. Each span records its operation, rows, columns, mode, backend, fallback_reason, duration_ms and, when something goes wrong, error.

Emitting spans in library code is only half of production observability. The moment a team deploys a training worker or an online scoring service, five practical questions appear immediately:

  1. Where do logs and metrics go? Operators rarely debug latency spikes from distributed traces alone. They want aggregated p95 latency and error-rate metrics on dashboards, correlated structured logs when a numerical guard or GPU host fallback fires, and traces for slow requests — all tagged with the same service.name, service.version and deployment.environment.name.
  2. How do we keep algorithm crates lightweight? sciencekit_preprocessing or sciencekit_linear_model must never compile tonic, hyper, reqwest or an OpenTelemetry SDK just to center a matrix.
  3. How do we guarantee silence by default? A library that opens background threads or attempts network connections to localhost:4317 when imported into a unit test or CLI script is broken by design.
  4. How do we prevent metric cardinality explosions? In OpenTelemetry and Prometheus, every distinct combination of metric label values allocates a separate time series. Letting arbitrary strings leak into metric labels turns user identifiers into memory leaks.
  5. How does a short-lived batch training job exit without losing its last spans? Batch processors buffer data in memory; without deterministic force_flush and shutdown (plus a Drop safety net), a process that finishes fit and exits main drops the very telemetry that explained the run.

crates/sciencekit_telemetry solves all five problems in a dedicated opt-in sub-crate. Algorithm crates keep calling sk_run_operation from sciencekit_common with zero SDK dependencies; applications that want OpenTelemetry build a validated SKTelemetryConfiguration and call SKTelemetry::init once at startup.


2. The idea in two pictures

Three-signal pipeline architecture

flowchart LR
    accTitle: Three-signal OpenTelemetry export pipeline in sciencekit_telemetry
    accDescr: Library operations emit tracing spans and structured events into SKGlobalTelemetrySubscriber, which fans out to the trace layer with error-status enrichment, the log bridge with trace correlation, and SKTelemetryMetricsLayer with closed-enum labels, exporting via OTLP gRPC, OTLP HTTP or in-memory test exporters.

    OP["sk_run_operation<br/>+ tracing events"]:::violet --> PROXY["SubscriberProxy<br/>blocks transport loops"]:::blue
    PROXY --> TL["Trace layer<br/>+ error status"]:::green
    PROXY --> LL["Log bridge<br/>severity + trace ID"]:::amber
    PROXY --> ML["Metrics layer<br/>closed enum labels"]:::orange
    TL --> EXP["OTLP gRPC :4317<br/>OTLP HTTP :4318<br/>or InMemory"]:::rose
    LL --> EXP
    ML --> EXP

    classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef rose fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

Process-wide lifecycle state machine

flowchart LR
    accTitle: Process-wide SKTelemetry lifecycle state machine
    accDescr: Process starts Uninitialized with zero exporters and zero traffic. SKTelemetry::init claims an atomic once-per-process slot; invalid config or missing transport feature releases the slot, whereas success enters Active state supporting bounded force_flush and idempotent shutdown or Drop detachment.

    IDLE["Uninitialized<br/>0 exporters · silent"]:::blue -->|"SKTelemetry::init"| CAS["Atomic slot check<br/>validate + build"]:::amber
    CAS -->|"build error"| IDLE
    CAS -->|"installed"| ACT["Active pipeline<br/>3 signal providers"]:::green
    ACT -->|"2nd init call"| REJ["Structured SKError<br/>UnsupportedOperation"]:::rose
    ACT -->|"force_flush"| FLUSH["Flush all 3<br/>within flush_timeout"]:::violet
    FLUSH --> ACT
    ACT -->|"shutdown / Drop"| DONE["Detached & shut down<br/>0 active exporters"]:::orange

    classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef rose fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d

3. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
Isolate the OpenTelemetry SDK and OTLP exporters in sciencekit_telemetryEvery estimator crate continues to depend only on sciencekit_common and tracing. Applications that never export OTLP pay zero compile-time or binary-size cost for opentelemetry_sdk, tonic or reqwest.Putting OTLP exporters inside sciencekit_common — bloats the foundation crate at the root of the entire workspace dependency graph.
Derive traces, logs and metrics from the existing tracing instrumentationEstimators already emit sciencekit.operation spans and structured tracing events without knowing which subscriber is listening. Bridging all three signals in subscriber layers preserves the span contract unchanged.Sprinkling direct opentelemetry::global::meter() calls inside every algorithm — duplicates instrumentation and couples math kernels to telemetry APIs.
Enrich span Status::Error inside a SpanExporter wrapper (SKOperationSpanExporter)SKOperationObservation::record_error records the error string field on a failed span without mutating tracing_opentelemetry internals. Inspecting finished SpanData right before export promotes any non-empty error attribute into Status::Error { description } cleanly.Changing sciencekit_common span field names to otel.status_code — violates the non-goal of keeping the existing span field contract stable.
Canonicalize metric labels to closed &'static str vocabulariesMapping operation, backend and mode onto the closed SKOperationKind, SKBackendKind and SKExecutionMode sets (with "unknown" fallback) caps total time-series cardinality by construction and avoids per-span String allocations on on_close.Forwarding raw span string fields into KeyValue metric attributes — risks unbounded cardinality if caller code emits custom spans.
Install a swappable SubscriberProxy behind OnceLock<Arc<SKGlobalTelemetrySubscriber>>tracing::subscriber::set_global_default can only succeed once per OS process. Delegating through an RwLock<Option<Arc<dyn Subscriber + Send + Sync>>> lets shutdown() and Drop detach the active pipeline cleanly and rebuild tracing’s callsite interest cache so post-shutdown operations become silent again.Installing the concrete Registry directly as the global default — makes shutdown unable to detach the subscriber layers for the remainder of the process.
Gate network transports behind off-by-default otlp-grpc and otlp-http Cargo featuresIn-memory pipelines (SKTelemetryPipeline::from_exporters and SKTelemetry::init_with_exporters) work with default features for deterministic tests, while network clients compile only when otlp-grpc, otlp-http or the umbrella telemetry feature is requested.Enabling gRPC/HTTP clients in default features — pulls TLS/HTTP/protobuf stacks into builds that only want local or custom exporters.

4. The concepts, taught from zero

4.1 One instrumentation seam, three signals

When an estimator runs scaler.fit(&matrix), sk_run_operation opens a tracing span named "sciencekit.operation" with structured fields (operation = "fit", rows = 4, columns = 2, mode = "InProcessSynchronous", backend = "faer"). Inside that span, code may emit structured events such as tracing::warn!(fallback_reason = "no_enumerated_device", "falling back to host backend"). When the closure finishes, SKOperationObservation records error (if Err) and duration_ms, then drops the span.

SKTelemetryPipeline attaches three independent tracing_subscriber::Layer implementations to a single Registry:

  1. Traces (sk_build_trace_layer): tracing_opentelemetry converts each span enter/exit into an OpenTelemetry SpanData exported through BatchSpanProcessor and SKOperationSpanExporter, preserving attributes and promoting recorded error messages into OpenTelemetry’s Status::Error.
  2. Logs (sk_build_log_layer): OpenTelemetryTracingBridge converts each tracing::Event (info!, warn!, error!, …) into an OpenTelemetry LogRecord with matching Severity, target, body message, structured key-value attributes, and — whenever emitted inside an active span — the enclosing span’s TraceId and SpanId.
  3. Metrics (SKTelemetryMetricsLayer): a custom Layer stores an OperationSpanState in the span’s extensions on on_new_span, updates recorded fields on on_record / on_event, and on on_close records five OpenTelemetry instruments:
    • sciencekit.operation.duration (f64 histogram, unit "ms")
    • sciencekit.operation.count (u64 counter, unit "{operation}")
    • sciencekit.operation.rows (u64 histogram, unit "{row}")
    • sciencekit.operation.columns (u64 histogram, unit "{column}")
    • sciencekit.operation.errors (u64 counter, unit "{error}", incremented only when the operation failed)

4.2 Bounding metric cardinality mathematically

Unlike traces and logs, metric backends maintain an in-memory aggregation slot per unique tuple of attribute values. SKTelemetryMetricsLayer restricts every observation’s three labels to closed sets:

  • operation: $7$ SKOperationKind names (fit, partial_fit, fit_transform, transform, predict, fit_predict, score) plus "unknown" $\Rightarrow 8$ values.
  • backend: $6$ SKBackendKind names (faer, matrixmultiply, ndarray-linalg, opencl, cuda, rocm) plus "unknown" $\Rightarrow 7$ values.
  • mode: $5$ SKExecutionMode names (Automatic, InProcessSynchronous, InProcessAsynchronous, OutOfCoreStreaming, OutOfCoreMemoryMapped) plus "unknown" $\Rightarrow 6$ values.

Even in the worst case where every combination is exercised in one process, the number of distinct attribute series per instrument is strictly bounded by:

$$N_{\text{series}} \le 8 \times 7 \times 6 = 336$$

Row counts, column counts and elapsed milliseconds are recorded as histogram values, never as attribute labels, and arbitrary caller strings outside those closed enums collapse deterministically to "unknown".

4.3 Breaking recursive export feedback loops

An OTLP exporter sends batches over tonic/hyper/h2 (gRPC) or reqwest (HTTP). Those networking crates themselves emit tracing spans and events! Without target filtering, exporting one fit span would emit HTTP spans, whose export would emit more HTTP spans in an infinite feedback loop.

sciencekit_telemetry blocks that loop at two levels:

  • SubscriberProxy rejects callsites whose target starts with "opentelemetry", "tonic", "hyper", "h2" or "reqwest" (Interest::never()).
  • Both sk_build_trace_layer and sk_build_log_layer attach a tracing_subscriber::filter::Targets filter setting those internal transport targets to LevelFilter::OFF so standalone SKTelemetryPipeline::layer() compositions enjoy the exact same protection.

4.4 Deterministic flushing and flush_timeout

OpenTelemetry’s BatchSpanProcessor, BatchLogProcessor and PeriodicReader run background worker channels whose built-in force_flush waits use fixed multi-second internal defaults and can reject overlapping control messages when called concurrently from several worker threads.

sciencekit_telemetry hardens both edges:

  • SKTelemetry::force_flush serializes concurrent callers on an internal Mutex<()> (recovering cleanly from poisoning) and rejects calls after shutdown.
  • SKTelemetryPipeline::force_flush executes the three provider flushes behind a bounded channel receive (recv_timeout(configuration.flush_timeout())), guaranteeing force_flush either hands pending signals to the exporters or returns a structured timeout error within flush_timeout.

5. Each public object, explained

All public items live in sciencekit_telemetry and follow PRD §3.4 (SK prefix on types, sk_/SK_ on free functions and constants, full English words without abbreviations, pure-dispatcher mod.rs files, and every source file at or under 200 lines):

  • SKTelemetryTransport: wire protocol enum with variants Grpc (default, standard endpoint "http://localhost:4317") and Http (OTLP/HTTP binary protobuf over /v1/traces, /v1/logs, /v1/metrics, standard endpoint "http://localhost:4318").
  • SKTelemetrySampler: trace sampling policy enum with AlwaysOn (default), AlwaysOff, TraceIdRatioBased(f64) and ParentBased(f64). Validates that ratios are finite and lie in $[0.0, 1.0]$.
  • SKTelemetryResource: validated OpenTelemetry resource metadata holding required service.name, optional service.version, optional deployment.environment.name, and deterministic BTreeMap<String, String> custom attributes, convertible via to_sdk_resource().
  • SKTelemetryBatchConfiguration & SKTelemetryBatchConfigurationBuilder: builder-validated batching configuration (maximum_queue_size, maximum_export_batch_size, scheduled_delay, export_timeout, periodic_metric_interval, plus uniform backend and execution_mode). Enforces $1 \le \text{maximum_export_batch_size} \le \text{maximum_queue_size}$ and strictly positive durations.
  • SKTelemetryConfiguration & SKTelemetryConfigurationBuilder: main builder implementing SKBuilder<SKTelemetryConfiguration>, configuring service identity, resource attributes, endpoint, transport, header / headers, timeout (default 10s), flush_timeout (default 5s), sampler, batch, backend (default Faer) and execution_mode (default Automatic).
  • SKTelemetryPipeline: owns SdkTracerProvider, SdkLoggerProvider and SdkMeterProvider built from one SKTelemetryConfiguration. Exposes from_exporters, layer, subscriber, force_flush and shutdown, alongside lower-level builders (sk_build_tracer_provider, sk_build_trace_layer, sk_build_logger_provider, sk_build_log_layer, sk_build_meter_provider, sk_build_metrics_layer, SKTelemetryMetricsLayer, and sk_build_otlp_pipeline) and metric name constants (SK_METRIC_OPERATION_DURATION, SK_METRIC_OPERATION_COUNT, SK_METRIC_OPERATION_ROWS, SK_METRIC_OPERATION_COLUMNS, SK_METRIC_OPERATION_ERRORS).
  • SKTelemetry: process-wide lifecycle guard returned by SKTelemetry::init(configuration) or SKTelemetry::init_with_exporters(...). Exposes is_initialized(), active_exporter_count(), is_shut_down(), configuration(), force_flush(&self) and shutdown(self), plus a Drop implementation that detaches the global subscriber and shuts down all three providers if the caller drops the guard without calling shutdown explicitly.
startup_telemetry.rs
use std::time::Duration;
use sciencekit_common::SKBuilder;
use sciencekit_telemetry::{
    SKTelemetry, SKTelemetryConfiguration, SKTelemetrySampler, SKTelemetryTransport,
};

let configuration = SKTelemetryConfiguration::builder()
    .service_name("sciencekit-scoring-api")
    .service_version(env!("CARGO_PKG_VERSION"))
    .deployment_environment("production")
    .endpoint("http://localhost:4317")
    .transport(SKTelemetryTransport::Grpc)
    .header("x-api-key", "collector-token")
    .timeout(Duration::from_secs(5))
    .flush_timeout(Duration::from_secs(3))
    .sampler(SKTelemetrySampler::ParentBased(0.1))
    .build()?;

let telemetry = SKTelemetry::init(configuration)?;
// ... run estimators normally (fit, transform, predict, score) ...
telemetry.force_flush()?;
telemetry.shutdown()?;

6. Validation & error contract

Every invalid configuration or lifecycle misuse fails deterministically with a structured SKError — never a panic:

Failure conditionReturned SKError
Missing or blank service_nameSKError::InvalidHyperparameter { name: "service_name", .. }
Blank service_version, deployment_environment or resource attribute keySKError::InvalidHyperparameter
Endpoint missing http:// / https://, containing whitespace/control bytes, missing host, unclosed IPv6 bracket, or port outside 1..=65535SKError::InvalidHyperparameter { name: "endpoint", .. }
Non-token ASCII header name or header value containing \r, \n or NULSKError::InvalidHyperparameter { name: "headers", .. }
Zero timeout, flush_timeout, scheduled_delay, export_timeout or periodic_metric_intervalSKError::InvalidHyperparameter
Non-finite sampler ratio or ratio outside $[0.0, 1.0]$SKError::InvalidHyperparameter { name: "sampler", .. }
maximum_queue_size == 0 or maximum_export_batch_size outside 1..=maximum_queue_sizeSKError::InvalidHyperparameter
Calling SKTelemetry::init when the transport feature (otlp-grpc / otlp-http) is disabled, when a global subscriber is already installed externally, or a second time in the same processSKError::UnsupportedOperation { operation: "telemetry_init", .. }
Calling force_flush after shutdown, or when an exporter exceeds flush_timeoutSKError::UnsupportedOperation { operation: "telemetry_force_flush", .. }

7. Walking through the companion tests

The test suites sit right next to their implementation modules under crates/sciencekit_telemetry/src/ and test every requirement using deterministic InMemorySpanExporter, InMemoryLogExporter, InMemoryMetricExporter and custom probe exporters:

  • Configuration & validation (configuration/configuration_tests.rs, configuration/validation_tests.rs):
    • transport_defaults_to_grpc_and_exposes_standard_endpoints, resource_projects_service_identity_and_custom_attributes_into_sdk_resource, sampler_validates_ratios_and_builds_sdk_samplers and configuration_builder_constructs_complete_configuration_with_defaults_and_overrides verify defaults, Resource key-value projection, sampling ratios and full builder overrides.
    • configuration_builder_rejects_missing_or_blank_service_name, configuration_builder_rejects_malformed_endpoints and configuration_builder_rejects_invalid_headers_timeouts_samplers_and_batch_bounds exercise missing names, malformed schemes/ports/whitespace/IPv6 brackets, CRLF header injection, zero timeouts, out-of-range ratios and inverted batch bounds.
  • Trace, log & metric bridges (pipeline/traces_tests.rs, pipeline/logs_tests.rs, pipeline/metrics_tests.rs, pipeline/metrics_cardinality_tests.rs, pipeline/pipeline_tests.rs):
    • fit_operation_exports_span_with_rows_columns_backend_and_execution_mode runs a real SKStandardScaler::fit and verifies the exported sciencekit.operation span carries operation = "fit", rows = "4", columns = "2", backend = "matrixmultiply", mode = "InProcessSynchronous" and duration_ms.
    • failed_operation_exports_span_with_error_status_and_message runs a failing Transform operation and confirms Status::Error carries the shape-mismatch description.
    • structured_tracing_events_export_with_matching_severity_target_body_and_fields and structured_event_inside_operation_span_preserves_both_span_and_log_records verify Severity::Info / Warn / Error, structured attributes and active span trace-context correlation.
    • completed_operations_export_duration_count_rows_and_columns_metrics_with_labels, failed_operation_increments_error_counter_labelled_by_operation_and_backend and metrics_layer_bounds_label_cardinality_to_closed_vocabulary verify all five instruments, error counting and "unknown" canonicalization for arbitrary caller strings.
    • configured_resource_attributes_propagate_to_traces_logs_and_metrics and sampler_and_batch_settings_govern_exported_spans_and_batches prove identical resource metadata reaches all three exporters and verify AlwaysOff vs ParentBased(1.0) batching.
  • Silent default, lifecycle & concurrency (lifecycle/noop_tests.rs, lifecycle/lifecycle_tests.rs, lifecycle/flush_timeout_tests.rs, lifecycle/concurrency_tests.rs, acceptance_tests.rs):
    • uninitialized_default_creates_no_exporter_and_produces_no_network_traffic binds a non-blocking loopback TcpListener, builds a configuration pointing at that port without calling init, runs SKStandardScaler::fit + transform, and proves active_exporter_count() == 0 and accept() returns ErrorKind::WouldBlock. default_feature_set_compiles_out_otlp_network_exporters verifies OTLP transports are absent unless enabled.
    • force_flush_exports_pending_signals_and_shutdown_stops_further_exports, double_initialization_returns_structured_error_without_replacing_pipeline, dropping_telemetry_guard_flushes_pending_signals_and_detaches_safely and force_flush_times_out_promptly_when_exporter_exceeds_configured_flush_timeout verify every lifecycle transition, including a StallingSpanExporter timing out cleanly at 30ms.
    • concurrent_initialization_race_elects_single_winner_and_rejects_others synchronizes 8 threads on a Barrier racing init_with_exporters, asserting 1 winner and 7 structured rejections. concurrent_small_and_large_operations_export_consistent_spans_logs_and_metrics runs 6 threads across small (8 × 4) and larger (1024 × 4) matrices, fitting SKStandardScaler, exporting SKModelState, computing sk_mean_squared_error and calling force_flush concurrently.
    • dense_and_sparse_csr_operations_export_matching_telemetry_signals and otlp_grpc_and_http_pipelines_construct_and_shut_down_cleanly verify dense/CSR parity without densification and exercise real OTLP gRPC and HTTP exporter construction under --features telemetry.

Streaming pipelines: epochs, chained stages and a bounded finalizer

Every pipeline chapter so far assumed the data fits in memory. Chapter 24 built SKPipeline, a conveyor belt whose stages receive an owned SKFeatureBlock; chapter 43 added a fan-out and chapter 52 turned the belt into a runtime DAG. All of them still take the whole matrix as an argument: fit(&features, labels) borrows one Array2. The PRD’s out-of-core promise needs the other shape: a transformer that learns from a stream of batches, never holding more than one batch at a time, and a pipeline that applies the learned stages to one batch at a time.

This chapter tells the story of sciencekit_pipeline::streaming (capability streaming-pipeline): the SKStreamingTransformer contract, the SKStreamingPipeline builder, chained fitting through the shared prefetch executor, one-shot materialization, multi-epoch replay, the bounded batch finalizer and the error surface. It is the first pipeline layer whose input is a provider rather than a matrix.


1. The problem, in plain words

Imagine a warehouse too large to empty onto a single table. You can still describe a procedure — “weigh each box, subtract the average weight, scale by two” — and run it box by box. Two things are hard:

  1. Learning the numbers. “The average weight” is not known until every box has passed. A streaming transformer must therefore make a pass over the source, accumulate just enough state (sums, counts), and only then freeze a model.
  2. Reusing the procedure. Once the average is known, every new box is transformed in isolation. The pipeline must keep every stage’s learned model and run them in order, without ever concatenating the stream.

The existing sciencekit_common machinery already supplies the hard I/O parts: an SKLazySource<F> yields SKDataBatch<F> values, an SKSourceProvider<F> opens one source per pass (or exactly one when it is a one-shot &mut Source), and sk_run_streaming_provider runs the prefetch driver with a pass policy. The streaming pipeline is the composition layer on top.

flowchart LR
    accTitle: One streaming pass through the shared prefetch executor
    accDescr: The pipeline opens a source from a provider, the prefetch driver reads owned batches into a bounded buffer, and each batch is handed to a transformer update step. The update accumulates learned state; the batch itself is dropped before the next one is read.
    P["SKSourceProvider"] -->|open one pass| S["SKLazySource<br/>next_batch"]
    S --> BUF["bounded prefetch buffer<br/>depth = 1"]
    BUF --> U["update(batch, parallelism, state)"]
    U --> ST["learned state only<br/>sums, counts"]
    U -.->|batch dropped| BUF
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef amber fill:#fffbeb,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    class P sky
    class S,BUF amber
    class U,ST emerald

2. The decisions, and the roads not taken

DecisionWhy we chose itAlternatives we discarded
A dedicated SKStreamingTransformer<F> contractThe batch pipeline’s SKPipelineTransformer fits on one block. A streaming stage must fit from a source and transform a batch; modelling that separately keeps both contracts honest instead of overloading one.Making every SKPipelineTransformer accept a stream (breaks the batch contract); a single mega-trait with both fit forms.
Fit returns a model that owns only learned stateThe driver hands owned batches to an update closure. If the model retained batches, memory would grow with the stream. Storing the running mean of a stage is legitimate; storing the data is not.Keeping the source in the model (self-referential lifetimes, unbounded memory).
Chained fit by wrapping the providerStage i is fitted over a provider that opens the upstream source and pushes every batch through the already-fitted stages 0..i. No second I/O loop and no intermediate materialization for reopenable providers.Fitting each stage on a separately materialized copy of the whole dataset (defeats streaming); a bespoke multi-stage driver (duplicates the executor).
Erase stages behind an object-safe adapterA Vec of heterogeneous transformers whose models differ cannot be spelled without boxing. A private SKStreamingStage/SKFittedStage pair erases the stage while the public contract stays generic and statically typed.A giant generic tuple like SKPipeline (the streaming builder is runtime-sized, so the type would grow with the stage count); dyn on the public trait (its generic provider method is not object-safe).
One-shot providers are materialized within a budgetA &mut Source cannot be reopened for each stage. Reading it once into memory — bounded by memory_budget_bytes — gives the one-shot user the full chain, and a structured BatchBufferOversize error when it does not fit.Refusing every one-shot chain (the spec allows materialization); silently densifying or truncating (dishonest).
Multi-epoch replay only for reopenable providersEpochs mean replaying the source. A one-shot provider has nothing to replay, so epochs > 1 is a structured UnsupportedOperation naming the reopenable requirement instead of a silent clamp.Clamping to one epoch (hides a configuration error); caching the whole source for replay (unbounded, and not a stream).
A batch finalizer with an explicit byte budgetExisting estimators expose fit(&features), not partial_fit, so the finalizer needs the transformed data resident. The buffer charges every block against the budget and concatenates once, preserving CSR when every block is sparse.Pretending every estimator streams (unsupported); an unbounded Vec (OOM).
Structured errors, stage index includedA source failure stops the pipeline with the central taxonomy error. A stage failure is wrapped with its zero-based index so the caller knows which station rejected the batch.Panicking (forbidden); losing the index (unactionable).
backend and execution_mode on the builderRepository-wide rule: every public operation records the configured backend (default Faer) and execution intent (default Automatic) in its span.Hardcoding Faer; inferring a backend per stage.

The finalizer is deliberately the first version: a true out-of-core finalizer built on partial_fit, memmap2-backed batches, streaming DAGs, GPU execution and model export are explicit non-goals of this change and remain future work.


3. The concepts, taught from zero

Batches, sources, providers

A batch (SKDataBatch<F>) is an owned feature block plus a position and a final marker. A source (SKLazySource<F>) yields batches one at a time and can fail. A provider (SKSourceProvider<F>) opens a source for one pass; a concrete &mut Source is a one-shot provider, while SKReopenableSource wraps a factory and opens a fresh source per pass. The pipeline’s fit takes a provider, so the same code spans both worlds.

The transformer contract

#![allow(unused)]
fn main() {
pub trait SKStreamingTransformer<F: SKFloat> {
    type Model;
    type Error: From<SKError>;

    fn fit_streaming<S: SKSourceProvider<F>>(
        &self,
        source: &mut S,
        epochs: usize,
    ) -> Result<Self::Model, Self::Error>;

    fn transform_batch(
        &self,
        model: &Self::Model,
        batch: &SKFeatureBlock<F>,
    ) -> Result<SKFeatureBlock<F>, Self::Error>;
}
}

fit_streaming drives sk_run_streaming_provider with an SKStreamingPassPolicy::Iterative policy carrying the epoch budget; the executor enforces the pass count. transform_batch borrows the model and one batch. A stage that accepts CSR must return CSR — the pipeline never densifies on its behalf.

The builder and the fitted pipeline

SKStreamingPipeline::start::<F>() opens SKStreamingPipelineBuilder<F>. then(stage) appends a stage, backend, execution_mode, epochs and memory_budget_bytes configure the run, and finalize_estimator(estimator) validates the accumulated configuration (at least one stage, epochs >= 1, a non-zero budget) before returning SKStreamingPipelineConfigured<F, Estimator>. Its fit(provider) returns SKFittedStreamingPipeline<F, Estimator::Model>, whose transform_batch(&batch) runs the fitted stages and the finalizer, and whose report() exposes the run’s metrics.

flowchart TB
    accTitle: Fitting and transforming a streaming pipeline
    accDescr: On the left, fitting opens the provider once per stage, each wrapped by the previously fitted stages, and finally accumulates the transformed blocks into a bounded buffer that feeds the batch estimator. On the right, a new batch is transformed by the fitted stages and the finalizer without touching the source.
    subgraph FIT["fit(provider)"]
        direction TB
        S0["stage 0 fit<br/>raw batches"] --> F0["model 0"]
        S1["stage 1 fit<br/>batches through model 0"] --> F1["model 1"]
        F0 --> S1
        F1 --> ACC["bounded finalizer buffer<br/>memory_budget_bytes"]
        ACC --> EST["estimator.fit(accumulated)"]
        EST --> FM["final model"]
    end
    subgraph TRANSFORM["transform_batch(batch)"]
        direction LR
        X["SKFeatureBlock"] --> T0["stage 0"] --> T1["stage 1"] --> TF["finalizer"] --> Y["SKFeatureBlock"]
    end
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef amber fill:#fffbeb,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef violet fill:#f5f3ff,stroke:#7c3aed,stroke-width:2px,color:#3b0764
    class S0,S1,ACC amber
    class F0,F1,EST,FM,TF emerald
    class X,Y,T0,T1 sky
    class FIT,TRANSFORM violet

Epochs and passes

An epoch is a full pass over the source by one stage’s fit_streaming. With n stages and e epochs, a reopenable provider is opened n × e times for fitting plus once for the finalizer accumulation. A one-shot provider can be read only once: the pipeline materializes it (within the budget), then all stages and the finalizer read the materialized blocks. epochs > 1 on a one-shot provider is rejected because the data cannot be replayed.

The bounded finalizer

SKFinalizerBuffer stores the transformed blocks, charging each block’s byte_size() against memory_budget_bytes before storing it. Exceeding the budget returns SKError::BatchBufferOversize with the block size, the required total and the available budget. At the end it concatenates the blocks: all dense uses ndarray::concatenate, all sparse rebuilds one CSR matrix from the per-row entries, and a mixed set densifies only at this explicit materialization point. The estimator then fits on the concatenated block, and the fitted model is exposed through final_model().

Errors and concurrency

A read failure propagates from the executor as the central SKError. A stage that rejects a batch is wrapped by sk_stage_failure(index, error) into SKError::Conversion whose message names the stage index and preserves the cause. Fitted pipelines are Send + Sync because every stage model and the finalizer model are, so concurrent transform_batch calls are safe and deterministic.


4. Walking through the real tests

The companion tests are the executable specification. They live beside the implementation as *_tests.rs modules.

Construction and validation — builder_tests.rs: an_empty_streaming_pipeline_is_rejected, zero_epochs_are_rejected and a_zero_memory_budget_is_rejected pin the InvalidHyperparameter surface; a_valid_pipeline_is_configured_with_the_default_backend fits a real one-stage pipeline and checks the default Faer backend and the fit report.

The transformer contract — transformer_tests.rs uses the test fixture SKTestMeanCentering, which learns column means through sk_run_streaming_provider. a_streaming_fit_reads_the_source_and_centers_batches checks the hand-computed means of the 3×2×2 fixture; one_pass_and_two_epochs_learn_the_same_mean shows that replaying the source leaves the mean unchanged (the extra pass adds the same data twice, so the ratio is identical); a_transformed_batch_keeps_its_row_count pins the row-count invariant.

Chained fitting — fit_tests.rs::the_second_stage_is_fitted_on_the_first_stage_output composes SKTestColumnScaling(2.0) and SKTestMeanCentering. If the second stage saw raw data, its means would be 6 and 7; it sees doubled data, learns 12 and 14, and the batch [1,2;3,4] becomes [-10,-10;-6,-6]. a_two_stage_fit_reads_one_pass_per_stage_plus_the_finalizer checks the report (stage count, batches, rows).

One-shot providers — oneshot_tests.rs covers the four cases: a single stage fits (a_one_shot_provider_fits_a_single_stage), a chain materializes within the budget (a_one_shot_provider_materializes_within_the_budget_for_a_chain asserts 96 resident bytes for three 2×2 f64 blocks), multiple epochs are rejected (a_one_shot_provider_rejects_multiple_epochs), and an over-budget materialization returns BatchBufferOversize (a_one_shot_provider_over_budget_returns_a_structured_error).

Epochs — epochs_tests.rs::a_reopenable_provider_replays_every_configured_epoch checks the reported epoch count, and the_epoch_count_does_not_multiply_the_finalizer_rows proves the finalizer takes exactly one accumulation pass even when stages replay four epochs.

Transform parity — transform_tests.rs compares the streaming pipeline against the equivalent batch path built from the same transformers: streaming_transform_equals_the_equivalent_batch_transform and streaming_transform_matches_on_unseen_rows assert identical dense outputs.

Representation parity — representation_tests.rs::a_sparse_batch_stays_csr_and_is_not_densified sends a two-entry CSR batch through SKTestColumnScaling and asserts the result is still CSR with two stored entries, doubled; a_dense_batch_stays_dense covers the dense side.

The finalizer budget — finalizer_tests.rs::the_finalizer_fits_within_a_sufficient_budget uses exactly 96 bytes and succeeds; the_finalizer_rejects_an_accumulation_over_the_budget uses 95 and matches the BatchBufferOversize { batch_bytes: 32, required_bytes: 96, available_bytes: 95 } fields.

Error propagation — errors_tests.rs::a_mid_stream_source_failure_surfaces_the_central_error uses a source that fails at the second batch; a_stage_failure_names_the_stage_index transforms a sparse batch through a chain whose second stage rejects it and asserts the message contains stage 1 and sparse.

Determinism and concurrency — concurrency_tests.rs asserts that two independent fits produce identical output (fitting_the_same_stream_twice_produces_identical_output), that the fitted type is Send + Sync (the_fitted_pipeline_is_send_and_sync), and that eight threads transforming the same batch agree with the sequential result (concurrent_transform_agrees_with_the_sequential_result).

Acceptance — streaming/acceptance_streaming_tests.rs covers a tiny stream and a produced metric (a_tiny_stream_produces_a_centered_metric_near_zero checks every column mean is zero), a large stream that never materializes (a_large_stream_fits_without_materializing_the_source, 1 000 blocks), sparse flow, and an enforced finalizer budget on a large stream. The crate-level acceptance_tests/streaming_pipeline_tests.rs repeats the tiny, large and one-shot acceptance paths from outside the module.


5. What this chapter leaves for later

The streaming pipeline is the composition seam, not the end of out-of-core. A partial_fit finalizer that consumes transformed batches without materializing them, memory-mapped batches (memmap2, Wave 7), streaming DAGs, GPU execution and model export are separate changes. What exists now is deliberately small and honest: every stage learns from a stream, every batch is transformed in isolation, every materialization is bounded and every failure is structured.


6. Where to read the code

ObjectFile
SKStreamingTransformercrates/sciencekit_pipeline/src/streaming/transformer.rs
SKStreamingPipeline, SKStreamingPipelineBuildercrates/sciencekit_pipeline/src/streaming/builder.rs
SKStreamingPipelineConfigured (chained fit)crates/sciencekit_pipeline/src/streaming/pipeline/configured.rs
SKFittedStreamingPipeline (transform)crates/sciencekit_pipeline/src/streaming/pipeline/fitted.rs
SKStreamingFitReportcrates/sciencekit_pipeline/src/streaming/pipeline/report.rs
SKFinalizerBuffercrates/sciencekit_pipeline/src/streaming/finalizer.rs
Materialization and stage applicationcrates/sciencekit_pipeline/src/streaming/fitting.rs
Object-safe stage and provider adapterscrates/sciencekit_pipeline/src/streaming/stage.rs, provider.rs
Error constructorscrates/sciencekit_pipeline/src/streaming/errors.rs

Polars and DataFusion sources: one tabular contract for two engines

1. The problem we were solving

A data scientist rarely starts with a Vec<f64> or an ndarray::Array2. The data already lives in a DataFrame engine such as Polars, in a query engine such as DataFusion, in an Arrow RecordBatch, or on disk as Parquet. Before this change, using sciencekit meant reselecting columns, renaming dtypes, converting missing values and reshaping rows by hand — then repeating the whole exercise in reverse to export results.

The two engines look similar from a distance and different up close:

  • Polars is an eager DataFrame plus a lazy query plan (LazyFrame). Its own Arrow fork is private; a series is a typed, nullable column, and category columns are physically dictionary codes.
  • DataFusion is a SQL query engine. A DataFrame is an unexecuted logical plan that produces Arrow RecordBatch values. DataFusion 46 carries Arrow 54, while the rest of this repository already speaks Arrow 58.

Adding either engine to the default build would drag a large dependency graph into every user of the library. The change therefore had three jobs:

  1. define one materialized table contract that both engines can feed;
  2. keep each engine behind an optional feature (polars, datafusion);
  3. map missing values and categories once, in the neutral layer, so an estimator never learns which engine produced its matrix.

The result is sciencekit_interop::tabular. It reuses the batch pipeline that already existed (SKTabularBatch, SKMissingValuePolicy, SKColumnSelection) rather than duplicating it.


2. The idea in one picture

flowchart LR
    accTitle: Two DataFrame engines feeding one materialized tabular contract
    accDescr: Polars DataFrame and LazyFrame and DataFusion DataFrame and RecordBatch are feature-gated. Each adapter maps its own dtype vocabulary onto SKLogicalType and produces an SKTabularBatch. The neutral materializer applies the missing-value policy, then builds a dense or sparse SKFeatureBlock plus an owned SKNominalMatrixOwned. Both blocks are checked for row alignment before SKTabularDataset is constructed.

    POL["Polars DataFrame"]:::blue --> PB["Polars adapter<br/>feature = polars"]:::amber
    PLAZ["Polars LazyFrame"]:::blue --> PB
    DF["DataFusion DataFrame"]:::violet --> DB["DataFusion adapter<br/>feature = datafusion"]:::rose
    RB["Arrow RecordBatch<br/>(DataFusion 46 / Arrow 54)"]:::violet --> DB
    PQ["Parquet file"]:::violet --> DB

    PB --> BATCH["SKTabularBatch<br/>neutral columns + nulls"]:::green
    DB --> BATCH

    BATCH --> MAT["to_tabular_dataset<br/>policy + column kinds"]:::orange
    MAT --> FB["SKFeatureBlock<br/>dense / sparse"]:::green
    MAT --> CAT["SKNominalMatrixOwned<br/>codes + label tables"]:::green
    FB --> DS["SKTabularDataset"]:::green
    CAT --> DS

    classDef blue fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e
    classDef violet fill:#ede9fe,stroke:#7c3aed,color:#3b0764
    classDef amber fill:#fef3c7,stroke:#d97706,color:#78350f
    classDef rose fill:#ffe4e6,stroke:#e11d48,color:#7f1d1d
    classDef green fill:#f0fdf4,stroke:#16a34a,color:#14532d
    classDef orange fill:#fff7ed,stroke:#ea580c,color:#7c2d12

Everything in blue and violet is engine-specific and optional. Everything in green and orange is compiled into every build and has no engine dependency.


3. The decisions — and the roads not taken

3.1 A dataset, not a second “source”

The original plan called the materialized value SKTabularSource<F>. That name was already taken by the reopenable batch trait in sciencekit_interop::source, which every streaming adapter implements. Keeping two meanings of source would have made imports and documentation ambiguous. The materialized value is therefore sciencekit_interop::tabular::SKTabularDataset<F>, while SKTabularSource keeps its streaming meaning. The design document records this naming deviation explicitly.

3.2 Reuse the batch pipeline

The adapters do not build matrices directly. They produce SKTabularBatch values, the same neutral column-major batch used by the Arrow adapter. The existing materializer then handles:

  • numeric coercion and integer widening (sk_coerce_numeric_column);
  • boolean-to-0/1 mapping;
  • missing-value policy (Reject, NumericNaN, CategoricalMissingCode, ConstantFill);
  • dense or sparse feature blocks (SKFeatureLayout);
  • categorical canonicalization through sk_canonicalize_labels.

This is why the chapter talks about a contract rather than two new importers. The engines only translate their dtype vocabularies.

3.3 Column kinds, not roles

SKColumnRole already answers “is this a feature, a target or ignored?” for the supervised batch path. The tabular contract needs a different question: “how does this column enter the materialized outputs?” SKColumnKind answers it with four values:

KindEntersMapping
Numericfeature blockf32/f64 directly, integers widened to the scalar
Booleanfeature blocktrue → 1, false → 0
Categoricalcategorical blockstrings canonicalized to codes + label table
Ignorednothingdropped from outputs and from the projected schema

SKTabularSourceConfig is the validated list of (name, kind) pairs plus the missing-value policy and the requested layout. Its builder rejects an empty list and duplicate names before a single row is read. An ignored column may even be absent from the adapter batch: the materializer skips it either way.

3.4 Missing values have exactly one mapping

Numeric and boolean nulls become NaN under SKMissingValuePolicy::NumericNaN. Categorical nulls become SK_CATEGORICAL_MISSING_CODE (-1) under SKMissingValuePolicy::CategoricalMissingCode. The default remains Reject, so a caller must acknowledge nullability rather than inheriting an engine’s opinion. A null is never silently turned into zero, because zero is a real measurement.

3.5 Version pins are part of the contract

The workspace targets Rust 1.85. Both engines float toward newer toolchains unless pinned:

  • Polars 0.46 builds on 1.85 only when psm is pinned to 0.1.28; newer psm releases pull ar_archive_writer 0.5, which uses let-chains stabilized in Rust 1.88.
  • DataFusion 46 (MSRV 1.82) builds on 1.85 once comfy-table, pulled through arrow-cast 54, is pinned to 7.1.4 for the same reason.

Both pins live in crates/sciencekit_interop/Cargo.toml with comments, and each is attached to the corresponding optional feature, so the default build resolves neither engine. The lockfile is not committed (the repository ignores it for a library), which is exactly why the pins must be declared in the manifest.

3.6 Roads not taken

  • One shared Arrow crate. DataFusion 46 pins Arrow 54 while the repository speaks Arrow 58. Mixing both in one public type would leak two incompatible RecordBatch types. Instead the DataFusion adapter maps its own Arrow vocabulary into neutral columns and never exposes a DataFusion Arrow type publicly.
  • Unsafe C Data Interface bridging between the two Arrow versions. The crate denies unsafe_code, and a cross-version FFI hop would be unverifiable at the byte level. The safe downcast-based reader is slower per cell but auditable.
  • Encoding categorical columns into one-hot features. That would silently change the model’s input width and contradict the existing categorical contract, which carries codes and label tables.
  • Writing back to Polars or DataFusion. The change is additive and import-only.

4. The public objects

SKTabularDataset<F>

Built by SKTabularDataset::new(schema, features, categorical). The constructor checks that the numeric and categorical blocks agree on the row count and that the projected schema width equals the numeric width plus the categorical width. It exposes schema(), features(), feature_view() (a zero-copy SKDataView), categorical(), number_of_rows(), number_of_feature_columns(), number_of_categorical_columns() and into_parts().

SKNominalMatrixOwned

An owned code matrix (ndarray::Array2<i64>) plus one Option<SKLabelTable> per column. Codes use the documented missing sentinel. with_view lends it as SKCategoricalView::Integer, so no string copy is needed at read time.

SKTabularSourceConfig and SKColumnKind

The builder-only configuration described above. column, missing_value_policy and layout are the only setters; build validates the surface.

SKTabularBatch::to_tabular_dataset

The neutral materializer. It resolves the configured names against the batch schema, validates each kind against the column’s logical type, builds the feature selection and the categorical selection, and assembles the dataset. An unknown name returns UnknownColumn listing what the source actually carries; a kind/type mismatch returns UnsupportedColumnType naming the column.

Polars surface (feature = "polars")

  • sk_tabular_batch_from_dataframe(frame, config, position, is_final)
  • sk_tabular_dataset_from_dataframe::<F>(frame, config)
  • TryFrom<(&DataFrame, &SKTabularSourceConfig)> for SKTabularDataset<F>
  • SKPolarsLazySource::new(lazy_frame, config, batch_size) implementing SKTabularSource

Polars 0.46 exposes no incremental sink over a LazyFrame. The lazy source therefore executes the plan once per open, then slices the executed frame into owned batches of at most batch_size rows. This keeps downstream memory bounded per block and preserves row order, but it is an honest limitation: the plan itself is not pulled row by row. The struct documents this in its type-level comment.

DataFusion surface (feature = "datafusion")

  • sk_tabular_batch_from_datafusion_record_batch
  • sk_tabular_batches_from_dataframe (async), sk_tabular_dataset_from_dataframe (async), sk_tabular_dataset_from_dataframe_blocking (sync, refuses to nest inside a Tokio runtime)
  • TryFrom<(&DataFrame, &SKTabularSourceConfig)> for SKTabularDataset<F>
  • SKDataFusionStreamSource, a genuine streaming source over execute_stream
  • sk_dataframe_from_parquet, sk_tabular_dataset_from_parquet and its blocking twin

SKDataFusionStreamSource buffers exactly one record batch ahead, only to know whether the current block is final. That keeps the is_final contract without collecting the result set.


5. Walking the real tests

The tests are the executable specification; each name below is a test in the repository.

Tabular contract

  • tabular_source_numeric_columns_form_feature_block_in_order builds a mixed batch with x, count, flag, label and an ignored note, then asserts the dense matrix is [[1, 10, 1], [2, 20, 0], [3, 30, 1]] in configuration order.
  • tabular_source_ignored_columns_are_excluded checks that note is absent from the projected schema and that only one categorical column remains.
  • tabular_missing_numeric_null_becomes_nan and tabular_missing_categorical_null_becomes_sentinel pin the two missing mappings.
  • tabular_source_kind_mismatch_names_the_column declares the text column label numeric and expects UnsupportedColumnType naming label.

Polars

  • polars_dataframe_maps_numeric_columns_in_order exercises f64, i32 and bool in one frame.
  • polars_dataframe_reads_categorical_dtype_as_text casts a string series to Polars’ Categorical dtype and proves it is read through its labels, not its internal codes.
  • polars_lazy_source_streams_ordered_batches opens a five-row lazy frame with batch_size = 2, expects positions 0, 1, 2, then reopens the source and reads the first batch again — the reopenability contract.
  • polars_acceptance_large_table_and_concurrent_reads runs a one-row and a 2,000-row frame, then compares four thread reads against the single-threaded matrix with NaN normalized.

DataFusion

  • datafusion_record_batch_maps_columns_in_config_order builds Arrow 54 arrays directly.
  • datafusion_dataframe_converts_to_dataset goes through SessionContext::read_batch and the blocking conversion.
  • datafusion_stream_source_preserves_order_and_final_flag asserts positions start at zero, exactly the last batch is final, and a second open yields another batch.
  • datafusion_parquet_converts_with_the_same_rules writes a Parquet fixture with datafusion::parquet::arrow::ArrowWriter, reads it back through a temporary SessionContext, and checks the same numeric/categorical result.
  • datafusion_dataset_reads_agree_across_threads wraps the dataset in Arc and compares four worker reads.

Gates

The change runs cargo fmt --all --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test --workspace, and the interop suite with --features polars,datafusion,arrow. The combined feature run matters: it proves that DataFusion’s Arrow 54 and the repository’s Arrow 58 can coexist in one build without a type collision.


6. What to remember

  1. A DataFrame engine and a query engine can share one materialized contract if the contract is defined on neutral columns, not on engine types.
  2. Feature gates keep the heavy dependency graph out of the default build; the pins that make the features work on Rust 1.85 are as important as the code.
  3. Missing values and categories are mapped once, in the neutral layer, under an explicit policy.
  4. Streaming is a property of the source trait, not of the materialized dataset; Polars offers batch slicing after execution, DataFusion offers a true record-batch stream, and both are documented for what they are.

Memory-mapped sources: touching a dataset instead of copying it

Every chapter before this one consumed data through a copy. A Vec, an Array2, a SKDataBatch — even the streaming chapters copied each block from a reader into memory before an estimator saw it. That is fine while the dataset fits in RAM, and the PRD’s out-of-core promise (§4.4) says it must not be a requirement. A dataset can be larger than memory, and the estimators listed in the PRD (SKKMeans, k-NN, SKDBSCAN, decision trees) ask for row 900 000 by index, not for “the next batch”. This chapter tells the story of the memmap feature of sciencekit_interop: raw binary matrices, NumPy .npy files and Arrow IPC files exposed as zero-copy, randomly addressable sources, each also usable as a sequential block source.

Everything here lives behind the crate feature memmap; with the feature off the crate compiles exactly as before. The two new dependencies are memmap2, which asks the operating system to map a file into the process address space, and npyz, which parses the Python-literal header of a .npy file.


1. The idea in plain words: the file is already in memory

Modern operating systems give every process a virtual address space. A program can reserve a range of addresses and tell the kernel: “the bytes behind these addresses are the contents of this file”. Nothing is read yet. The call returns immediately; the mapping is a promise, not a copy.

The bytes arrive later, one page at a time (typically 4 KiB), the first time the program touches that page. The CPU raises a page fault, the kernel reads the page from disk into the page cache, and the instruction that touched it resumes. If the same bytes are needed again, the page is already resident and no disk I/O happens. The kernel can also evict clean pages under memory pressure because the file is the backing store — the data is not lost, it can be read again.

This has three consequences that shape the whole design:

  1. Random access is genuinely random. Reading row 1 000 000 of a column-major-free matrix costs one address computation plus the page faults of the columns touched by that row — never a scan of the preceding rows.
  2. Resident memory is bounded by what you touch, not by the file size. A 40 GiB file can be queried on a 4 GiB machine.
  3. A view into the mapping borrows the file. The bytes are owned by the kernel, not by the process, so the source must keep the mapping alive exactly as long as any returned row view.

SKMappableSource<F> already existed in sciencekit_common, precisely so algorithms never learn where bytes come from:

#![allow(unused)]
fn main() {
pub trait SKMappableSource<F> {
    type Error: From<SKError>;
    fn number_of_rows(&self) -> usize;
    fn row(&self, index: usize) -> Result<ArrayView1<'_, F>, Self::Error>;
}
}

The returned ArrayView1<'_, F> borrows the source. That signature is what forces the design in the next sections: a row must be a contiguous, aligned slice of F that outlives the call and lives inside the mapping.


2. The shape of the feature

flowchart TB
  accTitle: Memory-mapped inputs and the two source interfaces
  accDescr: A raw binary file, a NumPy file and an Arrow IPC file each pass through format-specific validation or header parsing, then map into the process address space as a read-only memory map. The map serves either a random-access mappable source or a sequential lazy source.
    subgraph DISK["on disk"]
        RAW["raw binary<br/>headerless fixed-width scalars"]
        NPY[".npy<br/>Python header + C-order payload"]
        IPC["Arrow IPC file<br/>footer indexes record batches"]
    end
    subgraph MEM["process address space"]
        MM["memmap2::Mmap<br/>read-only, page aligned, Send + Sync"]
    end
    RAW --> VAL["descriptor validation<br/>rows × columns × dtype"]
    NPY --> HDR["npyz header parse<br/>magic · dtype · shape · order"]
    IPC --> IDX["footer index<br/>first_row + row_count per batch"]
    VAL --> MM
    HDR --> MM
    IDX --> MM
    MM --> RAS["SKMappableSource<br/>row(i) → ArrayView1"]
    MM --> SEQ["SKLazySource<br/>next_batch() → owned SKDataBatch"]
    classDef sky fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef amber fill:#fffbeb,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef emerald fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d
    class RAW,NPY,IPC sky
    class VAL,HDR,IDX,MM amber
    class RAS,SEQ emerald

Every source implements both contracts. row returns a borrowed view; next_batch copies at most a configured number of rows into an owned SKDataBatch. The same object can therefore serve a random-access estimator or the streaming driver without opening the file twice.

Decisions, and the roads not taken

DecisionWhyAlternatives discarded
Arc<Mmap> inside each sourceA Mmap is stable when moved and is Send + Sync; an Arc lets concurrent readers share it.Box<Mmap> (cannot clone for threads), a bare slice (lifetime cannot outlive the file).
unsafe confined to one byte-to-scalar helperProducing &[F] from raw bytes requires from_raw_parts. sk_scalar_slice validates alignment and length once and carries a SAFETY comment. The Arrow cache uses OnceLock, so its row views need no unsafe at all.Scattering unsafe through the sources; pretending transmute is safe.
Descriptor instead of guessing a raw shaperows × columns has many factorisations; any guess would be plausible and wrong half the time. A sidecar JSON ({"rows": 1024, "columns": 8, "dtype": "f64"}) is explicit and detectable.Inferring the shape from file length.
Zero-copy only when the dtype matchesAn f64 view cannot alias f4 bytes. The documented cast path materialises the matrix once.Silently converting per row (a hidden copy per access), rejecting all casts.
Alignment checked before exposing views.npy pads its header to 64 bytes, which is usually but not necessarily a multiple of the element size. An unaligned &f64 is undefined behaviour.read_unaligned per value (a copy and a different API), assuming headers are always friendly.
Arrow: footer index, batch decode on demandThe footer knows every batch’s offset and row count. row(i) binary-searches the cumulative offsets and decodes exactly one batch.Decoding every batch on open (linear in file size), scanning batches from the start.
Sequential blocks are ownedSKDataBatch is moved to another thread by the prefetch driver, so it cannot borrow the mapping.Borrowed batches (does not fit the executor contract).
Structured errors from the central taxonomyEvery opening failure names the file and the reason (MissingMappedFile, MappedLengthMismatch, MalformedMappedHeader, MisalignedMappedData, UnsupportedMappedDtype, NonLittleEndianMappedData, UnreadableMappedBatch).Panics, or a single opaque Io error.

3. Raw binary: explicit shape, exact length

A raw file is the simplest case and the strictest one. SKRawBinaryDescriptor carries rows, columns, dtype and an optional endianness (little by default). SKRawBinaryMappableSource::open performs four checks before any row can be read:

  1. the descriptor must be little-endian, otherwise SKError::NonLittleEndianMappedData;
  2. its dtype must equal the model scalar (F::SCALAR_NAME), otherwise SKError::UnsupportedMappedDtype;
  3. rows × columns × element_size must equal the file length exactly, otherwise SKError::MappedLengthMismatch naming the file, the expected and the actual byte counts;
  4. the payload must be aligned for F, checked by sk_scalar_slice.

Only then is the mapping retained. row(index) computes index * number_of_columns, slices the mapped scalars and reshapes them with ArrayView1::from_shape — no loop over preceding rows. The unit test random_access_does_not_scan_or_copy builds a million-row file and asserts that row 900 000 is correct and that its address equals mapped_payload_address() + 900_000 × columns × 8.


4. NumPy .npy: a header we must understand

A .npy file is a small text header followed by the array payload:

offset 0      6 bytes   \x93NUMPY      magic
offset 6      1 byte    major version  1, 2 or 3
offset 7      1 byte    minor version
offset 8      2 or 4    header length  u16 for v1, u32 for v2/3
offset 10/12  L bytes   Python dict:  {'descr': '<f8', 'fortran_order': False,
                                        'shape': (3, 2), }
offset 10+L   ...       raw C-order payload

npyz::NpyHeader::from_reader parses the dictionary and gives the dtype, shape and order. The adapter separately computes the payload offset from the framing bytes, because the mapping must start at that exact byte. It then applies a small policy:

  • Fortran order is rejected with SKError::UnsupportedOperation whose message suggests numpy.ascontiguousarray; a column-major array cannot be viewed as row-major rows.
  • Big-endian dtypes are rejected with SKError::NonLittleEndianMappedData.
  • f4 for an f32 model and f8 for an f64 model are zero-copy. is_zero_copy() is true and mapped_payload_address() names the first payload byte; the test float64_rows_alias_the_mapping asserts that a row pointer is exactly that address plus the row offset.
  • int64 (and float dtypes that differ from the model scalar) require open_with_cast. That path materialises the matrix once into an owned Array2<F>; the test int64_with_cast_materializes_values shows the values and asserts !is_zero_copy(). Opening without the cast returns UnsupportedMappedDtype and names the casting method.
  • Misalignment is a structured error, not undefined behaviour. The fixture writer can emit a header whose length deliberately puts the payload at an odd address; the test misaligned_header_payload_is_rejected expects MisalignedMappedData, and the cast path is the documented remedy.

The header parser itself is tested for a corrupt magic (malformed_header_is_rejected_without_panicking), a file ending inside the framing (truncated_header_is_rejected) and a payload shorter or longer than the declared shape (length_mismatch_is_rejected). Because a file is untrusted input, the byte-length multiplication is checked: absurd_npy_dimension_is_a_typed_error declares a shape whose element count fits usize while its byte count does not, and expects MalformedMappedHeader instead of an overflow panic. The hostile-input suite pairs it with a truncated raw file and a wrong raw shape descriptor, each returning a typed error.


5. Arrow IPC: index the batches, decode one

Arrow is columnar. Inside a record batch, every column is a separate contiguous buffer, so a row is not contiguous — it interleaves values from several columns. Zero-copy row views are therefore impossible in general. What the adapter can avoid is decoding the whole file to answer one row.

An Arrow IPC file ends with a FlatBuffer footer followed by its length and the ARROW1 magic. The footer lists every record batch’s offset, metadata length and body length, plus the schema. sk_read_ipc_layout reads only that footer and, for each block, parses the encapsulated message metadata to obtain the row count — the body buffers are never touched. It builds a cumulative index first_row → number_of_rows and validates that every block lies inside the file, so a truncated file fails on open (MalformedMappedHeader) rather than faulting later. The row-count accumulation uses checked_add, so a crafted footer cannot wrap the row space; the arrow_ipc_layout_tests cover both the normal accumulation and the overflow rejection.

SKArrowIpcMappableSource::row(index) then:

  1. binary-searches the cumulative offsets (partition_point) to find the containing batch;
  2. decodes that one batch through FileReader, materialises it as row-major F values in a boxed slice, and caches it in a Vec<OnceLock<Box<[F]>>>;
  3. returns an ArrayView1 over the cached slice through an ordinary shared reference.

The cache is the one place where a returned view is produced from interior mutability. It needs no unsafe: OnceLock::get hands out &Box<[F]> tied to the source’s lifetime, and a slot is filled once and never replaced or removed, so a concurrent reader either wins the race or drops its identical copy. Before slicing, the row offset is multiplied with checked_mul and bounded against the decoded batch length, so crafted batch metadata becomes UnreadableMappedBatch instead of an out-of-bounds read. Concurrent readers are exercised by eight_threads_read_disjoint_rows_from_an_ipc_file; opening_indexes_batches_without_decoding_them asserts decoded_batch_count() == 0 right after open and row_lookup_decodes_only_the_containing_batch shows the count rise only for the batches actually touched.


6. Sequential streaming, bounded batches, concurrency

SKLazySource<F> wants owned batches. sk_next_mapped_block reads at most block_size rows through the same row accessor, copies them into an Array2<F>, wraps it in SKDataBatch::new_dense, and marks the last block final. The cursor is an AtomicUsize so the source stays Sync; next_batch takes &mut self but the row reads themselves are shared.

This is where the two contracts meet: a single open source can answer random row requests and, later, stream the file once. The tests sequential_blocks_respect_the_block_size_and_mark_the_last, sequential_blocks_match_random_access and sequential_streaming_agrees_with_random_access check that the concatenation of the sequential blocks equals the random-access rows in order, that no block exceeds the configured size, and that exactly one block is final. The large-file test a_large_file_streams_in_bounded_batches runs 10 000 rows through a 512-row block size and asserts each batch’s resident byte_size() stays inside 512 × columns × 8 bytes.

All three sources are Send + Sync (asserted at compile time by mapped_sources_are_send_and_sync) and are read by eight threads over disjoint rows in eight_threads_read_disjoint_rows_from_a_raw_file, ..._from_a_numpy_file and ..._from_an_ipc_file. Reading is shared; only the sequential cursor and the per-batch OnceLock slots change, and each slot is written at most once.


7. The public objects, one by one

ObjectWhereWhat it does
SKRawBinaryDescriptor, SKRawBinaryDtype, SKRawBinaryEndiannessmemmap::descriptorShape, dtype and byte order of a headerless matrix; JSON sidecar parsing with from_json / from_sidecar.
SKRawBinaryMappableSource<F>memmap::raw_binary_sourceMaps a raw file, implements SKMappableSource<F> and SKLazySource<F>; with_block_size, mapped_payload_address.
SKNumpyMappableSource<F>memmap::numpy_sourceMaps a .npy matrix; open is zero-copy for a matching dtype, open_with_cast materialises; is_zero_copy, dtype_name, mapped_payload_address.
SKArrowIpcMappableSource<F>memmap::arrow_ipc_sourceMaps an IPC file and indexes its batches; number_of_batches, decoded_batch_count, row and next_batch.
sk_check_alignment, sk_scalar_slicememmap::alignment (crate-internal)The only byte-to-scalar casts; validate alignment and length.
sk_next_mapped_blockmemmap::sequential (crate-internal)Copies the next bounded block into an owned SKDataBatch.
sk_read_ipc_layoutmemmap::arrow_ipc_layout (crate-internal)Footer-only index of an Arrow IPC file.

All sources use the repository’s naming rules (SK on types, sk_ on free functions), keep the implementation in folder modules with a pure-dispatcher mod.rs, and put every companion test in a *_tests.rs file beside the implementation.


8. Limits, and what we deliberately did not build

Mapping a file assumes nobody else truncates or rewrites it while it is mapped. The adapters validate the length at open, which removes the common SIGBUS case, but a file truncated after open can still fault; the documentation states that mutation is undefined and the tests use immutable fixtures. Windows read-only mapping also differs in its sharing semantics; CI targets Linux/macOS.

Out of scope, on purpose: CSV and JSON (not fixed-width, they stream through the Arrow adapter), Parquet random row access (row groups, not rows, are the unit), .npz archives, compressed .npy, Fortran order and big-endian raw files. Each of these would either break zero-copy or need a materialising layer that already exists elsewhere.


9. Running the tests and the book

# The neutral crate, with the feature off:
cargo test -p sciencekit_interop

# The memory-mapped sources:
cargo test -p sciencekit_interop --features memmap

The feature matrix in CI runs both, and the memmap flag also enables the arrow adapter because the IPC source builds on it. Build the book with:

mdbook build docs

Linear support-vector machines: coordinate descent, one sweep at a time

Chapter 41 built SKSVC, a kernel support-vector classifier that only ever touches the data through a kernel matrix. That design is elegant, and it is the right answer whenever the dataset is modest and the boundary has to bend — a few thousand rows, a radial basis function, a curve that no straight line can follow. But it hides a scaling wall: an $n \times n$ kernel matrix (or a cache of its rows) grows with the square of the number of training rows. For $50,000$ text documents the Gram matrix alone would need $20$ billion entries. Text classification, the canonical linear-SVM workload, is exactly that regime: a very large number of rows, a very large number of columns, and each row almost entirely zero.

This chapter tells the story of SKLinearSVC, the linear member of the sciencekit_svm family. It fits a maximum-margin linear boundary directly in the input space, with no kernel matrix at all, using dual coordinate descent — the algorithm made practical by Fan, Chang, Hsieh, Wang and Lin in LIBLINEAR (2008). The story is as much about the data boundary as about the math: a CSR matrix with four stored entries per row must never be expanded into a dense $20,000 \times 10,000$ block just to multiply it by a coefficient vector.

flowchart LR
    accTitle: End-to-end flow of SKLinearSVC from data views to confidence margins
    accDescr: A borrowed dense view or a borrowed CSR view enters one-time representation dispatch. The dispatched design answers row dots and scaled-row accumulation over stored entries only. The dual coordinate-descent solver keeps an O(n) dual vector and an O(p) coefficient vector, then re-optimizes the intercept by 1-D bisection for the fitted weights. One-vs-rest heads are fitted in parallel and assembled into SKLinearSVCModel, which exposes decision_function and deterministic labels but deliberately refuses probabilities.
    A["SKDataView<br/>Dense or CSR, zero-copy"] --> B["SKLinearSvcDesign::dispatch<br/>(one match, once per operation)"]
    B --> C["SKDenseLinearSvcDesign<br/>row dot · add_scaled_row · ||x_i||²"]
    B --> D["SKSparseLinearSvcDesign<br/>stored entries only"]
    C --> E["Dual coordinate descent<br/>α ∈ Rⁿ · w ∈ Rᵖ⁺¹"]
    D --> E
    E --> F["Intercept recovery<br/>1-D bisection for fixed weights"]
    F --> G["One-vs-rest heads<br/>parallel when the plan allows"]
    G --> H["SKLinearSVCModel<br/>decision_function · predict_labels"]
    H --> I["predict_probabilities<br/>UnsupportedOperation, by design"]
    classDef input fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef design fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef solver fill:#fde68a,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef state fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#4c1d95
    classDef refusal fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    class A input
    class B,C,D design
    class E,F,G solver
    class H state
    class I refusal

1. The idea, from zero

Imagine two clouds of points on a sheet of paper. A linear classifier draws a straight line between them and labels a new point by which side of the line it falls on. Many lines separate the clouds; which one should we pick?

A support-vector machine picks the line that leaves the widest empty corridor between the two clouds. That corridor is the margin. The line is described by a weight vector $w$ and an intercept $b$, and every training row $(x_i, y_i)$ with $y_i \in {-1, +1}$ would ideally satisfy

$$ y_i,(w^\top x_i + b) ;\ge; 1 . $$

The left side is the margin of row $i$: positive means “correct side”, and at least $1$ means “correct side, and outside the corridor”. Real data trespasses. We therefore trade the width of the corridor against the size of the trespass, with a knob $C$ that says how expensive a trespass is:

  • L1 hinge loss — every trespass costs $C$ per unit: $C \max(0,,1 - y_i f(x_i))$.
  • L2 squared hinge loss — the trespass is squared: $C \max(0,,1 - y_i f(x_i))^2$.

Squaring makes the loss differentiable and punishes large violations harder; it is the default of SKLinearSVC, matching LIBLINEAR’s default solver. Written as one primal problem,

$$ \min_{w,,b};; \tfrac12 \lVert w \rVert_2^2 ;+; C \sum_{i=1}^{n} \ell!\left(1 - y_i (w^\top x_i + b)\right). $$

The first term is the regularizer: it prefers short weight vectors, which is what makes the corridor wide. The second term is the data fit. Neither loss is differentiable everywhere (or, for the hinge, anywhere at the kink), so the primal is not a job for gradient descent. The dual is.

The dual, and why it is a gift for sparse data

Introduce one non-negative multiplier $\alpha_i$ per training row. The dual of the problem above is

$$ \min_{\alpha};; \tfrac12 \alpha^\top Q \alpha - \mathbf{1}^\top \alpha \quad\text{subject to}\quad 0 \le \alpha_i \le C ;;(\text{L1}), \qquad \alpha_i \ge 0 ;;(\text{L2, shifted}), $$

where the matrix entry is the pairwise inner product of signed rows,

$$ Q_{ij} = y_i, y_j, x_i^\top x_j . $$

For the squared hinge, the diagonal carries an extra shift $D_{ii} = 1/(2C)$ — the dual is strictly convex even when rows are duplicated. And the weight vector is not solved for at all: it is reconstructed exactly from the multipliers,

$$ w = \sum_{i=1}^{n} \alpha_i, y_i, x_i . $$

Notice what is not here. There is no Gram matrix materialized: the solver only ever needs $Q_{ii}$ (one squared row norm) and, through $w$, one inner product per row. Notice also what the dual buys us for sparse data: a row with four stored entries costs four multiply-adds per sweep, not ten thousand.


2. Coordinate descent: one multiplier at a time

The dual is a box-constrained quadratic program with $n$ variables. A general QP solver would need the matrix; coordinate descent never builds it. Each sweep visits every coordinate $i$ and solves the one-dimensional problem exactly, holding all other $\alpha_j$ fixed:

$$ \alpha_i ;\leftarrow; \operatorname{clip}!\left(\alpha_i - \frac{G_i}{Q_{ii} + D_{ii}},, 0,, U_i\right), $$

where $U_i = C \cdot \text{weight}i$ for the hinge loss, $U_i = \infty$ for the squared hinge, and $D{ii}$ is the squared-hinge shift (zero for the hinge). The state maintained between updates is just $w$, so the gradient component is cheap:

$$ G_i = y_i, w^\top x_i - 1 + \alpha_i D_{ii}. $$

The update is projected because a multiplier may not leave its box. The solver never updates a coordinate that is already pinned at a bound and pushed further out: it first forms the projected gradient

$$ PG_i = \begin{cases} \min(G_i, 0) & \alpha_i = 0,\ \max(G_i, 0) & \alpha_i = U_i,\ G_i & \text{otherwise}, \end{cases} $$

and only moves when $|PG_i|$ is non-zero. A full sweep’s stopping statistic is

$$ \max_i |PG_i| . $$

When it falls below the configured tolerance, the dual has converged; when the sweep budget maximum_number_of_iterations runs out first, fit returns the central NotConverged { iterations } error instead of pretending the model is done. Both rules are visible in crates/sciencekit_svm/src/linear_svc/solver.rs:

#![allow(unused)]
fn main() {
let gradient = labels[row] * design.row_dot(row, &coefficients) - F::one()
    + dual[row] * diagonal_shift;
let projected_gradient = if dual[row] <= F::zero() {
    gradient.min(F::zero())
} else if dual[row] >= upper_bound {
    gradient.max(F::zero())
} else {
    gradient
};
maximum_projected_gradient = maximum_projected_gradient.max(projected_gradient.abs());
}

Two properties matter beyond correctness. First, determinism: the multipliers start at zero, coordinates are visited in index order, and no randomness enters, so repeated fits on the same data are bit-identical. Second, memory: the solver holds an $O(n)$ dual vector and an $O(p)$ coefficient vector. For the acceptance fixture of $20,000$ rows and $10,000$ features that is about $234$ KiB of solver state, not the $1.6$ GB a dense design would need.

The convergence tail is honest

Coordinate descent slows down when the design has nearly duplicate columns, because the matrix $Q$ becomes ill-conditioned. On a perfectly separable dataset the multiplier vector also keeps creeping toward its limiting optimum, so a very strict absolute tolerance can take thousands of sweeps even though the boundary has been right for hundreds of them. SKLinearSVC does not hide this: the tolerance and the sweep budget are both on the builder, and exhausting the budget is an explicit NotConverged { iterations }. The acceptance suite therefore sets tolerance(1e-2) where its accuracy target needs no more precision, exactly as LIBLINEAR exposes the same knob as -e.

The rule deserves one blunt warning: the tolerance is absolute, not relative to the data. The solver compares $\max_i |PG_i|$ directly against tolerance, so features with large magnitudes produce large gradients no matter how close the boundary already is. On unscaled data with a large offset, the default $10^{-4}$ can be unreachable within the sweep budget and fit returns NotConverged even though the classifier is already accurate. The remedy is to scale the features first — SKStandardScaler centers and standardizes each column, which also removes the offset that made the intercept hard to learn — not to loosen the tolerance until the error disappears.

Shrinking: the road not taken

LIBLINEAR accelerates sweeps by shrinking: rows whose multipliers are pinned at a bound and whose projected gradient is comfortably inward are removed from the active set, and only re-activated when the remaining coordinates move enough to matter. It is a real optimization. SKLinearSVC deliberately does not implement it yet. The design brief is a deterministic, readable reference solver with one code path shared by dense and CSR designs; an active set would add a second convergence rule and a re-activation policy to get right, and the NotConverged contract already makes slow convergence visible rather than silent. The coefficient and dual updates are written so an active-set layer can be added on top without touching the math.


3. The data boundary: one design, no densification

Dense and sparse inputs differ in how a row is stored, not in what a row dot means. The solution is a small trait with three row-level operations, SKLinearSvcDesignAccess, and two implementations:

operationdense designCSR design
row_dotrow.dot(coefficients)fold over stored (column, value) pairs
add_scaled_rowadd scale · row elementwiseadd scale · value at each stored column
row_norm_squaredrow.dot(row)sum the squares of the stored values

SKLinearSvcDesign::dispatch performs the representation match once per operation and rejects CSC with a precise UnsupportedRepresentation { representation: "csc", .. } suggesting a conversion to CSR. From that point on the solver talks to the trait and never branches on representation again. The CSR implementation in crates/sciencekit_svm/src/linear_svc/design.rs is the whole sparse contract:

#![allow(unused)]
fn main() {
fn row_dot(&self, row_index: usize, coefficients: &[F]) -> F {
    let stored = self.features.outer_view(row_index).expect("row index bounded");
    let dot = stored.indices().iter().zip(stored.data().iter())
        .fold(F::zero(), |accumulator, (&column, &value)| {
            accumulator + coefficients[column] * value
        });
    if self.has_intercept { dot + coefficients[self.number_of_columns()] } else { dot }
}
}

The companion test sparse_fit_scans_stored_entries_only_on_a_matrix_too_wide_to_densify in linear_svc_representation_tests.rs makes the guarantee observable: it fits $40$ rows by $4,000,000$ columns — $1.28$ GB if densified, a few stored entries per row in reality — and recovers every training label. If any code path tried to densify, the test would run out of memory instead of passing.

The intercept is the one place where the two views share a trick. When include_intercept(true), every row is conceptually augmented with a constant $1$; the dense design appends the intercept coefficient to the dot product, and the sparse design does the same after folding its stored entries. The branch happens in the accessors, not in the solver loop.

The intercept: an augmented column, re-optimized at the end

The dual’s coordinate loop treats the augmented constant column as an ordinary feature: every row implicitly gains a $1$, $Q_{ij}$ gains a $+1$ term and the diagonal becomes $\lVert x_i\rVert^2 + 1$. That keeps one update rule valid for every coordinate, but it has a consequence worth stating plainly: the intercept is regularized too. The same $\tfrac12\lVert w\rVert^2$ term that shrinks the feature weights also shrinks the augmented coefficient, so the dual solve produces a penalized intercept, not an unpenalized bias. (LIBLINEAR’s default -B -1 excludes the bias from the regularizer through a different formulation; this implementation uses the augmented, regularized design instead.)

After the dual has converged, sk_recover_linear_svc_intercept re-optimizes $b$ for the weights it already has. With $w$ fixed, the weighted training objective is a convex function of the single scalar $b$:

$$ \sum_i \text{weight}_i \cdot \ell!\left(1 - y_i (w^\top x_i + b)\right), $$

and its derivative is monotone. The code bisects that derivative over the interval spanned by the breakpoints $y_i (1 - y_i w^\top x_i)$ for one hundred steps, then stores the midpoint as the intercept. For the hinge loss the derivative steps between slopes; for the squared hinge it is continuous. Either way, bisection lands on the loss-minimizing intercept for the fixed weights the dual produced; it does not undo the regularization that shaped $w$, so the resulting pair is not the minimizer of a primal objective with a truly unpenalized bias. The test intercept_is_recovered_for_the_two_point_problem shows the symmetric two-point problem coming out with $w = 1$ and $b = 0$ — a case with no offset, where the distinction between the two formulations does not bite.

This is why scaling the data matters. The augmented column always has magnitude $1$, while the feature columns can have any magnitude, so the relative cost of the intercept depends on the feature scale. On unscaled data with a large offset, the intercept is both harder to learn and more heavily distorted, and the absolute stopping rule can end in NotConverged; centering and standardizing the columns first (with SKStandardScaler) makes the intercept small and the problem well conditioned.


4. More than two classes: one-vs-rest, in parallel

The dual solver is binary. For $c > 2$ classes, SKLinearSVC fits one binary head per class, labelling that class $+1$ and every other class $-1$; this is one-vs-rest. Each head gets its own coefficient vector and intercept, keeps the class weights of the training rows it sees, and is independent of the others. Independence is what makes parallelism safe:

#![allow(unused)]
fn main() {
let heads = if plan.parallelism > 1 {
    head_labels.par_iter().map(fit_head).collect::<Result<Vec<_>, SKError>>()?
} else {
    head_labels.iter().map(fit_head).collect::<Result<Vec<_>, SKError>>()?
};
}

plan.parallelism comes from the shared execution planner, so the same estimator adapts to the machine and the dataset size. Rayon’s indexed parallel iterator preserves the order of head_labels, so head $j$ is always the head for canonical class $j$ regardless of how many threads ran. A binary problem is the special case with a single head whose positive side is the larger canonical class index.

Prediction turns the heads into one decision matrix with shape (rows, classes): column $j$ is head $j$’s margin for multiclass models, and binary models expose the mirrored pair [-d, d] so the argmax is well defined over two columns. Labels are the argmax of each row, and ties break toward the smallest canonical class index because the fold only replaces the winner on a strictly larger value:

#![allow(unused)]
fn main() {
row.iter().enumerate().skip(1).fold(0usize, |winner, (index, &value)| {
    if value > row[winner] { index } else { winner }
})
}

The test decision_ties_break_by_the_smallest_canonical_class_index overwrites three heads with equal intercepts and a hand-built tie, and asserts that class $0$ wins every row.

Probabilities: an explicit refusal

A margin is a signed distance, not a probability. Turning one into the other requires a calibration step fitted on held-out scores — the Platt scaling and pairwise coupling that SKSVC performs when built with probability(true). SKLinearSVC has no such calibration, and rather than fabricate a distribution it returns UnsupportedOperation { operation: "predict_probabilities", .. } with a reason naming calibrated alternatives. Two companion tests cover the binary and multiclass cases (probabilistic_prediction_is_rejected_with_guidance and probabilistic_prediction_is_rejected_for_multiclass_models_too).


5. The public surface

Everything is reached through the builder; the constructor stays private.

objectroledefaults
SKLinearSVC<F>estimator; build() starts the builder—
SKLinearSVCBuilder<F>C, loss, class_weight, include_intercept, tolerance, maximum_number_of_iterations, backend, execution_mode1.0, SquaredHinge, None, true, 1e-4, 1000, Faer, Automatic
SKLinearSVCLossHinge or SquaredHingeSquaredHinge
sk_linear_svc_loss_from_code(u8)binding-facing loss discriminator (0/1), fails closed—
SKLinearSVCHead<F>one head’s coefficients, intercept and iteration count—
SKLinearSVCModel<F>fitted model: class table, heads, loss, C, feature count, backend—

SKLinearSVCModel implements SKClassifierPredictor: predict_labels returns the canonical class index per row, and predict_probabilities refuses. Its inherent decision_function returns the (rows, classes) margin matrix. Every public operation runs inside an observability span built from the configured backend and execution_mode, and fit transfers both into the model — the backend is a runtime value on the builder, exactly as the backend-selection spec requires, never a type parameter.

SKLinearSVC reuses the crate’s existing SKClassWeight policy (None, Balanced, Explicit, LabelMap). The weight multiplies that class’s box capacity $U_i = C \cdot \text{weight}_i$ and its diagonal shift $(2C,\text{weight}_i)^{-1}$, which is the standard class-weighted linear SVC: upweighting a rare class makes trespass on that class more expensive.


6. Walking the executable specification

The companion tests double as the contract. Read them in this order:

Configuration — linear_svc_builder_tests.rs checks every default and every rejected hyperparameter; linear_svc_config_tests.rs checks the default squared hinge, explicit hinge, the binding loss codes and all class-weight policies.

Design — linear_svc_design_tests.rs hand-computes an augmented row dot and a scaled-row accumulation, then proves dense and CSR designs agree on the same logical matrix and that CSC is rejected.

Solver — linear_svc_solver_tests.rs starts from a two-point problem whose dual optimum lies on a box boundary (hinge_dual_update_reaches_the_hand_computed_two_point_optimum asserts w = 1), shows that a tighter tolerance needs more sweeps (projected_gradient_stopping_rule_makes_tolerance_monotone), checks the recovered intercept, compares both losses on one separable fixture (hinge_and_squared_hinge_converge_on_the_same_separable_fixture), and proves that a one-sweep budget reports NotConverged { iterations: 1 }.

Estimator — linear_svc_fit_tests.rs fits separable and overlapping binary problems and the no-intercept case; linear_svc_multiclass_tests.rs asserts three and four heads, that each head scores its own class highest, and that repeated fits are identical; linear_svc_predict_tests.rs checks decision-matrix shapes, argmax consistency, ties and the probability refusal; linear_svc_weights_tests.rs proves that Balanced moves the boundary, that explicit unit weights reproduce the unweighted model exactly, that upweighting changes the fit, and that a label map resolves to the same coefficients as explicit weights.

Boundary and robustness — linear_svc_representation_tests.rs compares dense and CSR fits and predictions and runs the too-wide-to-densify fixture; linear_svc_validation_tests.rs pins every central error variant, including the ShapeMismatch dimensions; linear_svc_concurrency_tests.rs repeats fits, runs eight threads against one Arc<SKLinearSVCModel>, and statically asserts Send + Sync.

Acceptance — linear_svc/acceptance_tests/ covers two-row and single-feature problems with both losses, a tiny multiclass problem, class weights, metric production through sciencekit_metrics (sk_accuracy_score, macro sk_f1_score), parallel-versus-single-thread head fitting under a one-thread rayon pool, dense-versus-sparse batch prediction, and the $20,000 \times 10,000$ sparse fixture with a planted signal per class.

The acceptance fixture numbers are worth reading closely: they were chosen after measuring the solver’s convergence tail. A design with ten nearly identical columns per class makes $Q$ ill-conditioned and pushes a strict $10^{-4}$ tolerance past the sweep budget, while one strong column per class plus sparse noise converges in tens of sweeps. That is not a hidden limitation; it is the well-known conditioning behaviour of coordinate descent, and it is why the tolerance belongs on the builder.


7. Roads not taken

  • Reusing the SMO solver from chapter 41. SMO keeps a working set of two kernel columns and a kernel cache. For a linear model with $50,000$ columns that cache is either useless (linear kernel rows are the data) or an $O(n^2)$ liability. Separate solver, shared crate.
  • Reusing the logistic-regression coordinate descent. The logistic objective, variable domain and stopping rule differ; sharing the code would couple sciencekit_linear_model to sciencekit_svm for no mathematical gain.
  • Converting CSR to CSC for column-wise scans. A copy does not remove the fact that every dual update is a row dot; it only adds memory traffic.
  • Crammer–Singer multiclass. A genuinely different formulation, deferred. One-vs-rest is the LIBLINEAR default and composes cleanly with per-class weights.
  • Probabilities from margins. Rejected on purpose; calibration is a separate fitted object.
  • memmap2 spilling and model export. Wave 7 work, recorded in the PRD alongside the same deferral for SKSVC/SKSVR.

The linear SVM completes the SVM block: kernel machines for curved boundaries on modest data, and a linear coordinate-descent workhorse for the wide, sparse, many-row problems where a Gram matrix was never an option.

Histogram gradient boosting: bins, histograms and leaves grown on the smaller child

Chapter 47 taught the boosting loop: fit a small tree to the negative gradient of the loss, replace each leaf with a Newton step, shrink the tree and add it to the running score. Its split finder, inherited from the exact CART implementation in sciencekit_tree, pays a steep price at every node: it sorts each candidate feature again, so one tree costs roughly $O(\text{number_of_nodes} \times \text{number_of_features} \times n \log n)$.

For a few thousand rows that is fine. For a few hundred thousand it is not, and it also gets in the way of two things tabular data needs: missing values and categorical columns. This chapter follows the implementation in crates/sciencekit_ensemble/src/histogram_boosting/ that solves all three problems at once — the LightGBM recipe: bin every feature once, search splits with histograms, grow the tree leaf-wise, and represent categorical partitions with a bit mask.


1. The idea in one sentence

If a numeric feature is compressed to at most 255 bins, then a split decision only needs the sums of gradients, Hessians and row counts in each bin — and those sums can be shared between a parent and its children instead of being recomputed.

Two consequences follow immediately:

  1. Split search becomes linear in the number of bins, not in the number of rows.
  2. A node’s histogram is cheap to update: accumulate the smaller child directly and subtract it from the parent to obtain the larger child.
flowchart TB
    accTitle: Why binning turns split search into histogram arithmetic
    accDescr: Raw rows are sorted once and mapped to compact bin identifiers. Each node then sums gradients and Hessians per bin in parallel across features. A prefix scan evaluates every boundary, and the best gain becomes a split. Children reuse the parent histogram by subtraction.
    subgraph RAW["Raw training data"]
        R1["row 0: x = 3.71, y = 1"]
        R2["row 1: x = missing, y = 0"]
        R3["row 2: x = 8.02, y = 1"]
    end
    subgraph BIN["Binned once — u8 per cell"]
        B1["bin 3"]
        B2["bin 255 = missing"]
        B3["bin 41"]
    end
    subgraph HIST["Node histogram"]
        H1["G, H, count per bin<br/>parallel across features"]
    end
    subgraph GAIN["Prefix scan"]
        G1["gain = G_L²/(H_L+λ)<br/>+ G_R²/(H_R+λ)<br/>− G²/(H+λ)"]
    end
    RAW --> BIN --> HIST --> GAIN
    GAIN --> SPLIT["Best split condition"]
    SPLIT --> SMALL["Accumulate the smaller child"]
    SPLIT --> SUB["Larger child = parent − smaller"]

    classDef raw fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef bin fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef hist fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef gain fill:#fae8ff,stroke:#c026d3,stroke-width:2px,color:#701a75
    classDef split fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#881337
    classDef small fill:#ffedd5,stroke:#ea580c,stroke-width:2px,color:#7c2d12

    class R1,R2,R3 raw
    class B1,B2,B3 bin
    class H1 hist
    class G1 gain
    class SPLIT split
    class SMALL,SUB small

2. Binning a column from zero

A bin is just a small integer identifier. Instead of remembering 3.71, the model remembers “bin 3”. Binning is built in binning/edges.rs by SKNumericBinning::derive:

  1. Collect the finite values of a column. NaN is the missing marker and is skipped here.
  2. If the column holds more than 200 000 values, keep every k-th value so the sample stays deterministic. This is quantile sketching in its simplest honest form: the sample is fixed by position, never by a random draw, so two fits on the same column derive the same edges.
  3. Sort the sample and pick maximum_bins - 1 equally spaced quantile positions as interior edges, dropping duplicates.
  4. bin(value) is a binary search (partition_point) over the edges. A NaN returns the reserved missing_bin, which is always maximum_bins.

The contract is deliberately small and testable. hist_binning_derives_at_most_maximum_bins checks that 1 000 distinct values with maximum_bins = 16 produce at most 16 bins and preserve order. hist_binning_routes_missing_to_dedicated_bin checks that NaN never collides with an observed value, and hist_binning_is_deterministic derives two binnings from 10 000 values and compares the edges exactly.

SKBinnedDataset in binning/dataset.rs applies this per feature and stores the result column-major: feature f owns one contiguous block of number_of_rows u8 cells. Column-major storage is the key to the next section — a histogram over a node’s rows walks one compact block per feature, which parallelizes cleanly across features.

Categorical features take a different branch. SKFeatureBinning::categorical records the observed integer codes in ascending order, truncates them to maximum_bins - 1 (leaving room for an unknown category bin), and maps each code to its position. A code never seen during fit maps to unknown_bin = categories.len(). Because the mapping stores membership, not an ordinal distance, category 30 is not “bigger” than category 10.

Sparse inputs are binned from their stored entries plus the implicit observed zero. The absent coordinates are never materialized as a dense row; hist_dataset_does_not_densify_sparse_input builds the same logical design densely and as CSR and compares the resulting bin vectors and edges.


3. Histograms, gain and the prefix scan

histogram/accumulate.rs turns the binned dataset into a node histogram. For every feature it keeps three vectors indexed by bin:

  • gradient_sums[bin] — the sum of negative gradients −g;
  • hessian_sums[bin] — the sum of second derivatives h;
  • counts[bin] — the number of node rows in that bin.

sk_accumulate_histogram maps each feature to its own rayon task and walks the node’s row indices once. hist_accumulate_sums_gradients_and_hessians_per_bin checks a four-row hand computation: one row per bin, gradient sums 1, 2, 3, 4, total gradient 10. hist_accumulate_respects_the_row_subset then accumulates only rows {1, 3} and verifies that the totals follow the subset, not the whole table.

The split objective is the Newton gain already used by Chapter 47’s leaf values:

$$ \text{gain} = \frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{G^2}{H + \lambda}. $$

sk_split_gain in histogram/gain.rs is that formula. Because the bins are ordered by value, a single left-to-right scan can maintain prefix G, H and count and evaluate every boundary. Each candidate is rejected when either side has fewer than minimum_samples_leaf rows or when its gain is not strictly positive. hist_gain_matches_hand_computed_split uses gradients 1, 1, -1, -1 and unit Hessians to show that boundary 1 wins with gain 4. hist_gain_applies_l2_regularization checks the $\lambda$ term, and hist_gain_rejects_splits_below_minimum_samples_leaf shows that raising the minimum to three rows removes every boundary.


4. Subtracting a parent histogram

The naive way to split a node is to accumulate both children from scratch. That repeats work on every row. The histogram variant instead accumulates the smaller child and derives the larger one as parent − smaller: gradients, Hessians and counts all subtract cell by cell.

sk_subtract_histogram in histogram/subtract.rs performs that subtraction. hist_subtract_equals_direct_accumulation computes the same larger child twice — once by direct accumulation and once by subtraction — and checks every bin’s counts, gradient sums and Hessian sums within 1e-12. This is the test that keeps the bookkeeping honest: subtraction is an optimization only if it produces the same numbers.


5. Leaf-wise growth instead of depth-first growth

Exact CART grows depth-first: split the left child, then its left child, and so on. Histogram boosting grows leaf-wise: every leaf with a valid split becomes a candidate in a priority list, and the leaf with the best gain splits next. This is growth/leaf_wise.rs.

The algorithm is short enough to follow:

  1. Accumulate the root histogram and its best candidate split; the root starts as a pending leaf.
  2. Pick the pending leaf whose own best candidate gain is largest. Ties resolve by lower node index, so the result does not depend on iteration order.
  3. For every leaf that is created, scan the selected features. Feature subsampling (maximum_features) is seeded from random_seed and the node index, and the sampled indices are sorted so the scan order is stable. The resulting candidate travels with the leaf, so the priority list never ranks a child by the gain that produced it.
  4. If no split is valid, the leaf keeps its Newton value.
  5. Otherwise partition rows by the split condition, accumulate the smaller child, subtract the larger child, store both children as leaves and push them onto the pending list.
  6. Stop when the number of leaves reaches maximum_leaf_nodes or no pending leaf splits.

The tree itself is a flat array in growth/tree.rs. SKHistogramNode<F> stores either a leaf value or a split condition plus the indices of its two children. SKHistogramTree::leaf_value_for walks that array with a closure that returns the bin of one feature — exactly the shape prediction needs.

hist_growth_splits_the_highest_gain_leaf grows the four-row example into three nodes: a root with split maximum_bin = 1 and leaf values +1 and −1, with a normalized importance of 1.0 on the only used feature. hist_growth_splits_the_leaf_with_the_largest_own_gain is the ordering guard: the root splits after bin 3, its left child can still improve by 0.75 and its right child by 2.0, so with a budget of three leaves the right child must be the one split. hist_growth_respects_the_maximum_leaf_budget grows 16 alternating rows with a budget of three leaves and checks that the tree stops at exactly three leaves and five nodes. hist_growth_creates_a_leaf_node_without_a_split pins down the leaf constructor.


6. Categorical splits are membership masks, not thresholds

A numeric split asks $\text{bin} \le \text{maximum_bin}$. A categorical split cannot: {10, 30} versus {20} is not an interval. sk_scan_categorical_feature in histogram/categorical.rs therefore:

  1. Sorts the observed category bins by their gradient-to-Hessian ratio $G / (H + \lambda)$.
  2. Scans prefix partitions of that ordering, evaluating the same gain formula.
  3. Stores the winning left set as a BitVec<u8, Lsb0> with one bit per observed category bin.
  4. Sends the unknown-category bin to the right, a documented direction that never panics.

hist_categorical_partitions_categories_by_gradient_ratio builds gradients $3, -4, 3$ over categories ${10, 20, 30}$ and asserts that the winning mask has bits 0 and 2 set, bit 1 clear, and gain $98/3$. hist_categorical_respects_minimum_samples_leaf shows that requiring two rows per side leaves only three rows and removes every partition.

At prediction time SKHistogramTree reads the membership bit for the query’s category bin. A query category absent from the fitted list maps to unknown_bin, falls outside the mask and follows the documented right direction. hist_growth_routes_an_unknown_category_away_from_the_left_mask builds the minimal categorical tree by hand and checks both sides of that traversal: the unknown bin and a masked-out observed category reach the right leaf, while a masked-in category reaches the left one.


7. Missing values learn a direction

The dedicated missing bin is included in every numeric scan, in both possible directions. For a given boundary the scan evaluates “missing rows go left” and “missing rows go right”, keeps the larger gain and stores the winner as default_left. Prediction checks the bin first: a bin equal to missing_bin follows default_left; every other bin follows the ordinary $\text{bin} \le \text{maximum_bin}$ rule.

hist_missing_learns_the_left_direction and hist_missing_learns_the_right_direction construct gradients that make each direction strictly better and then assert that a missing query reaches the same leaf as the corresponding side. hist_missing_without_missing_rows_uses_deterministic_direction shows the tie-breaking rule: with no missing rows both directions have the same gain, the scan keeps the first candidate, and the learned direction is deterministically “right” (default_left = false).


8. Boosting on top of the same loss contract

The booster does not re-implement losses. stage.rs asks the existing SKGradientLoss trait for negative_gradient and hessian, grows a histogram tree, then adds $\text{learning_rate} \times \operatorname{tree}(x)$ to every row’s raw score. hist_stage_applies_a_hand_computed_newton_update fits a single stage to targets $0, 0, 1, 1$ with squared error: the initial prediction is $0.5$, the two leaves are $-0.5$ and $+0.5$, and with learning rate $0.1$ the raw scores become $0.45, 0.45, 0.55, 0.55$.

The scalar loop in scalar_loop.rs and the multiclass loop in multiclass_loop.rs reuse the existing gradient-boosting pieces:

  • sk_initialize_scalar_scores / sk_initialize_multiclass_scores for the constant start;
  • SKEarlyStoppingMonitor for patience and best-stage restoration;
  • sk_split_regression_validation_rows / sk_split_classification_validation_rows for the seeded held-out split;
  • sk_select_stage_rows for without-replacement row subsampling.

Every stage recomputes the negative gradients and Hessians from the current raw scores, for both the scalar and the multiclass loops; reusing the initial scores would refit the same trees forever. hist_multiclass_refreshes_gradients_between_stages compares the first two stage trees of every class and fails if the second stage simply repeats the first. The same subsample fraction is drawn per stage and per class before growth, and hist_multiclass_applies_row_subsampling checks that the root of a 0.5-subsampled multiclass tree holds fewer than all training rows.

Early stopping is on by default with patience 10, exactly as the specification’s default scenario requires. hist_early_stop_reports_the_fitted_iteration_count fits a constant target and shows the model keeps only the single best stage even though 20 were allowed. hist_early_stop_disabled_fits_every_iteration checks that without_early_stopping fits all seven requested stages, hist_early_stop_keeps_every_stage_when_no_validation_split_is_possible covers the three-row, three-class case where no stratified hold-out exists and all five stages must survive, and hist_early_stop_is_seed_deterministic fits the same seeded configuration twice and compares the reported stage count.

Prediction bins each raw query row on the fly through the stored SKFeatureBinning, so no binned matrix has to be stored or rebuilt. Dense rows read their cells; CSR rows read only stored entries and treat absent coordinates as the observed zero. Both go through the same model code.


9. The public surface

ObjectRole
SKHistGradientBoostingClassifier<F> / SKHistGradientBoostingRegressor<F>Configured estimators, built only through their builders
SKHistGradientBoostingClassifierBuilder<F> / SKHistGradientBoostingRegressorBuilder<F>Mandatory builders with backend(SKBackendKind) defaulting to Faer and execution_mode defaulting to Automatic
...ClassifierModel<F> / ...RegressorModel<F>Fitted models exposing stage trees, initial predictions, learning rate, bin edges, categories, feature importances and fitted iteration count
SKHistGradientBoostingRegressionLossSquaredError (default) or AbsoluteError
SKNumericBinning<F>, SKFeatureBinning<F>, SKBinnedDataset<F>Quantile edges, category mapping and the column-major u8 store
SKHistogramTree<F>, SKHistogramNode<F>Flat histogram tree and binned traversal
SKHistogramSplit, SKHistogramSplitCandidate<F>Numeric and categorical split conditions with their gain
sk_accumulate_histogram, sk_split_gain, sk_scan_numeric_feature, sk_scan_categorical_feature, sk_subtract_histogram, sk_grow_histogram_treeFree-scope building blocks used by the stages

Defaults follow the specification: 100 iterations, 255 bins, 31 leaves, at least 20 samples per leaf, no categorical features, early stopping with 10 non-improving iterations, Faer, Automatic.


10. Decisions and roads not taken

  • Column-major instead of row-major. Row-major would make row-wise prediction slightly more direct, but histogram accumulation visits one feature at a time across a node’s rows. Column-major wins for the hot loop; prediction bins a single row on the fly and does not need a stored matrix.
  • Recompute exact CART? No. The exact splitter in sciencekit_tree remains available for users who need thresholds on raw values. The histogram booster reuses the tree conventions but has its own u8-bin node type, because categorical masks and missing directions cannot be expressed by a single numeric threshold.
  • One u8 per cell, not per-feature dynamic lengths. A shared stride of maximum_bins + 1 keeps indexing trivial and the storage compact. A feature with fewer distinct values simply leaves empty bins, which the scan rejects through the sample-count constraint.
  • Deterministic sampling, not random quantile sketches. The column sample is a fixed stride and the row subsample is a seeded draw without replacement, so repeated fits and different thread counts produce identical trees. hist_determinism_repeated_fits_agree, hist_determinism_is_thread_count_invariant and hist_determinism_concurrent_prediction_agrees stand guard over that promise.
  • memmap2 streaming, monotonic/interaction constraints and export are deliberately deferred. The in-memory binned store is the first implementation; a future memory-mapped store replaces it behind the same binning interface. docs/PRD.md §8.8 records the deferral.

11. Walking the companion tests

The executable contract lives beside the implementation, in *_tests.rs modules:

  • binning/binning_tests.rs — hist_binning_derives_at_most_maximum_bins, hist_binning_routes_missing_to_dedicated_bin, hist_binning_is_deterministic.
  • binning/dataset_tests.rs — hist_dataset_stores_columns_with_u8_bins, hist_dataset_maps_categories_and_unknown_bin, hist_dataset_rejects_out_of_range_maximum_bins, hist_dataset_does_not_densify_sparse_input.
  • histogram/accumulate_tests.rs, gain_tests.rs, subtract_tests.rs, categorical_tests.rs — the hand-computed sums, the gain formula, subtraction equivalence and the bit-mask partition.
  • growth/growth_tests.rs, missing_tests.rs — the hand-computed growth sequence, the leaf budget and both learned missing directions.
  • classifier_tests.rs, regressor_tests.rs, early_stopping_tests.rs, multiclass_loop_tests.rs — defaults, binary, multiclass, squared/absolute error, regularization, the fitted-iteration count, refreshed multiclass gradients and per-stage subsampling.
  • representation_tests.rs, validation_tests.rs, determinism_tests.rs — dense/CSR parity, every documented error, repeated-fit and thread-count determinism, concurrent prediction and Send + Sync.
  • acceptance_tests/{tiny_tests,large_tests,metric_tests}.rs — tiny designs, categorical and missing values, 50 000-row binary/multiclass/regression fits, and metric production through sciencekit_metrics (hist_acceptance_large_regression, hist_acceptance_produces_classification_and_regression_metrics).

Run them with:

cargo test -p sciencekit_ensemble hist_

OpenCL backend: command queues, kernels and honest device work

The GPU compute contracts chapter built a promise: SKDeviceInfo, SKDeviceCapabilities, SKGpuKernel, SKDeviceBuffer and SKFallbackReason describe what a device backend must look like, without any vendor runtime. This chapter delivers the first backend that keeps that promise on real hardware — OpenCL 3.0, reached through an ICD loader, behind the opencl feature of sciencekit_gpu and re-exported by the sciencekit_gpu_opencl package through its gpu-opencl feature.

Nothing here invents a second device vocabulary. The types this chapter describes are the contract types; the backend only adds the machinery that turns them into work on a device.

flowchart LR
    accTitle: One OpenCL operation from host array to verified result
    accDescr: A host matrix is copied into a device buffer, the program is compiled once and cached, the kernel is enqueued on the in-order command queue with its buffer arguments, the device executes it, and the output buffer is copied back to the host. The backend records the backend kind, the operation, the device and the bytes moved on the observability span.
    H["host array<br/>ndarray view"] -->|"upload (copy)"| B["device buffer<br/>cl_mem"]
    S["embedded OpenCL C source"] -->|"compile once,<br/>cache per device"| P["program + kernel"]
    B --> Q["command queue<br/>(in-order)"]
    P --> Q
    Q -->|"enqueue kernel"| D["device execution"]
    D --> O["output buffer"]
    O -->|"download (copy)"| R["host result<br/>ndarray"]
    Q -.->|"bytes moved"| T["span: backend=opencl,<br/>operation, device_index,<br/>transfer_bytes"]
    classDef host fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
    classDef device fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef plan fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef trace fill:#f3e8ff,stroke:#9333ea,stroke-width:2px,color:#581c87
    class H,R host
    class B,D,O device
    class S,P,Q plan
    class T trace

1. From zero: what a GPU actually asks of you

A graphics card is not a faster CPU that you call like a function. To make it compute you need five objects, and every OpenCL program is a story of moving data between them:

  1. A platform and a device. The ICD loader (libOpenCL.so.1 on Linux) is a small dispatcher that finds vendor drivers registered under /etc/OpenCL/vendors. Each driver reports platforms, and each platform reports devices — an NVIDIA GPU, an AMD GPU, an Intel integrated chip, even a CPU runtime. A device is what actually executes kernels; the crate describes it with SKDeviceInfo and SKDeviceCapabilities.
  2. A context. A context is the device’s little universe: buffers and programs created in it can only be used with that same device.
  3. A command queue. Work does not run when you “call” it; you enqueue commands — “write this buffer”, “run this kernel”, “read that buffer” — and the queue delivers them to the device. The backend creates an in-order queue, which is the simplest possible contract: commands complete in the order they were enqueued. That is why the code does not need explicit event waits before reading a result.
  4. A buffer. Device memory is separate from your process memory. A cl_mem allocation holds bytes on the card; to fill it you copy host data in (upload), and to see a result you copy it back (download). Those two copies are the cost that no kernel can hide, which is why the backend counts them.
  5. A program and a kernel. OpenCL C source is compiled at runtime on the target device by the vendor’s compiler, producing a program; a named function inside it is a kernel. The backend embeds its sources in the library, compiles each one once per device and caches the result, so a repeated dispatch pays no compile cost.

A kernel executes over a work range: one work item per output element. The pairwise kernel uses a two-dimensional range (one item per output pair); GEMM uses a two-dimensional range grouped into 16 × 16 tiles whose inputs are staged in local memory (memory shared by the work items of one group, much faster than global memory).

2. The decisions, and the roads not taken

  1. opencl3 0.12.0, pinned exactly. The spike compared the two maintained crates on this machine (RTX 3070 Ti Laptop GPU, clinfo reporting Platform #0: NVIDIA CUDA and libOpenCL.so.1, with no development symlink and no CL headers):

    • ocl 0.19.7 failed at link time with cannot find -lOpenCL: it links the development symlink, which a runtime-only install does not have.
    • opencl3 0.12.4 (the latest) failed the workspace MSRV: it uses Vec::len in a const context, which Rust 1.85 does not accept.
    • opencl3 0.12.0 compiles on Rust 1.85 and resolves to cl3 0.13.2, whose dynamic loader opens libOpenCL.so.1 at runtime. The spike kernel read back [2.0, 4.0, 6.0, 8.0] from the actual GPU.

    Road not taken: linking a vendor SDK at build time. It would make the default build require a GPU toolchain, break CI on machines without one, and contradict the contract crate’s promise of a runtime-free default.

  2. The implementation lives in sciencekit_gpu, behind opencl. The contract traits SKComputeBackend and SKDeviceDiscovery are defined there; a crate implementing them cannot also be a dependency of sciencekit_gpu — that is a package cycle. So the planned vendor-facing package sciencekit_gpu_opencl exists as a facade whose gpu-opencl feature enables sciencekit_gpu/opencl and re-exports the backend. It exposes no second contract: every type it exports is the sciencekit_gpu type.

  3. The kernel catalogue is carried, not partially advertised. Every enumerated device advertises all four kernels (PairwiseDistance, Gemm, Elementwise, TreePredict) because the backend implements all four. A device that cannot run one of them is a bug, not a capability gap, and the planner’s KernelNotSupported reason remains reserved for future backends.

  4. The safe path copies; the mapped path is not claimed. Mapped memory is reported in capabilities (host_unified_memory), but the backend’s declared transfer policy is SKDeviceTransferPolicy::Explicit and every transfer is a visible copy with accounting. Road not taken: mapping host memory into the device address space, which is faster on unified-memory parts but makes lifetimes and aliasing a per-vendor negotiation.

  5. Kernels are precision-generic sources, compiled per scalar type. The embedded source writes SK_REAL, replaced by float or double before compilation. One kernel file serves both precisions; f64 support is still gated by the device’s reported double_fp_config, and a device without it returns UnsupportedScalarType instead of silently computing in f32. The session caches each compiled program under a key carrying both the kernel name and the scalar type, so an f32 dispatch can never hand a later f64 dispatch the wrong program.

  6. The fallback backend always exists. SKOpenClBackend is compiled whether the feature is on or off. With the feature off it calls no OpenCL symbol, discover_devices returns an empty inventory and fallback_reason() returns Some(SKFallbackReason::NoDeviceAvailable). A call site can therefore be written once and still report the truth on a CPU-only build.

3. The public objects

ObjectWhereWhat it is
SKOpenClBackendcrates/sciencekit_gpu/src/opencl/backend/The backend. Built only through SKOpenClBackend::builder(). Implements SKDeviceDiscovery and SKComputeBackend<F>.
SKOpenClBackendBuilderbackend/builder.rsdevice_index(usize) pins one enumerated device, transfer_policy(...) chooses the policy, build() is strict, build_or_fallback() records the reason instead of failing.
SKOpenClDistanceMetricopencl/kernels/pairwise.rsSquaredEuclidean, Euclidean, Manhattan, Chebyshev.
SKOpenClBuffer<F>opencl/buffer/resident.rsA validated, device-resident matrix: shape, scalar type, device index and element count.
SKOpenClTransferReportbackend/implementation.rsupload_bytes, download_bytes, kernel_bytes and total_bytes().
sk_opencl_devicesopencl/device.rsStable enumeration of the ICD loader’s devices.
sk_register_opencl_device_inventoryopencl/device.rsRegisters the enumeration process-wide, so sk_resolve_operation_backend(OpenCl) selects a device.
SK_OPENCL_TREE_NODE_COLUMNSopencl/kernels/tree.rsThe six-column node layout the tree kernel documents.

The typed operations on the backend are upload_resident, download_resident, pairwise_distances, gemm, transform, combine and predict_trees. The shared contract methods (upload, download, dispatch) are also implemented: they accept and return the contract’s staged SKDeviceBuffer<F>, and therefore perform a genuine device round-trip (the staged buffer carries no runtime handle). Callers that can hold a SKOpenClBuffer<F> use the resident path and avoid re-uploading.

4. How the truth is kept: fallback and observability

flowchart TD
    accTitle: How the OpenCL backend decides between device work and an honest CPU fallback
    accDescr: The builder enumerates devices through the ICD loader. With the feature off the enumeration is empty without any OpenCL call. With the feature on, an empty inventory, a device that cannot be opened, a missing scalar precision or a failed kernel build all produce a structured error and the no-device reason. Only a successfully opened session runs kernels and records opencl on the span.
    A["SKOpenClBackend::builder()"] --> B{"feature enabled?"}
    B -->|no| C["empty inventory<br/>reason: no-device-available<br/>no OpenCL symbol called"]
    B -->|yes| D["enumerate platforms/devices"]
    D --> E{"device selected<br/>and context opened?"}
    E -->|no| C
    E -->|yes| F["session: context + queue + program cache"]
    F --> G{"scalar supported?<br/>kernel builds?"}
    G -->|no| H["structured error<br/>UnsupportedScalarType / Conversion<br/>(driver build log)"]
    G -->|yes| I["device work<br/>span backend=opencl"]
    classDef off fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef decide fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef on fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    class C,H off
    class B,E,G decide
    class D,F,I on

The API makes the decision impossible to ignore:

  • build() returns Err(SKError::DeviceUnavailable { backend: "opencl", reason }) when no device can serve the request.
  • build_or_fallback() returns a backend whose is_available() is false, availability() returns that same structured error, fallback_reason() returns Some(SKFallbackReason::NoDeviceAvailable) and every operation returns DeviceUnavailable. This is the shape planning wants: it can always hold a backend value and read the reason, instead of matching on a constructor failure.

Every public operation opens a span through SKOpenClBackend::operation_span(operation). An operation with an open session records backend = opencl, the operation name and — once known — device_index and transfer_bytes: a trace shows which device ran the kernel and how much data crossed the bus. An operation on a backend without a device never claims device work: it records the host fallback kind (faer) and the fallback_reason (no-device-available), exactly as sk_resolve_operation_backend does, and leaves the device index and byte count unset. The tests a_kernel_operation_records_backend_device_and_bytes and an_unavailable_operation_records_the_host_fallback_and_reason assert both halves.

5. The kernels, one by one

  • Pairwise distance (kernels/pairwise.rs): work item (column, row) computes output[row, column] from one left row and one right column. The metric is a kernel argument, so one compiled program serves all four metrics. Euclidean takes the square root inside the kernel; Chebyshev folds with fmax. Shape validation happens on the host before any buffer is touched.
  • GEMM (kernels/gemm.rs): a classic tiled kernel. Each 16 × 16 work group loads a tile of left and a tile of right into __local memory, synchronizes with barrier(CLK_LOCAL_MEM_FENCE), and accumulates. Global sizes are rounded up to whole tiles, and every read and the final write are bounds-checked — which is what makes unaligned sizes like 17 × 23 · 23 × 19 correct.
  • Elementwise (kernels/elementwise.rs): sk_elementwise_transform computes input · factor + offset; sk_elementwise_combine computes left + right. One work item per element.
  • Tree prediction (kernels/tree.rs): one work item walks one feature row from the root to a leaf. The tree is a dense matrix with six columns per node — feature index, threshold, left child, right child, leaf value, leaf flag — documented by SK_OPENCL_TREE_NODE_COLUMNS. The walk is bounded by a maximum depth so a malformed tree cannot hang the device.

A kernel failure is never silent: create_kernel compiles through the session’s program cache, and session::compile_program turns a failed build into SKError::Conversion("OpenCL program build failed with code ...: <driver build log>"). The test a_broken_program_reports_the_build_log asserts that the driver’s diagnostic text is part of the error.

6. Why transfers and memory checks matter

A GPU is not automatically faster. The cost of an operation is upload + kernel + download; for small matrices the copies dominate, and the correct answer is to stay on the CPU. The backend does not pretend otherwise: it makes the copies explicit, reports them through transfer_report(), and never claims a speedup. This is also why the resident path exists — upload once, dispatch many times — and why upload/download in the contract path are documented as the convenient, copying path.

Two guards keep failure structured rather than fatal:

  • SKOpenClAllocation::allocate compares the requested byte count with the device’s reported memory and returns DeviceUnavailable when the request cannot fit (some drivers otherwise over-commit virtual memory silently).
  • write_from_host rejects a payload larger than the allocation with ShapeMismatch. Together with scalar-type validation these are the buffer scenarios of the spec.

7. The companion tests, by name

The tests live beside the code and are the executable source of truth. On a host with an OpenCL device they run for real and print the device line; on a host without one they print a skip line — but they never fake a device.

  • opencl::device::device_tests::enumeration_is_stable_and_describes_opencl_devices — enumeration is stable, every entry is an OpenCL device, and the feature-off build enumerates nothing.
  • ...::an_empty_inventory_has_no_device_to_select — an empty inventory reports DeviceUnavailable, never a guessed device.
  • ...::selection_is_deterministic_and_honours_the_device_index — repeated selection agrees; an impossible index is rejected.
  • ...::registering_the_inventory_resolves_opencl_to_a_device — the shared resolver returns OpenCl with no fallback reason once the inventory is registered.
  • opencl::buffer::buffer_tests::buffers_round_trip_without_loss — f32 and f64 matrices come back bit-for-bit.
  • ...::an_oversized_allocation_reports_a_structured_error — a 32 TiB request is rejected against the device’s memory and an oversized payload is rejected against the capacity.
  • opencl::kernels::kernels_tests::pairwise_metrics_match_the_cpu_reference — all four metrics against a CPU reference on a 13 × 11 / 17 × 11 input.
  • ...::large_pairwise_matches_the_cpu_reference — 257 rows against 129 rows.
  • ...::single_precision_pairwise_matches_within_tolerance — the f32 tolerance (1e-3).
  • ...::one_backend_serves_both_precisions_of_the_same_kernel — an f32 dispatch followed by an f64 dispatch of the same kernel on one backend still matches the CPU.
  • ...::programs_are_cached_once_per_scalar_type — the same program is reused, and each precision owns a separate cache entry.
  • ...::gemm_matches_the_cpu_reference — 17 × 23 × 19, 64 × 96 × 32 and 129 × 47 × 65.
  • ...::elementwise_kernels_match_the_cpu_reference — affine transform and combination.
  • ...::tree_prediction_matches_the_cpu_reference — a hand-built five-row tree, including a tie on the threshold.
  • ...::a_broken_program_reports_the_build_log — a deliberately malformed source surfaces the compiler diagnostic.
  • opencl::backend::fallback_tests::a_backend_without_a_device_records_the_fallback_reason, ...::fallback_operations_report_structured_errors and ...::the_strict_builder_reports_the_reason — the fallback in both configurations.
  • ...::a_real_device_serves_the_contract_surface — upload, download and a GEMM dispatch through the shared contract buffers.
  • opencl::backend::concurrency_tests::concurrent_pairwise_dispatches_agree and ...::concurrent_transfers_agree — eight threads over one shared backend.
  • opencl::backend::observability_tests::a_kernel_operation_records_backend_device_and_bytes — the span records opencl, the operation, the device index and a positive byte count.
  • opencl::backend::fallback_tests::an_unavailable_operation_records_the_host_fallback_and_reason — a failed device attempt records the host fallback and no-device-available, never OpenCL device work it did not perform.
  • sciencekit_gpu_opencl::lib_tests::the_reexported_backend_runs_a_real_kernel — the facade package’s feature wiring drives a real GEMM.

8. Maintaining this chapter

When a kernel is added, extend SKGpuKernel, add its embedded source, add a typed operation and a CPU-parity test — and update this chapter’s kernel list and the test walk-through. When a new device backend arrives (CUDA, ROCm), it plugs into the same contracts and the same span fields; only the vendor runtime changes. Keep the rule from the contracts chapter intact: a backend either does the work on a device or reports, in a structured and observable way, why the CPU is doing it instead.

One export contract for every fitted model

This chapter explains how sciencekit gives every fitted model the same export surface — and a native import wherever the exported state is enough to rebuild the model — through one neutral schema that Safetensors, the JSON debug reader, ONNX and the language bindings can all consume without knowing a single estimator. It is written for a reader who has never used Rust or a numerical library, and every claim is grounded in the code and the companion tests.

Why one schema instead of one serializer per model

Imagine a library where every estimator invents its own file format. Saving a scaler requires one reader, saving a forest another, saving a pipeline a third, and every new estimator multiplies the formats. A format crate would have to know the private fields of every model, which breaks encapsulation, and each model would drift from the others.

The library therefore defines a format-agnostic contract in sciencekit_common::interop:

  • SKExportable<F> — a fitted model describes its learned state.
  • SKImportable<F> — a model rebuilds itself from that state.
  • SKModelState<F> — the state itself: metadata plus a deterministic map of named tensors.
  • SKModelMetadata — estimator name, format version, scalar dtype, feature count, optional class labels and typed hyperparameters.
  • SKTensor<F> — a named tensor with a data type, a shape and an owned payload (Floating, Integer or Boolean).

A format crate (Safetensors, JSON) only walks tensors(); it never imports an estimator. A model crate implements the two traits beside its model, so private fields stay private. This is the single most important decision of the change.

flowchart LR
  accTitle: Model export and import through one shared state
  accDescr: Scaler, linear and forest models export their state into a shared model-state object of metadata and named tensors, while a type-erased pipeline refuses export. The state is written by the safetensors and JSON debug writers, reserved for a future ONNX builder, and can be imported into a fresh model.
    subgraph Models["Model crates"]
        S["SKStandardScalerModel"]
        L["SKLinearRegressionModel"]
        F["SKRandomForestRegressorModel"]
        P["SKPipelineGraphModel"]
    end
    S -->|export_state| State
    L -->|export_state| State
    F -->|export_state| State
    P -->|export_state| Refusal["UnsupportedOperation<br/>type-erased stages"]
    State["SKModelState&lt;F&gt;<br/>metadata + named tensors"]
    State -->|tensors| SF["Safetensors writer"]
    State -->|tensors| JS["JSON debug writer"]
    State -->|tensors| ONNX["ONNX builder (future)"]
    State -->|import_state| S2["fresh model"]

Stable dotted names and versioning

Every tensor name is a dotted path: the first segment is a short scope and the remaining segments name the learned field. Real examples from the code:

standard_scaler.mean
standard_scaler.scale
minmax_scaler.minimum
one_hot.category_counts
linear.coefficients
ridge.coefficients
knn.training_dense
svm.dual_coefficients
tree.nodes.threshold
forest.tree.0.t.tree.nodes.value
gradient_boosting.stage.0.nodes.value

The names are a compatibility promise. Renaming a tensor, changing its shape or changing its meaning requires bumping SK_MODEL_FORMAT_VERSION in crates/sciencekit_common/src/interop/shared.rs. Every importer calls sk_validate_import_metadata before reading a tensor, so a foreign estimator name or a different version is rejected as UnsupportedRepresentation, never half-imported. The shared round-trip helper sk_assert_export_round_trip exports twice and refuses any state whose second export differs: export must be read-only and deterministic.

How a sparse model survives a round trip

A sparse training design must never be silently densified. The neighbor and SVM helpers encode a CSR matrix as its indptr/indices/data triple and record training_representation = "csr" (or support_vector_representation) in the metadata. Import rebuilds a CSR matrix and asserts the representation. The test knn_regressor_keeps_a_sparse_design_sparse in crates/sciencekit_neighbors/src/classifier/export_tests.rs fits on CSR, round-trips and checks training_representation() == "csr" before comparing predictions.

flowchart TB
  accTitle: A sparse design round-trips through export and import without densifying
  accDescr: A CSR design is exported into metadata that records the sparse representation plus integer and float tensors. Importing that state rebuilds the CSR design and never converts it to a dense matrix.
    CSR["CSR design<br/>indptr · indices · data"] --> Export["export_state"]
    Export --> Meta["metadata:<br/>representation = csr"]
    Export --> Tensors["integer/float tensors"]
    Meta --> Import["import_state"]
    Tensors --> Import
    Import --> CSR2["CSR design (never densified)"]

Metadata carries the configuration

A model must reconstruct not only its numbers but its behavior. Metadata carries the estimator name, the format version, the scalar dtype, the feature count, class labels in canonical index order, and typed hyperparameters through SKParameterValue (bool, integer, float, string, list). Examples from the code: the standard scaler records with_mean, with_std, sample_count and backend; ridge records rank, include_intercept and solver; the random forest records its OOB kind, score and scored-row count; logistic regression records its penalty, solver, class-weight policy and multi-class strategy.

The resolved backend travels as its documented display name through sk_backend_parameter, and an imported model reports the same SKBackendKind in its observability spans. The tests assert exactly that, for example linear_regression_round_trips_coefficients_rank_and_backend.

A subtle trap: NaN. Missing markers and imputation statistics legitimately store NaN, and derived equality says NaN != NaN, which would make two identical exports look different. The shared helper sk_states_equal treats two NaNs as equal, and the imputer encodes a NaN missing marker as the string "nan" in metadata.

Where the code lives

Each model crate keeps the implementation beside the model, following the repository’s folder-module rule: a pure-dispatcher mod.rs declares mod export; and the implementation lives in export.rs, with a *_tests.rs companion at the end.

  • sciencekit_common::interop::shared — the format version, scalar dtype mapping, tensor readers, backend and metadata readers.
  • sciencekit_common::interop::testing — sk_assert_export_round_trip, sk_assert_state_names and sk_states_equal.
  • sciencekit_tree::export_helpers — the node-array codec reused by trees, forests and gradient boosting.
  • sciencekit_neighbors::neighbors::export_helpers and sciencekit_svm::export_support — the dense/CSR-preserving block codecs.
  • sciencekit_common::interop::nested — sk_embed_state / sk_extract_state, reused by the composed imputer, the forests, gradient boosting and the typed pipeline to nest one model’s whole state under a namespace.

Walking the companion tests

Every importable family has a test that fits, exports, imports into a fresh model, and compares predictions — never merely “export returned Ok”. The composite families that refuse import instead have a companion test that asserts the typed UnsupportedOperation (see the refusal table below).

  • standard_scaler_round_trips_predictions_and_backend (crates/sciencekit_preprocessing/src/standard_scaler/model/export_tests.rs) fits three scalers with SKBackendKind::MatrixMultiply, round-trips each and asserts bit-identical transform output plus the preserved backend.
  • one_hot_encoder_round_trips_integer_category_codes (crates/sciencekit_preprocessing/src/one_hot_encoder/model/export_tests.rs) proves integer category tables survive; the nominal test proves string label tables do.
  • simple_imputer_round_trips_the_composed_indicator (crates/sciencekit_impute/src/simple_imputer/model/export_tests.rs) embeds the composed missing-indicator under a nested namespace and compares the stacked output.
  • ridge_round_trips_multi_alpha_solutions (crates/sciencekit_linear_model/src/ridge/model/export_tests.rs) compares every coefficient row and both intercepts for a two-alpha fit.
  • logistic_regression_round_trips_probabilities and sgd_classifier_round_trips_classes_and_heads compare calibrated and one-vs-rest outputs and the canonical class table.
  • knn_regressor_keeps_a_sparse_design_sparse and svc_round_trips_pairwise_support_vectors_and_classes compare predictions after proving the representation and the class table survived.
  • random_forest_classifier_round_trips_members_and_oob and gradient_boosting_regressor_round_trips_stages compare predictions across nested tree states.
  • histogram_regressor_round_trips_binning_and_missing_routing compares the exported bin edges and predictions with NaN routing, while histogram_classifier_round_trips_categorical_masks checks the categorical table; histogram_regressor_round_trips_a_sparse_design proves a CSR design stays sparse.
  • kmeans_round_trips_centers_labels_and_backend, dbscan_round_trips_labels_and_nearest_core_assignment, pca_round_trips_components_mean_and_whitening, truncated_svd_round_trips_components_and_projection and isolation_forest_round_trips_trees_offset_and_scores cover the remaining learned-state families.

Coverage in this change

The retrofit lands family by family, each family in its own commit. It covers 47 fitted model types. Export is universal; import is conditional. Of the 47, 35 round-trip exactly — fit, export, import and reproduce the original predict/transform output bit-for-bit — while 12 refuse explicitly (10 composites at import, 2 type-erased pipelines at export). Nothing here claims that every model round-trips.

FamilyExportImport
Scalers (standard_scaler, minmax_scaler, robust_scaler)yesyes — bit-identical
One-hot encoders and polynomial featuresyesyes — bit-identical
Simple imputer, missing indicator, KNN imputeryesyes — bit-identical
Linear regression, ridge, lasso, elastic net, logistic regression, SGDyesyes — bit-identical
K-nearest neighbours (dense and CSR)yesyes — bit-identical
SVC, SVR, LinearSVCyesyes — bit-identical
Decision trees, random forests, gradient boostingyesyes — bit-identical
Histogram gradient boostingyes (binning tables, categorical masks, missing routing)yes — bit-identical
Clustering (KMeans, MiniBatchKMeans, DBSCAN)yesyes — bit-identical
Decomposition (PCA, TruncatedSVD, IncrementalPCA)yesyes — bit-identical
Outlier detection (IsolationForest)yesyes — bit-identical
Bagging, grid-search and halving winnersyesno — typed UnsupportedOperation
Typed pipelines and feature unionyesno — typed UnsupportedOperation
Graph and streaming pipelinesno — typed UnsupportedOperationno

The workspace-wide coverage test in the umbrella crate asserts at compile time that every fitted model type exposes the export contract, and at run time that the shared format version is used and concurrent exports agree (concurrent_export_agrees_with_the_single_threaded_state).

What refuses to import, and why

The spec (model-export-coverage) asks for two different things. Requirement “Every fitted model exports state” is about describing the learned model; requirement “Native import where reconstructible” is about rebuilding the estimator object. A state can be complete enough to inspect and still not contain the configuration needed to construct the estimator again. The spec covers exactly that gap: “models that cannot SHALL return UnsupportedOperation with guidance”, never a partial model.

The refusals are therefore deliberate, typed and documented, not missing code:

Model family (model type)Export?Import?
Bagging classifier (SKBaggingClassifierModel)yesno — typed UnsupportedOperation: member tensors are prefixed, but each member’s own metadata is absent, so the base model cannot be rebuilt
Bagging regressor (SKBaggingRegressorModel)yesno — same member-metadata gap
Grid-search classifier (SKGridSearchCVClassifierModel)yesno — typed UnsupportedOperation: winner tensors and selection metadata are present, the winner’s configuration is not
Grid-search regressor (SKGridSearchCVRegressorModel)yesno — same winner-configuration gap
Successive-halving classifier (SKHalvingGridSearchClassifierModel)yesno — same winner-configuration gap
Successive-halving regressor (SKHalvingGridSearchRegressorModel)yesno — same winner-configuration gap
Typed pipeline classifier and regressor (SKPipelineClassifier, SKPipelineRegressor)yes (nested stage states and final model)no — typed UnsupportedOperation: the configured stage chain holds live estimator values, not data
Feature union (SKFeatureUnionModel, static tuple)yes (each member state)no — typed UnsupportedOperation: the configured member chain holds live estimator values
Graph pipeline (SKPipelineGraphModel)no — typed UnsupportedOperation: stages sit behind type-erased Any boxesno
Streaming pipeline (SKFittedStreamingPipeline)no — typed UnsupportedOperation: fitted stages are type-erasedno

Each message names the missing information and suggests the path forward. For a typed pipeline, for example, the guidance is to rebuild the pipeline in code and import each nested stage state; for bagging, grid-search and halving the guidance is to re-fit the estimator. The tests graph_pipeline_export_returns_a_typed_unsupported_operation, streaming_pipeline_export_returns_a_typed_unsupported_operation and feature_union_import_returns_a_typed_unsupported_operation assert the error kind, so a silent regression to a partial model would fail the suite.

Why not import these too? Their state carries numbers but not enough configuration: bagging members and search winners would need their own nested metadata embedded, and the typed pipeline/union/graph/streaming stages hold live estimator values that a state cannot express today. That is an architectural change (a serialisable stage descriptor), deliberately left out of this retrofit.

Roads not taken

  • Derive macros. A #[derive(SKExportable)] would remove boilerplate, but it would also freeze private field names as public tensor names. The explicit code is the documentation of the format.
  • One serializer per model. Rejected for the reasons in the first section.
  • Densifying sparse inputs. Rejected: a sparse model must stay sparse, and the CSR triple keeps it so.
  • Silently accepting unknown versions. Rejected: import fails loudly with UnsupportedRepresentation and never builds a partial model.

ONNX export: turning a fitted model into a portable graph

This chapter explains how sciencekit exports fitted models to ONNX, the Open Neural Network Exchange format that Python, C++, Java, JavaScript, mobile and edge runtimes all read. It assumes no prior Rust knowledge, no numerical computing background and no ONNX experience. Every claim below points at real code in crates/sciencekit_onnx and at a real companion test.

The problem: a model is useful only where it can run

sciencekit trains models in Rust. A team often wants to serve one of those models somewhere else: a Python service, a browser, a phone, a C++ trading engine. Copying the Rust binary is not an option there. The usual answer is a neutral inference format — a file that any runtime can load.

ONNX is that format. It is not a training format and not a serialization of a particular library’s structs. It is a description of a computation: “read a matrix, multiply it by these numbers, add those numbers, apply a sigmoid, emit the result”. A runtime reads the description and executes it.

What an ONNX file actually contains

Think of an ONNX model as a recipe card with four sections:

SectionWhat it holdsIn sciencekit terms
InputsName, element type and shape of every queryfeatures, a matrix of batch_size × feature_count
InitializersBig constant tables stored beside the recipe (weights, thresholds, centres)The learned tensors of SKModelState
NodesThe operations, each reading named tensors and writing named tensorsMatMul, Add, TreeEnsembleClassifier, …
OutputsThe tensors the caller receivesprediction, or label plus probabilities

Two numbers describe the dialect:

  • the IR version says how the file structure itself is encoded;
  • the opset (operator-set version) says which operators and which operator semantics exist. Operator names are stable, their arguments are not: in opset 9 Unsqueeze took an axes attribute; from opset 13 axes is an input tensor. Choosing an opset is choosing a contract.

sciencekit_onnx writes IR version 8 and opset 17 for the default domain, plus opset 3 of the ai.onnx.ml domain for tree ensembles. Those constants live in crates/sciencekit_onnx/src/graph/opset.rs.

The key decision: translate the neutral state, do not invent a second format

The previous chapter introduced SKExportable: every fitted model already describes itself as SKModelState — metadata plus stable, named tensors. The obvious temptation is to give ONNX its own per-model exporter that reaches into private fields. That would create a second model definition, and the two would drift.

The exporter instead is a translator from the neutral state:

#![allow(unused)]
fn main() {
pub trait SKToOnnx<F: SKFloat> {
    fn to_onnx(&self) -> Result<SKOnnxModel, SKError>;
}

impl<F, T> SKToOnnx<F> for T
where
    F: SKFloat,
    T: SKExportable<F>,
{
    fn to_onnx(&self) -> Result<SKOnnxModel, SKError> {
        let state = self.export_state()?;
        sk_export_state_to_onnx(&state)
    }
}
}

The blanket implementation is the whole contract: anything that can export its state gets to_onnx() for free. The model crates do not depend on sciencekit_onnx, and sciencekit_common stays ONNX-free. Dispatch happens once, on the state’s estimator name, inside sk_export_state_to_onnx.

flowchart LR
  accTitle: From fitted Rust models to a verified ONNX graph
  accDescr: Four fitted model families export a shared model state. A dispatcher keyed by estimator name routes each state to the matching graph builder for preprocessing, linear, tree, neighbour, clustering, decomposition or pipeline models. The builders produce a protobuf model whose predictions are verified with the ONNX checker and runtime.
    subgraph Train["Fitted in Rust"]
        M1["SKStandardScalerModel"]
        M2["SKLogisticRegressionModel"]
        M3["SKRandomForestRegressorModel"]
        M4["SKPipelineClassifier"]
    end
    M1 -->|export_state| S["SKModelState&lt;F&gt;<br/>metadata + named tensors"]
    M2 -->|export_state| S
    M3 -->|export_state| S
    M4 -->|export_state| S
    S -->|sk_export_state_to_onnx| D{"dispatcher<br/>by estimator name"}
    D --> P["preprocessing<br/>Sub · Mul · Div · Clip"]
    D --> L["linear<br/>MatMul · Add · Sigmoid"]
    D --> T["trees<br/>TreeEnsemble*"]
    D --> N["neighbours<br/>distance · TopK · Gather"]
    D --> C["clustering<br/>distance · ArgMin"]
    D --> X["decomposition<br/>Sub · MatMul"]
    D --> PL["pipelines<br/>stage subgraphs"]
    P --> G["SKOnnxGraphBuilder"]
    L --> G
    T --> G
    N --> G
    C --> G
    X --> G
    PL --> G
    G -->|prost| B["ModelProto bytes"]
    B -->|onnx.checker + onnxruntime| V["verified predictions"]

The protobuf spike and the encoding choice

An ONNX file is a Protocol Buffer message (ModelProto). The change began with a spike comparing three encoders under the project’s Rust 1.85 minimum and its Apache-2.0 licensing policy:

CandidateLicenseFinding
prost 0.14.5Apache-2.0Already in the workspace lock. Messages declared with #[derive(prost::Message)] need no protoc and no vendored .proto file.
onnx-protobuf 0.2.3MPL-2.0Depends on the old protobuf 3.4 line and adds a file-level copyleft the project avoids.
axonml-onnx 0.6.2MIT OR Apache-2.0Admissible, but pulls axonml-core, axonml-nn, axonml-tensor and axonml-serialize — an entire foreign ML framework for a pure encoder.

prost with hand-declared structs won. Only crates/sciencekit_onnx/src/graph/proto.rs knows about protobuf; the builder API is backend-agnostic. Every learned tensor travels in raw_data, little endian, which is exactly what a runtime expects and what keeps f64 values bit-exact.

Building a graph and refusing an invalid one

SKOnnxGraphBuilder collects inputs, initializers, nodes, outputs and metadata, then validates before serializing:

  • at least one input and one output;
  • every name is defined once — an initializer cannot shadow a node output;
  • every node input was produced earlier (an empty name means “optional input omitted”);
  • every declared output has a producer;
  • an initializer’s byte length matches the product of its dimensions.

Those checks are the first line of defence behind the spec scenario “Missing tensor is rejected”. A graph that fails them never becomes bytes.

Every node is a SKOnnxNode with typed attributes (attribute_integer, attribute_floats, attribute_strings, …). Attributes carry the protobuf AttributeProto.type discriminant, without which a runtime cannot tell an empty integer list from an empty float list.

Element types, metadata and versioning

SKOnnxTensorDType maps the neutral scalar to ONNX:

sciencekitONNX
F32FLOAT (1)
F64DOUBLE (11)
I64INT64 (7)
BoolBOOL (9)

The declared input is always a matrix [batch_size, feature_count], with a symbolic batch dimension so the graph accepts any number of rows. The output shape depends on what the model produces: [batch, 1] for a regression, [batch, class_count] for probabilities and [batch] for a label.

Model metadata copies the neutral metadata under explicit keys:

sciencekit.estimator_name      sciencekit.format_version
sciencekit.scalar_data_type    sciencekit.feature_count
sciencekit.number_of_classes   sciencekit.class_label.<index>

The class table is written one entry per index, not as a comma-joined string, so a label containing punctuation survives the trip. producer_name is sciencekit and producer_version comes from the crate version.

The operator subset, family by family

FamilyEstimatorsOperatorsNotes
ScalersSKStandardScaler, SKMinMaxScaler, SKRobustScalerSub, Mul, Div, Add, Clipper-column statistics broadcast over the batch
EncoderSKOneHotEncoderGather, Equal, Cast, Concatnumeric integer codes and the ignore policy
Linear regressorsSKLinearRegression, SKRidge, SKLasso, SKElasticNet, SKSGDRegressorMatMul, Addone coefficient vector; coordinate-descent families need a single alpha
LogisticSKLogisticRegressionMatMul, Add, Sigmoid, Softmax, ReduceSum, Div, Concat, ArgMaxbinary, multinomial and one-versus-rest
TreesSKDecisionTree*, SKRandomForest*TreeEnsembleClassifier, TreeEnsembleRegressor, ArgMaxf32 only
Support-vector machinesSKSVC, SKSVR, SKLinearSVCMatMul, Add, Unsqueeze, Sub, Mul, ReduceSum, Exp, Tanh, Pow, Greater, Cast, Gather, Abs, ArgMaxlinear, polynomial, rbf and sigmoid kernels
NeighboursSKKNeighbors*Unsqueeze, Sub, Mul, ReduceSum, TopK, Gather, Equal, Cast, Concat, Div, ArgMaxdense brute-force search, uniform weights
ClusteringSKKMeans, SKMiniBatchKMeansUnsqueeze, Sub, Mul, ReduceSum, ArgMinnearest centre
DecompositionSKPCA, SKTruncatedSVDSub, MatMul, DivPCA includes the mean and the whitening scale
PipelinesSKPipelineClassifier, SKPipelineRegressorcomposed stage subgraphsstages wired in order

The matrix is data, exposed by sk_onnx_coverage() and sk_onnx_supported_families(), so tests and documentation cannot claim more than the dispatcher delivers. export_coverage_lists_every_implemented_estimator asserts the twenty-two working names are present; export_coverage_rejects_an_unregistered_family_with_its_name asserts an unregistered family returns UnsupportedOperation whose reason names it and points at the matrix — never a silently wrong graph.

Trees need building twice, on purpose

The neutral tree state already carries the exact parallel arrays ONNX-ML wants: split feature per node, threshold, true/false child, leaf values and their offsets. SKOnnxTreeLayout reads them; SKOnnxTreeEnsemble re-lays them under a tree id and scales each leaf weight. A forest stores the mean probability, so each member’s leaf weights are divided by the tree count and the ensemble’s SUM aggregation reconstructs the mean. The label comes from an explicit ArgMax over the probabilities rather than from the ensemble’s own label output, because ONNX-ML leaves tie-breaking unspecified while the Rust predictor breaks ties toward the smallest class index.

ONNX-ML stores thresholds and leaf weights as 32-bit float attributes. A double-precision tree would silently round its thresholds, so the exporter rejects it:

#![allow(unused)]
fn main() {
if state.metadata().scalar_data_type() == SKTensorDataType::F64 {
    return Err(unsupported(estimator_name, "… only f32 trees are exported"));
}
}

f64_trees_are_rejected_because_the_onnx_ml_attributes_are_floats locks that decision in a test.

Support vectors and the kernel subgraph

A fitted kernel SVM is a support-vector expansion: $f(x) = \sum_i \alpha_i K(x, s_i) + b$. ONNX has no operator for an arbitrary kernel, so export/svm/kernel.rs writes the kernel itself as arithmetic:

  • linear — $\operatorname{MatMul}(X, SV^{\mathsf T})$;
  • rbf — broadcast $X - SV$, square, reduce, negate, multiply by $\gamma$ and apply Exp;
  • polynomial — $\operatorname{Pow}(\gamma \cdot X \cdot SV^{\mathsf T} + c_0, \text{degree})$;
  • sigmoid — $\operatorname{Tanh}(\gamma \cdot X \cdot SV^{\mathsf T} + c_0)$.

The dual coefficients then enter as a MatMul and the bias as an Add (export/svm/expansion.rs). SKSVR emits the margin as its regression prediction.

SKSVC keeps one expansion per one-vs-one pair. A binary model exposes the single signed margin and derives its label from ArgMax([−m, +m]), which reproduces the Rust rule “zero votes for the negative class”. A multiclass model reproduces sk_aggregate_one_vs_one_confidences node by node: per class it accumulates the vote (Greater + Cast, with the loser contribution 1 − winner) and the signed margin sum, then builds votes + margin_sum / (3 · (|margin_sum| + 1)). Labels come from ArgMax over the votes only — exactly what the Rust predictor does — so ties fall to the smallest class index. Calibrated probabilities are not exported; the graph exposes decisions and labels, which is what the SVM spec promises.

SKLinearSVC needs no kernel: its heads are linear, so the graph is one MatMul plus Add, with a single head mirrored into [−d, d] to match the Rust decision matrix, followed by ArgMax.

Two limits are explicit. A precomputed kernel reads a gram query the graph cannot interpret, so it returns UnsupportedOperation naming the kernel. A CSR support-vector block has no dense matrix to expand, so it returns UnsupportedOperation naming the representation. Neither silently exports a wrong graph. export_svm_precomputed_kernel_is_rejected_by_name locks the first case.

Neighbours without a k-d tree

A graph runtime has no k-d tree. The exported neighbour model therefore recomputes the brute-force search: broadcast the query [N, 1, F] against the training design [1, M, F], square the difference, sum over features, negate and take the k largest with TopK. Regression gathers the training responses and reduces them; classification gathers each neighbour’s canonical class index, counts matches per class with Equal/Cast/ReduceSum, divides by k and takes the ArgMax. The Rust side chooses the same neighbours, so predictions agree within floating-point tolerance.

The graph consumes a dense query matrix. That is not a representation regression: ONNX tensors are dense by construction, and the translation happens at the documented file boundary. A CSR training state is rejected with a message naming the reason rather than densified behind the caller’s back.

Pipelines recover stage identity

A typed pipeline nests each fitted stage under pipeline.stage.<i> and the final estimator under pipeline.final. The neutral nesting copies tensors and parameters but not the inner estimator name — import knows the types at compile time, ONNX does not. The exporter therefore recognizes each stage by its documented tensor signature (logistic.coefficients, standard_scaler.mean, pca.components, …), extracts the nested state with sk_extract_state and appends its nodes to the same graph. A stage that is not a transformer stops the composition with an explicit error, because a pipeline cannot feed a prediction to the next stage.

Public objects, one by one

  • SKToOnnx<F> — the export method, blanket-implemented over SKExportable<F>.
  • sk_export_state_to_onnx — dispatch a state to a graph; the single entry point every other path uses.
  • SKOnnxModel — serialized bytes plus the declared interface (inputs(), outputs(), opset(), metadata(), node_count(), initializer_count(), save()).
  • SKOnnxGraphBuilder — validated accumulator: add_input, add_output, add_node, add_floating_initializer, add_integer_initializer, add_metadata, build.
  • SKOnnxNode — an operator call with typed attributes, in the default or ai.onnx.ml domain.
  • SKOnnxValueInfo / SKOnnxDimension — typed input/output declarations with fixed or symbolic dimensions.
  • SKOnnxTensorDType — the scalar-to-ONNX element-type mapping.
  • sk_onnx_coverage / SKOnnxFamilyCoverage — the documented matrix.

Walking the companion tests

The tests are the executable source of truth. They come in three layers.

Graph layer. graph_identity_round_trips_through_protobuf builds an identity graph, decodes the bytes back to a ModelProto and checks the opsets, node and interface. graph_serializes_floating_initializers_as_raw_f32_bytes reads the raw payload back as little-endian floats. graph_rejects_an_output_no_node_produces, graph_rejects_a_node_reading_an_undefined_input and graph_rejects_an_initializer_whose_values_do_not_match_its_shape prove the builder refuses malformed graphs.

Family parity. Each test fits a real model, computes the Rust prediction and writes a fixture under SCIENCEKIT_ONNX_FIXTURE_DIR:

  • standard_scaler_export_matches_the_rust_transform, minmax_scaler_export_matches_the_clipped_transform, robust_scaler_export_matches_the_rust_transform;
  • one_hot_encoder_exports_integer_codes_under_the_ignore_policy and one_hot_encoder_rejects_the_export_of_the_reject_policy;
  • linear_regression_export_matches_the_rust_prediction, ridge_single_alpha_export_matches_the_rust_prediction, logistic_regression_binary_export_matches_the_rust_probabilities, logistic_regression_multiclass_export_matches_the_rust_probabilities;
  • decision_tree_classifier_export_matches_the_rust_probabilities, random_forest_regressor_export_matches_the_rust_prediction (plus the classifier and single-tree variants);
  • export_remaining_neighbors_classifier_matches_the_rust_probabilities, export_remaining_kmeans_matches_the_rust_labels, export_remaining_pca_matches_the_rust_transform and the truncated-SVD test;
  • export_pipeline_classifier_composes_scaler_and_logistic_regression and export_pipeline_regressor_composes_two_transforms_and_a_linear_model;
  • export_svm_binary_svc_rbf_matches_the_rust_decisions_and_labels, export_svm_binary_svc_linear_matches_the_rust_decisions_and_labels, export_svm_multiclass_svc_one_vs_one_matches_the_rust_outputs, export_svm_svr_rbf_matches_the_rust_prediction, export_svm_linear_svc_binary_and_multiclass_match_the_rust_outputs and export_svm_precomputed_kernel_is_rejected_by_name.

Acceptance. onnx_runtime_validates_an_exported_scaler regenerates a fixture and executes the committed harness when the host Python has onnx and onnxruntime, skipping with an explicit message otherwise. metadata_carries_producer_estimator_version_and_shape, dtype_mapping_declares_float_for_f32_and_double_for_f64, large_and_small_models_export_valid_graphs, classifier_metadata_carries_the_class_table and concurrent_exports_of_one_model_produce_identical_bytes cover the acceptance criteria.

Real verification, not a parse check

A file that merely parses proves nothing. The committed harness crates/sciencekit_onnx/validation/compare_with_onnxruntime.py loads every exported model with onnx, validates it with onnx.checker.check_model, runs it with onnxruntime.InferenceSession and compares every declared output against the Rust prediction within the fixture tolerance. The recorded run matched 26 of 26 fixtures, including f32 and f64 scalers, the one-hot encoder, binary and multiclass logistic models, decision trees, random forests, k-nearest neighbours, k-means, PCA, truncated SVD, both pipelines, binary SVC with rbf and linear kernels, multiclass one-vs-one SVC, rbf SVR and binary plus multiclass SKLinearSVC.

Decisions and roads not taken

  • Translator over per-model exporters. One dispatcher plus the neutral state keeps a single model definition. A per-model ONNX serializer would drift.
  • prost with declared messages. No protoc, Apache-2.0, already in the lock. The rejected alternatives are in the spike table.
  • Opset 17. Broad runtime support and every operator used here. Opset 21 would buy nothing and shrink the set of runtimes that can read the file.
  • Explicit ArgMax labels. ONNX-ML tie-breaking is unspecified; the Rust predictor’s smallest-index rule is part of its contract.
  • Dense graph inputs. ONNX tensors are dense; the boundary is the file, and a CSR-only state is rejected with a reason instead of being densified silently.
  • f32 trees only. The ONNX-ML schema’s float attributes cannot carry doubles faithfully, so the exporter says so.
  • Unsupported families are loud. Gradient/histogram boosting (base score plus learning rate), isolation forest (path-length composition) and DBSCAN (no fitted prediction) return UnsupportedOperation naming the family; precomputed SVM kernels and CSR support vectors are rejected by name for the same reason. They are listed as unsupported in sk_onnx_coverage; none of them produces a partial graph.
  • Validation with onnxruntime, not tract. The design named tract-onnx 0.22 as one possible checker. Its transitive crates were not resolvable in the build environment, and the reference Python runtime is a stronger cross-implementation check anyway: it is the runtime a production consumer is most likely to use. The harness is committed and rerunnable.

ONNX import: reading a foreign graph as a model

This chapter explains how sciencekit loads an ONNX model and runs it as a predictor — the mirror image of the export chapter. It assumes no Rust knowledge, no numerical-computing background and no ONNX experience. Every claim points at real code in crates/sciencekit_onnx and at a real companion test you can run.

From a recipe card to a running model

An ONNX file is a recipe: named inputs, constant tables, operator nodes and named outputs. Export wrote that card. Import has to read it and then cook.

flowchart LR
    A["model.onnx<br/>protobuf bytes"] --> B["decode<br/>serde-onnx IR"]
    B --> C["validate<br/>opset · operators · external data"]
    C --> D["analyse interface<br/>one input · prediction head"]
    D --> E["SKOnnxPredictor&lt;F&gt;"]
    E --> F["topological walk<br/>initializers + operators"]
    F --> G["responses or<br/>labels + probabilities"]
    style A fill:#FDE68A,stroke:#B45309,color:#111
    style B fill:#BFDBFE,stroke:#1D4ED8,color:#111
    style C fill:#FCA5A5,stroke:#B91C1C,color:#111
    style D fill:#DDD6FE,stroke:#6D28D9,color:#111
    style E fill:#A7F3D0,stroke:#047857,color:#111
    style F fill:#FBCFE8,stroke:#BE185D,color:#111
    style G fill:#FED7AA,stroke:#C2410C,color:#111
    accTitle: The ONNX import pipeline
    accDescr: Bytes are decoded into the shared IR, validated, analysed to pick a prediction head, wrapped in a predictor, executed by a topological walk and returned as responses or class probabilities.

Those five stages are five small modules: decode.rs, model.rs, interface.rs, predictor*.rs and interpreter.rs. mod.rs is a pure dispatcher — it only declares modules and re-exports public items, following the repository convention.

One IR for both directions

Export used to assemble the graph with hand-declared prost messages. Import would then need its own decoding, and the two vocabularies would inevitably drift. The change adopted serde-onnx as the single ONNX intermediate representation, pinned to revision 0c54592:

serde-onnx = { git = "https://github.com/neurono-ml/serde-onnx", rev = "0c54592",
               default-features = false, features = ["import", "export"] }

SKOnnxGraphBuilder now fills serde_onnx::ir::Model; SKOnnxModel stores the encoded bytes and that decoded model; from_bytes decodes into the very same type. The exporter and importer therefore share Node, Attribute, Tensor, ElemType and the typed ai.onnx.ml operator structs.

One wrinkle is worth recording precisely, because it is an upstream bug in revision 0c54592, not a limitation of ONNX. decode_attribute in serde-onnx/src/proto/codec.rs decides whether an attribute carries a value from the encoded protobuf field: it tests proto.i != 0, proto.f != 0.0 and !proto.s.is_empty() instead of consulting AttributeProto.type. Protobuf omits scalar fields equal to their default, so a legal INT 0, FLOAT 0.0 or empty STRING is indistinguishable from an absent field and decoding fails with attribute "axis" carries no value. Legal ONNX graphs use axis = 0 and keepdims = 0 constantly. import/decode.rs therefore substitutes a sentinel before decoding and restores the zero afterwards. The shim is deliberately narrow (only AttributeType::Int/Float/String with the default value), and decode_tests.rs proves both halves: the pinned decoder rejects the same bytes, and the shim restores exactly the zero without touching non-zero attributes. The guard is removable once the pinned revision is bumped.

Why import is stricter than export

Export knows its own output. Import meets strangers. The loader therefore refuses, up front and with a typed error, everything it cannot honestly run:

SituationError variant
Bytes that are not a ModelProtoSKOnnxImportError::InvalidModel
Graph data dependencies form a cycleGraphCycle (names the node path)
Opset or IR version above the ceilingUnsupportedOpset
An operator outside the documented subsetUnsupportedOperator (names domain, operator and node index)
A value no initializer or earlier node definesMissingInitializer (names the tensor)
An initializer stored in another fileExternalData (names the tensor)
Input width or tensor shape disagreesShapeMismatch
An element type outside the dense numeric subsetUnsupportedDtype
No regression head and no coherent classifier headUnsupportedOutput
An operator received operands or attributes it cannot executeInvalidOperator

The rule mirrors the library’s philosophy: a precise refusal beats a silent guess. a_node_reading_an_undefined_value_names_the_missing_tensor and an_external_initializer_is_rejected_by_name in validation_tests.rs and model_tests.rs are the executable proof, and the structural validator comes from the shared IR (serde_onnx::ir::validate_model) so a cycle is reported as a cycle instead of as a stalled topological walk. Malformed nodes and shape metadata are validated before any ndarray call that would panic: operand_tests.rs, shape_validation_tests.rs and graph_validation_tests.rs cover missing operands, an initializer width that disagrees with the declared input, invalid Transpose/Squeeze axes and a cyclic graph.

The operator dispatch table

The subset is advertised as data, not prose: SK_ONNX_SUPPORTED_OPERATORS lists the default-domain operators and SK_ONNX_SUPPORTED_ML_OPERATORS the two ai.onnx.ml tree ensembles. sk_onnx_supports_operator(domain, operator) is the single decision point used by validation and by the interpreter.

flowchart TD
    N["Node(domain, op_type)"] --> Q{"documented subset?"}
    Q -- no --> R["UnsupportedOperator<br/>domain · operator · node index"]
    Q -- yes --> S{"domain"}
    S -- "&quot;&quot; / ai.onnx" --> C["elementwise · matrix<br/>reductions · selection<br/>shape operators"]
    S -- "ai.onnx.ml" --> T["TreeEnsembleClassifier<br/>TreeEnsembleRegressor"]
    C --> V["SKOnnxValue"]
    T --> V
    style N fill:#E0E7FF,stroke:#4338CA,color:#111
    style Q fill:#FEF3C7,stroke:#B45309,color:#111
    style R fill:#FCA5A5,stroke:#B91C1C,color:#111
    style C fill:#A7F3D0,stroke:#047857,color:#111
    style T fill:#BFDBFE,stroke:#1D4ED8,color:#111
    style V fill:#FBCFE8,stroke:#BE185D,color:#111
    accTitle: Operator dispatch
    accDescr: Each node is checked against the documented subset, rejected with a typed error when outside it, and dispatched either to the core operator implementations or to the ONNX-ML tree ensembles, producing an interpreter value.

Every value the interpreter moves is a SKOnnxValue: Float32, Float64, Int64 or Boolean backed by an ndarray::ArrayD. Arithmetic broadcasts like NumPy, and integer operands of Gather, TopK and ArgMax stay integers so indices are never rounded through a float.

How a graph becomes a model: the topological walk

ONNX stores nodes in an order, but an interpreter must not trust that order — a valid file may mention a dependency later. interpreter::execute keeps a pending list and repeatedly runs the first node whose every non-empty input is already available:

$$ \text{ready}(n) \iff \forall, i \in \text{inputs}(n):\ i = \emptyset \ \lor\ i \in \text{values} $$

Initializers enter the value map first, then each ready node writes its outputs. If no node is ready, the first node with a missing operand produces MissingInitializer — this is exactly the cycle/typo diagnosis a plain index-by-index loop would miss.

sequenceDiagram
    participant E as execute
    participant V as value map
    participant N as pending nodes
    E->>V: insert every initializer
    loop until pending is empty
        E->>N: find first node whose inputs are all available
        alt a node is ready
            E->>V: run node, write its outputs
        else nothing is ready
            E-->>E: MissingInitializer(name, node_index)
        end
    end
    E->>V: select the declared outputs by name
    accTitle: Topological execution
    accDescr: The executor seeds the value map with initializers, repeatedly runs a node whose inputs are available, and fails with a typed missing-initializer error when no node can run.

The tree ensembles show the same walk at a smaller scale. tree_walk.rs finds the root, then follows nodes_truenodeids or nodes_falsenodeids until it reaches LEAF, accumulating class_weights or target_weights. Thresholds are compared in the tree’s own comparison mode (BRANCH_LEQ, BRANCH_LT, …), and a NaN feature follows nodes_missing_value_tracks_true — the ONNX-ML semantics.

The public objects

  • SKOnnxModel — the shared handle: bytes plus decoded IR. from_bytes and from_file decode and validate; inputs, outputs, opset, node_count, initializer_count and model() expose the interface. model_tests.rs walks all of them on an affine fixture.
  • SKOnnxPredictor<F> — the generic predictor. It implements both SKRegressorPredictor<F> (predict) and SKClassifierPredictor<F> (predict_labels, predict_probabilities), plus predict_arrays, which returns every declared output by name. A method whose head the model does not declare returns UnsupportedOperation rather than guessing.
  • SKOnnxPredictorBuilder<F> — the mandatory builder. Attach .model(...), .model_bytes(...) or .model_file(...) and call .build(); only build performs interface analysis.
  • SKOnnxImportError — the typed taxonomy above.
  • SK_ONNX_SUPPORTED_OPERATORS / SK_ONNX_SUPPORTED_ML_OPERATORS / sk_onnx_supports_operator — the operator contract as data.

Head analysis is deliberately simple: one required dense float matrix input; one integer label output plus one float matrix is a classification; a single float output is a regression (one column for predict, any width for predict_arrays); an integer-only output is labels-only. Anything else is UnsupportedOutput.

Like every other estimator, the predictor builder exposes backend and execution_mode (defaults Faer and Automatic). Imported models use neither choice for heavy algebra — the interpreter walks the graph — but the selection surface is uniform and every public prediction operation records the configured kind in a sciencekit.operation span through sk_run_operation. The span also carries the row and column counts and never a hardcoded backend; observability_tests.rs asserts the override (MatrixMultiply) reaches the span and that the default is Faer.

The decisions and the roads not taken

  • tract-onnx 0.22 was spiked. It builds on Rust 1.85, but it brings its own IR and a large dependency tree to run operators the library itself exports. The change chose the shared-IR interpreter instead: a smaller dependency surface and one model vocabulary for both directions.
  • ort (the official runtime binding) requires Rust 1.92, above the project’s MSRV, so it was never a candidate.
  • A dynamic-shape, quantized, string-tensor interpreter is out of scope and is rejected explicitly rather than half-supported. ExternalData is refused because reading side files is a security and portability decision of its own.
  • Computing everything in f64 would have been simpler but would drift from onnxruntime on f32 models; the interpreter keeps the operand dtype and promotes only for genuinely mixed arithmetic.

Walking the tests

The companion tests are the executable truth of this chapter:

  • identity_graph_returns_its_input_unchanged (interpreter_tests.rs) proves the adapter without any learned tensor.
  • parsed_model_exposes_inputs_outputs_and_counts and invalid_bytes_return_a_structured_error (model_tests.rs) cover metadata and the first typed refusal.
  • affine_regressor_matches_the_closed_form, feature_width_mismatch_is_rejected_before_inference and non_finite_input_is_rejected (predictor_tests.rs) cover the regression surface.
  • softmax_classifier_exposes_labels_and_probabilities and two_float_outputs_are_an_ambiguous_head (classifier_tests.rs) cover the classifier surface.
  • a_large_batch_preserves_the_row_count_and_agrees_row_by_row and classifier_batches_agree_row_by_row (batch_tests.rs) prove batching.
  • an_unsupported_operator_is_rejected_with_its_name (operators_tests.rs) proves the documented subset is enforced.
  • a_node_reading_an_undefined_value_names_the_missing_tensor and an_integer_feature_input_is_rejected_as_an_unsupported_dtype (validation_tests.rs) prove the stricter-than-export contract.
  • linear_regression_round_trips_through_export_and_import, standard_scaler_round_trips_through_export_and_import, decision_tree_classifier_round_trips_through_export_and_import and pipeline_regressor_round_trips_through_export_and_import (round_trip_tests.rs) close the loop against the original Rust model.
  • binary_rbf_svc_round_trips_labels_and_decision_values, multiclass_rbf_svc_round_trips_labels_and_decision_values, pca_round_trips_the_transform, truncated_svd_round_trips_the_transform, standard_scaler_without_mean_round_trips_the_transform and dense_knn_classifier_round_trips_labels_and_probabilities (round_trip_families_tests.rs) extend that loop to the remaining exported families.
  • The same file documents two round trips that cannot exist yet, as executable expectations of the typed refusal: boosting states (the histogram_gradient_boosting exporter is outside sk_onnx_coverage) and a CSR-trained KNN (the neighbour exporter translates only a dense training design). Both return UnsupportedOperation naming the reason; no import code pretends to round-trip them.
  • the_pinned_decoder_rejects_a_legal_zero_integer_attribute, the_shim_restores_zero_integer_and_float_attributes and the_shim_leaves_non_zero_attributes_untouched (decode_tests.rs) keep the sentinel shim honest.
  • concurrent_predictions_match_the_sequential_result (concurrency_tests.rs) proves a loaded predictor is Send + Sync and deterministic.

Finally, the external proof lives in crates/sciencekit_onnx/validation/compare_with_onnxruntime.py. Run cargo run -p sciencekit_onnx --example validate_import <fixture-root> and then the harness: it compares the Rust prediction, onnxruntime and the imported prediction on identical inputs and reports the matched/total counts. Today all 36 exported fixtures match on both counts, which is why the import contract is backed by a real runtime rather than by hope.

Native model import: from a foreign file back to a real model

This chapter explains what it means to import a model natively, and why the library does it in two stages — first into a neutral state, then into a concrete fitted type. It assumes no Rust, no machine-learning and no ONNX background. Every claim points at real code under crates/sciencekit_interop/src/native/ and crates/sciencekit_onnx/src/native/, and at a companion test you can run.

The previous chapters built two halves of the story: export gave every fitted model a neutral SKExportable state, and ONNX import taught the library to run a foreign graph. Native import connects them: the file is read into that same neutral state and then rebuilt into the model type it originally was.

“Native” versus “generic”

A generic predictor answers one question: given these features, what comes out? It is a black box. You cannot inspect its coefficients, put it in a typed pipeline, save it as Safetensors again, or train it further.

A native import returns the real type: SKLinearRegressionModel<F>, SKLogisticRegressionModel<F>, SKStandardScalerModel<F>, a decision tree, a random forest or a k-means model. That object implements the same prediction traits, records the same backend in its spans and, where the algorithm keeps the learning state, accepts more data through partial_fit.

flowchart LR
    subgraph Foreign["Foreign containers"]
        SF["Safetensors<br/>binary"]
        JS["JSON debug<br/>text"]
        ON["ONNX<br/>protobuf graph"]
    end
    SF --> DET["detect + validate<br/>magic · version · length"]
    JS --> DET
    ON --> GRAPH["graph to neutral state<br/>affine · scaler · trees"]
    DET --> STATE["SKModelState&lt;F&gt;<br/>metadata + named tensors"]
    GRAPH --> STATE
    STATE --> CHECK["estimator dispatch<br/>exact tensor set · class table"]
    CHECK --> NATIVE["SKNativeImport&lt;F&gt;<br/>real fitted model + descriptor"]
    NATIVE --> PRED["predict · transform · clusters"]
    NATIVE --> RETRAIN["partial_fit<br/>where supported"]
    style SF fill:#FDE68A,stroke:#B45309,color:#111
    style JS fill:#FDE68A,stroke:#B45309,color:#111
    style ON fill:#FBCFE8,stroke:#BE185D,color:#111
    style DET fill:#BFDBFE,stroke:#1D4ED8,color:#111
    style GRAPH fill:#DDD6FE,stroke:#6D28D9,color:#111
    style STATE fill:#A7F3D0,stroke:#047857,color:#111
    style CHECK fill:#FCA5A5,stroke:#B91C1C,color:#111
    style NATIVE fill:#FED7AA,stroke:#C2410C,color:#111
    style PRED fill:#E0F2FE,stroke:#0369A1,color:#111
    style RETRAIN fill:#E0F2FE,stroke:#0369A1,color:#111
    accTitle: Two import paths converge on one neutral state
    accDescr: Safetensors and JSON are detected and validated directly; an ONNX graph is first mapped to the same neutral state. The state is validated, dispatched by estimator name and rebuilt into a native model that can predict and, where supported, continue training.

Why a neutral state beats per-runtime loaders

The tempting shortcut is one loader per producer: a scikit-learn loader, an ONNX loader, a Safetensors loader, each knowing every estimator. That design fails in three ways.

  1. Combinatorial drift. producers × estimators is a matrix. Each new producer must re-learn every estimator’s private field layout.
  2. Hidden partial models. A loader that half-recognizes a file tends to return a half-initialized object.
  3. No shared validation. Each path invents its own idea of “missing tensor”, “wrong dtype” or “unknown version”.

The neutral SKModelState<F> already solved this for export: metadata (stable estimator name, format version, scalar type, feature count, class table, typed hyperparameters) plus a deterministic map of named tensors. Native import reuses it. Safetensors and JSON are just two ways to fill the same container; ONNX is a third producer that computes the container from a graph. After that point there is exactly one validator and one dispatch table.

The trust boundary: validate before you construct

A model file is untrusted input. SKNativeImportError names each failure with its own variant, and the checks run in a fixed order so a later stage never sees bytes a former stage could not trust.

StageRejectsError variant
Container detectionneither JSON nor SafetensorsWrongMagic
Lengthheader announces more bytes than existTruncatedFile
Versiona major version this build cannot readUnknownFormatVersion
Tensor seta required tensor is absentMissingTensor
Tensor setan unknown tensor is presentUnexpectedTensor
Shapea tensor disagrees with its declared shapeShapeMismatch
Class tablelabels and score heads disagreeShapeMismatch { tensor: "class_labels" }
Familyno importer covers the estimator nameUnsupportedFamily
Graphan operator outside the documented subsetUnsupportedConstruct

Two of those deserve emphasis. Extra tensors are rejected, not ignored. An unknown tensor means the file was produced by a different estimator or a newer format; silently dropping it would hide a version skew. And the class table is validated against the declared class count, because accepting a three-label table on a two-head binary model would predict the wrong label without any error.

Not one of these paths unwraps a caller-controlled length or index; the code uses get, try_into and checked arithmetic, so a hostile file becomes a typed error rather than a panic.

Format detection is structural

The JSON debug format and the Safetensors header are both JSON-shaped, so the discriminator cannot be “does it look like JSON”. A JSON document begins with {; a Safetensors file begins with an eight-byte little-endian header length. Compressed Safetensors keep a compression magic, so they are recognized first. sk_detect_native_model_format implements exactly that rule:

first bytes == gzip/brotli/snappy magic  → Safetensors
first non-space byte == '{'              → JSON (parse and check format_version)
otherwise: read u64 length, check bounds → Safetensors

native_import_rejects_wrong_magic, native_import_rejects_a_truncated_container and native_import_rejects_an_unknown_json_version exercise those branches.

The affine models

Many producers emit a linear model as two operators: $\hat{y} = XW + b$. The mapper reads the MatMul weight $W$ and the optional Add bias $b$. If the graph also contains Sigmoid or Softmax, it is a classifier; otherwise a regressor.

For a regressor with one output column, the native state is

$$ \hat{y}i = \sum{j=1}^{d} w_j x_{ij} + b , $$

stored as linear.coefficients (length $d$), linear.intercept, a zero rank and an empty singular-value vector. Those last two are not produced by a foreign graph; the math that computed them (a QR or SVD solve) is gone, and the prediction function does not need them.

For a classifier, ONNX stores $W$ as $d \times h$ (features × heads), while the native logistic model stores $h \times d$. The mapper transposes and records number_of_classes, strategy = binary when $h = 1$, strategy = multinomial otherwise, plus the class table. For multinomial scores the model applies

$$ p_k(x) = \frac{\exp(z_k)}{\sum_{j=1}^{h}\exp(z_j)}, \qquad z = xW + b, $$

which is exactly the graph’s Softmax.

The scalers

All three scalers are per-column affine maps, so a graph alone is ambiguous between them. The mapper therefore uses the stable initializer names a sciencekit export writes — standard_scaler.mean, minmax_scaler.minimum, robust_scaler.center — when the estimator metadata is present. For a standard scaler the transform is

$$ z_j = \frac{x_j - \mu_j}{\sigma_j}, $$

and the neutral state additionally needs the running moments a stream update keeps. Those are synthesized as $\text{moments_mean} = \mu$ and $\sum (x-\mu)^2 = \sigma^2$ for the imported snapshot: predictions use only $\mu$ and $\sigma$, and a fresh continued fit rebuilds the true moments from new data.

The trees

ONNX-ML stores an ensemble as flat parallel arrays: per node a tree id, a node id, a feature id, a mode (BRANCH_LEQ or LEAF), a threshold, true and false child ids; per leaf a target weight (regressor) or class weights (classifier). The native state stores the same tree as parallel arrays where the node’s position is its id and children are positions. The mapper therefore groups by tree id, sorts nodes, builds an id→position map and remaps every child pointer; a leaf gets split feature $-1$ and threshold $0$.

A forest export scales each member’s leaves by $1/T$ so the ONNX sum is the forest average:

$$ \hat{y}{\text{forest}} = \frac{1}{T}\sum{t=1}^{T} \text{leaf}_t(x). $$

The native forest averages its members itself, so the importer multiplies each restored leaf by $T$ before writing it into forest.tree.{i}.t.tree. The test native_safetensors_round_trips_tree_and_forest checks the Safetensors half; the ONNX half is covered by native_onnx_imports_an_exported_decision_tree.

A forest classifier would additionally need each member’s local class table to be reconstructed, and that mapping is not recoverable from the ONNX weights alone. It is reported as UnsupportedOperator { operator: "TreeEnsembleClassifier" } rather than guessed; the generic predictor remains available for that graph.

One result type, several surfaces

SKNativeImport<F> is an enum with four variants — Classifier, Regressor, Transformer, Clusterer — each carrying the concrete model and an SKNativeModelDescriptor. The descriptor preserves the estimator name, feature count, class table, backend kind and the family’s SKRetrainingSupport.

A closed enum is deliberate. The prediction traits in sciencekit_common (SKRegressorPredictor, SKClassifierPredictor, SKFeatureTransformer, SKClustererPredictor) have generic methods over the input type, so they are not object-safe: you cannot write Box<dyn SKRegressorPredictor<F>>. The enum keeps the concrete types and dispatches one match per surface:

predict_regression   → only a Regressor answers
predict_labels       → only a Classifier answers
predict_probabilities
transform            → only a Transformer answers
predict_clusters     → only a Clusterer answers

Wrong-surface calls return UnsupportedOperation; they never guess.

Continued training

The import result records whether the family keeps a learning state. SKRetrainingSupport::Supported is set only where continuing is honest:

FamilyContinued fittingWhy
SKSGDRegressor, SKSGDClassifieryesthe iterate is the model; partial_fit continues it
SKLogisticRegressionyesrefitted through warm_start_from from the imported coefficients
SKLinearRegressionnoan OLS state carries no accumulated design; use SGD
trees, forests, scalers, k-meansnoinference-only after conversion

native_retrain_logistic_regression_warm_starts_from_the_import builds the reference with the same warm-start builder and asserts identical labels and probabilities. native_retrain_guidance_explains_why_a_family_is_inference_only asserts that rejection names the operation and the reason instead of silently resetting coefficients.

The public objects

  • SKNativeImport<F> and sk_import_native_state — dispatch a neutral state to a native model.
  • SKNativeImportError — the typed trust-boundary failure surface.
  • SKNativeModelFormat and sk_detect_native_model_format — structural container detection with version and length checks.
  • sk_import_native_model_from_bytes / ..._from_path — container → state → native model in one call.
  • SKNativeModelDescriptor and SKRetrainingSupport — what the conversion preserved and what it can do next.
  • SKNativeImportCoverage and sk_native_import_coverage — the documented matrix, read by tests so an advertised family is an exercised family.
  • SKOnnxNativeImporter — builder-only ONNX conversion (backend, execution_mode, model, model_bytes, model_file, build::<F>).
  • SKOnnxNativeError — UnsupportedOperator, UnsupportedEstimator, InvalidGraph, Native, Onnx.

Every public operation records the configured backend kind in its observability span; the ONNX importer also records the estimator and feature count.

The companion tests, walked through

Run them with:

cargo test -p sciencekit_interop native_
cargo test -p sciencekit_onnx native_
cargo test -p sciencekit_linear_model native_retrain
  • native_safetensors_round_trips_linear_regression exports a fitted linear model, reads the bytes back and asserts the predictions are equal — not merely close, because no arithmetic happens between export and prediction.
  • native_json_round_trips_standard_scaler does the same through the JSON debug format. It is the reason serde_json enables float_roundtrip: without it, parsing shortened decimals is off by one ULP and predictions drift.
  • native_safetensors_round_trips_tree_and_forest covers both tree state shapes. It exists because tree export used to write a NaN threshold at every leaf, which the Safetensors writer rejects as non-finite; leaves now write zero and the importer still treats them as leaves by their split feature.
  • native_onnx_imports_an_exported_logistic_regression checks labels, probabilities and the preserved class table.
  • native_onnx_matches_onnxruntime_for_an_external_classifier loads an ONNX file built outside the crate and compares the native probabilities and labels to values recorded from onnxruntime. Run python3 crates/sciencekit_onnx/validation/compare_native_import.py \ crates/sciencekit_onnx/validation/external to reproduce the reference half.
  • native_import_rejects_an_unexpected_tensor proves the trust boundary is bidirectional: a file that carries an extra tensor is rejected.
  • native_validation_concurrent_conversions_are_identical converts the same bytes on eight threads and compares the probability matrices.
  • native_validation_a_failed_conversion_leaves_no_model shows that a rejected attempt has no side effect: the intact state still converts afterwards.

Decisions and roads not taken

Closed enum instead of a trait-object registry. A plugin registry would let families register themselves, but linkage order would decide which importer wins, and F is generic, so a static registry needs either monomorphized vectors or an inventory-style dependency. The enum is smaller, exhaustive and reviewable.

Exact tensor sets instead of “read what you need”. Ignoring extra tensors is convenient until a file from a newer format is silently accepted with the wrong semantics. The exact set makes version skew loud.

One ONNX subset, documented. Arbitrary graphs, neural networks and LoRA are out of scope. Supported today: affine regression/classification (including the sigmoid, softmax and argmax heads), the three per-column scalers and single decision trees; forests are supported for regressors, with the classifier case returning a named error.

No pin bump. The change keeps serde-onnx at revision 0c54592 and its narrow zero-attribute sentinel in import/decode.rs. Bumping to the upstream fix is a separate decision that must delete the shim and prove it is unused.

NaN leaves became zero. The Safetensors and JSON formats both enforce finite values. Writing 0 at a leaf is lossless for prediction because leaves are identified by a negative split feature; it also makes every tree state serializable without exception.

Low-rank adapters: teaching a frozen model a small new trick

This chapter explains low-rank adaptation (LoRA) as sciencekit implements it: a frozen fitted model stays exactly as it is, and a tiny pair of matrices learns a correction on new data. It assumes no Rust, no linear algebra and no prior machine-learning background. Every claim points at real code under crates/sciencekit_linear_model/src/adapters/lora/ and at a companion test you can run.

The story follows one question. A library user has a fitted model that works well, then receives fresh data from a slightly different distribution. Retraining the whole model is expensive and risks forgetting what it already knew. What if the model could learn just the part that changed, while the original weighs nothing in the loss?

The problem: moving a wall you already built

A linear model stores one number per feature, its coefficient, plus one intercept. For a linear regressor, prediction is the dot product of the feature row with the coefficient vector, plus the intercept. A logistic classifier stores one coefficient vector per class head and turns the resulting scores into probabilities.

Those numbers are what the model learned. Rewriting them means throwing away the old solution and solving the whole problem again, now on a mixture of old and new data — and, with a limited amount of new data, the old knowledge can quietly drift away.

Low-rank adaptation takes a different road: freeze the old numbers and learn a small correction next to them. The correction is added at prediction time.

The idea in one picture

flowchart LR
    accTitle: Frozen base plus a small trainable correction
    accDescr: A fitted base model keeps its coefficient matrix W frozen. New data trains only two thin matrices A and B, whose product is scaled by alpha over the rank and added to W to form the adapted matrix W prime. Prediction and merge both use that same adapted matrix.

    DATA["New data<br/>features + targets"] --> FIT["fit A and B only<br/>monotone descent"]
    BASE["Frozen base model<br/>coefficient matrix W"] --> ATTACH["attach<br/>A is rank by features<br/>B is heads by rank"]
    ATTACH --> FIT
    FIT --> DELTA["low-rank update<br/>(alpha / rank) times B times A"]
    BASE --> ADD["effective matrix<br/>W prime = W + update"]
    DELTA --> ADD
    ADD --> PREDICT["predict<br/>same product as the base"]
    ADD --> MERGE["merge<br/>standalone native model"]

The left side of the picture never changes. Everything the optimizer touches is the two thin matrices under fit A and B only.

What “low-rank” means, and why it is cheap

A full coefficient block W for a logistic classifier with p heads and d features has p × d numbers. A low-rank correction replaces that dense block with two thin factors:

  • A is r × d — one row per rank r;
  • B is p × r — one column per rank.

Their product B A is a p × d matrix, but it is built from only r · (p + d) numbers. The adapter stores A and B, never the product.

The update applied to the base is:

$$W’ = W + \frac{\alpha}{r} B A$$

The factor $\frac{\alpha}{r}$ is the scaling. In the code it is a method on the configuration:

#![allow(unused)]
fn main() {
/// The update scale `alpha / r`.
pub fn scaling(&self) -> F {
    F::from(self.rank).map_or(F::one(), |rank| self.alpha / rank)
}
}

With rank 8 and alpha 16 the scaling is exactly 2 — that is the first companion test, scaling_is_alpha_divided_by_rank. Dividing by the rank makes the correction’s magnitude roughly independent of how many factors are used, so changing the rank does not silently change the step size of the update.

Chapter code lives in core_implementation.rs; the target selection lives in config.rs and is a closed enum, SKLoraTargetModule, with one variant for linear coefficients and one for logistic coefficients. A closed enum means a misspelled target cannot compile, and a mismatched target becomes a typed error rather than a silent no-op.

One object per responsibility

Public objectFileWhat it is
SKLoraAdapter<F>core_implementation.rsImmutable configuration: identifier, rank, alpha, target, backend, optimizer budget.
SKLoraAdapterBuilder<F>builder.rsThe only way to construct an adapter; rejects rank zero, non-finite alpha, empty identifiers and a zero iteration budget.
SKLoraTargetModuleconfig.rsWhich coefficient block is adapted.
SKLoraBaseModel<F>base_model.rsA frozen fitted model: linear, logistic, or an explicitly unsupported family.
SKLoraAttachedModel<F>attached_model.rsBase plus the trainable A/B factors; the object you fit and predict with.
SKLoraMergedModel<F>merge.rsA native model with the update folded in; can be unmerged.
SKLoraAdapterArtifact<F>artifact.rsAn imported adapter before it is paired with a base.
SKLoraAdapterRegistry<F>registry.rsAdapters keyed by identifier, rejecting duplicates.

Construction is builder-only, as everywhere in the library. The adapter’s defaults are documented in builder.rs and verified by defaults_are_documented_and_stable: rank 4, alpha 1, linear target, Faer backend, automatic execution mode. Every public operation records the configured backend in its observability span — sk_prediction_attributes in prediction.rs does exactly that for prediction, and fit_linear/fit_logistic build the same attributes before their descent loops.

Freezing the base

SKLoraBaseModel::linear_regression and ::logistic_regression wrap an already fitted model. Attaching validates three things before allocating anything:

  1. the base family has a coefficient block (trees and neighbours do not);
  2. the adapter’s target module matches the base family;
  3. the base has at least one feature and one head.

A family without a coefficient block enters as SKLoraBaseModel::unsupported_family("decision_tree") and attaching returns UnsupportedOperation with a reason naming the family. That is the an_unsupported_base_family_is_rejected test, and the requirement that no unsupported path panics.

The factors start deterministically: B is all zeros and A is a small, fixed pattern computed from its indices. Because B is zero, the initial update is exactly the zero matrix. That is why a_zero_adapter_predicts_exactly_like_the_base can assert bit-for-bit equality with the frozen base, not merely a tolerance.

Fitting only the thin matrices

SKLoraAttachedModel::fit dispatches once on the target module and hands the work to fitting/linear.rs or fitting/logistic.rs:

  • A regression base consumes continuous targets and minimizes the mean squared error.
  • A classifier base consumes canonical integer class indices and minimizes the logistic loss — binary cross-entropy for one head, softmax cross-entropy for several.

Both descents share the same discipline:

  • the gradients are computed from the residual (regression) or the probability error (classification), never from a dense copy of a sparse input;
  • sk_transposed_feature_product in fitting/gradients.rs handles dense and CSR designs, so Xᵀ never requires densifying;
  • each accepted iteration must strictly decrease the loss. A backtracking loop halves the step up to a fixed number of attempts before accepting it, so the reported loss is monotone even when the data has a difficult scale.

The training verdict is observable through training_loss, which returns the same number the optimizer minimizes. It validates its inputs exactly like fit does before touching the loss: a feature count that disagrees with the base, a target vector whose length disagrees with the rows, and a non-finite feature or target all return a typed error instead of panicking or silently truncating (training_loss_rejects_a_feature_count_that_disagrees_with_the_base, training_loss_rejects_a_target_count_that_disagrees_with_the_rows). The test fitting_reduces_the_training_loss_below_the_frozen_base compares the loss before and after the fit on a shifted relationship, and fitting_reduces_the_logistic_loss_below_the_frozen_base does the same for a classifier on a rotated decision rule.

Determinism matters as much as convergence: there is no random initialization. two_fits_on_the_same_data_produce_identical_factors fits twice and asserts that A and B are equal, which is what lets an exported adapter be reproduced.

Applying versus merging

There are two ways to use a trained adapter, and they answer different needs.

Apply keeps the base frozen and adds the update at prediction time. Every prediction computes the effective block and applies the base’s own matrix product:

#![allow(unused)]
fn main() {
/// The adapted parameter block `W + (alpha / rank) · B A`.
pub(crate) fn effective_coefficients(&self) -> Result<Array2<F>, SKError> {
    Ok(self.base.coefficients()? + self.delta())
}
}

Merge folds the update into a standalone native model:

#![allow(unused)]
fn main() {
pub fn merge(&self) -> Result<SKLoraMergedModel<F>, SKError> { ... }
}

The merged model carries a real SKLinearRegressionModel or SKLogisticRegressionModel whose coefficient block is W', and unmerge returns the original frozen base plus the adapter. Because apply and merge use the same effective block and the same scoring helper, predictions are not merely close: merged_prediction_reproduces_the_attached_prediction_exactly asserts bit-for-bit equality.

The numerical proof is the pair of tests merged_coefficients_equal_the_hand_computed_low_rank_update and the_low_rank_reference_holds_for_single_precision. They set known factors, compute the reference $\frac{\alpha}{r} B A$ explicitly in the test, add it to the base block by hand, and check that the adapter’s predictions differ by less than 1e-9 — for f64 and for f32. The f32 case is the interesting one: the reference uses the fitted intercept, not a hard-coded constant, because the base intercept itself already carries single-precision rounding.

Prediction never densifies: dense_and_sparse_predictions_agree_without_densifying runs the same rows as a dense matrix and as a CSR matrix and compares the two result vectors.

Storing an adapter apart from its base

An adapter is stored separately for a practical reason: the base model is already persisted, often large, and shared by several tasks. Storing the base again for every adapter would multiply the storage and create many near-copies that can drift.

SKExportable writes a state with metadata (identifier, rank, alpha, target, heads, fitted, optimizer budget, backend) and exactly two tensors, lora.<target>.a and lora.<target>.b. SKLoraAdapterArtifact reads them back, validates the shapes against the metadata, and only then pairs the adapter with a base through attach.

The validation tests stay on the trust boundary: a tampered B shape returns ShapeMismatch (a_tampered_factor_shape_is_rejected_without_a_panic), a state without A returns InvalidHyperparameter (a_missing_factor_tensor_is_rejected), a stored factor carrying NaN or infinity returns NonFiniteValue (a_non_finite_stored_factor_is_rejected_on_import), and a round trip reproduces the original predictions exactly (a_round_trip_preserves_predictions_exactly). No untrusted length, shape or value is ever unwrapped.

SKLoraAdapterRegistry addresses several adapters by identifier. Inserting the same identifier twice is an error naming the identifier (duplicate_adapter_identifiers_are_rejected); the registry never silently replaces one task’s adapter with another’s.

Concurrency and acceptance

SKLoraAttachedModel<F> and the registry are Send + Sync; the compile-time check is an_adapter_is_send_and_sync. concurrent_prediction_matches_the_sequential_result shares one fitted adapter across eight threads and asserts every result equals the sequential one. The acceptance tests also cover a single row and a single feature (a_one_row_one_feature_fit_still_produces_a_finite_prediction), a 600-row design (a_large_design_is_fitted_and_the_loss_falls), and a three-class logistic adapter (a_multiclass_logistic_adapter_runs_and_lowers_the_loss).

Decisions and roads not taken

  • Gradual or alternating least squares were considered for the regression fit. The shipped path is a monotone gradient descent with backtracking: it is smaller, works for both dense and sparse designs, and every accepted iteration can be proven to reduce the loss. Alternating solves remain a possible performance upgrade inside fitting/linear.rs.
  • Random initialization was rejected. A deterministic pattern plus a zero B makes the zero adapter exact, makes two fits identical, and removes a seed from the public configuration.
  • Full-model fine-tuning is out of scope. The base is frozen by construction, not by convention.
  • Deep-network LoRA is out of scope too: the library’s current families are linear and logistic models with matrix-valued coefficients, and the enum SKLoraTargetModule says so explicitly. A future neural estimator would add a variant, not change this one.
  • Storing the product B A was rejected: it would lose the low-rank structure and make the adapter as large as the base block it corrects.

When you change this code

Keep the three invariants that the tests encode: the zero adapter must reproduce the base exactly, merge must reproduce apply exactly, and persisted shapes must be validated before use. When you extend the surface, update this chapter rather than adding a parallel one; lora_acceptance_tests.rs and the other lora_*_tests.rs companions are the executable source of truth.

The umbrella crate: one door into many rooms

This chapter explains what an umbrella crate is, why sciencekit ships one, and how it is built without duplicating a single line of algorithm code. It assumes no Rust and no machine-learning background. Every claim points at real code under src/ at the workspace root and at a companion test you can run.

The previous chapters told the story one crate at a time: sciencekit_common fixed the vocabulary, sciencekit_math supplied the kernels, and each algorithm family arrived as its own package. Twenty-one packages is honest engineering and terrible onboarding: a newcomer has to know that a scaler lives in sciencekit_preprocessing, a cost function in sciencekit_common and a metric in sciencekit_metrics. The umbrella answers the only question a newcomer actually asks: what do I add to Cargo.toml?

One dependency, many packages

A Cargo package is a named unit with its own Cargo.toml; a crate is what it compiles to. The umbrella is a package that owns almost no code of its own: it depends on the family packages and re-exports their public items. A re-export is a signpost, not a copy — pub use sciencekit_linear_model::SKRidge; means “the name SKRidge exists here too, and it is the same type the other crate defines”.

That identity matters. If the umbrella defined its own SKRidge, a model fitted through the umbrella would not be accepted by a function written against sciencekit_linear_model, and the ecosystem would split in two. Rust’s type system makes accidental duplicates a compile error precisely so that a re-export can stay honest: one type, several doors.

flowchart TB
    subgraph Packages["Workspace packages"]
        C["sciencekit_common<br/>vocabulary"]
        M["sciencekit_math<br/>kernels"]
        P["sciencekit_preprocessing<br/>scalers · encoders"]
        L["sciencekit_linear_model<br/>regression · logistic"]
        T["sciencekit_tree<br/>CART"]
        E["sciencekit_ensemble<br/>forests · boosting"]
    end
    U["sciencekit umbrella<br/>re-exports only"]
    U -->|"pub use"| C
    U -->|"pub use"| M
    U -->|"pub use"| P
    U -->|"pub use"| L
    U -->|"pub use"| T
    U -->|"pub use"| E
    APP["user crate"] -->|"one dependency"| U
    APP -.->|"still possible"| L
    style C fill:#BFDBFE,stroke:#1D4ED8,color:#111
    style M fill:#DDD6FE,stroke:#6D28D9,color:#111
    style P fill:#A7F3D0,stroke:#047857,color:#111
    style L fill:#FED7AA,stroke:#C2410C,color:#111
    style T fill:#FDE68A,stroke:#B45309,color:#111
    style E fill:#FBCFE8,stroke:#BE185D,color:#111
    style U fill:#FCA5A5,stroke:#B91C1C,color:#111
    style APP fill:#E0F2FE,stroke:#0369A1,color:#111
    accTitle: The umbrella is a set of doors, not a second implementation
    accDescr: Each family package keeps its own implementation, the umbrella re-exports those exact types, and a user crate can depend on the umbrella alone or still reach a single family package directly.

A decision that changed shape: the crate already existed

The original plan said “create crates/sciencekit”. Cargo refuses two packages with the same name in one workspace, and the root package was already called sciencekit — an empty src/lib.rs kept as the umbrella slot. Creating a second sciencekit was impossible, so the umbrella was implemented in the existing root package: the same public outcome (sciencekit is the one crate users add), one fewer package, and no rename of the published crate.

The only visible consequence is the file layout: the family modules live in src/<family>.rs at the root instead of crates/sciencekit/src/. The exported names and paths are identical either way.

A prelude is not a glob import

Rust lets you write use sciencekit::*; to import everything public at the crate root. The umbrella deliberately does not flatten every family there. Two reasons, both practical:

  1. Collisions. Three different families own a type called SKClassWeight: the tree/ensemble split policy, the logistic-regression class policy and the support-vector-machine policy. They are different types with different fields. Flattening them into one namespace would force a rename that lies about the domain, or would silently drop two of them.
  2. Compile time and documentation noise. A glob pulls in hundreds of names, most of which a given program never uses. Documentation pages become a wall of unrelated items.

A prelude is the opposite design: a small, curated module with a stable list of names that are almost always wanted together — the builder and fit traits, the data views, the error type, the scalar bound, and one or two headline estimators per family. You opt in with use sciencekit::prelude::*;, and you opt out of the noise. When a name is not there, its family module is one import away.

flowchart LR
    ROOT["sciencekit root<br/>SKError · SKBuilder · data views"]
    FAM["family modules<br/>preprocessing · linear_model · svm · …"]
    PRE["prelude<br/>curated shortlist"]
    USER["your program"]
    ROOT --> USER
    PRE --> USER
    FAM --> USER
    PRE -.->|"selected names only"| ROOT
    PRE -.->|"selected names only"| FAM
    style ROOT fill:#A7F3D0,stroke:#047857,color:#111
    style FAM fill:#BFDBFE,stroke:#1D4ED8,color:#111
    style PRE fill:#FED7AA,stroke:#C2410C,color:#111
    style USER fill:#E0F2FE,stroke:#0369A1,color:#111
    accTitle: Root, families and prelude feed the same program
    accDescr: The crate root re-exports the shared vocabulary, family modules expose the full algorithm surface, and the prelude is a curated shortlist drawn from both. A program can mix all three.

The collision decision is executable. The companion test colliding_names_live_in_their_family_modules in src/reexports_tests.rs asserts that all three SKClassWeight types resolve through their own module, and that duplicated identities stay identical:

#![allow(unused)]
fn main() {
sized::<crate::tree::SKClassWeight<f64>>();
sized::<crate::linear_model::SKClassWeight<f64>>();
sized::<crate::svm::SKClassWeight<f64>>();

sized::<crate::SKFeatureBlock<f64>>();
sized::<crate::pipeline::SKFeatureBlock<f64>>();
}

The second pair is the safe case: sciencekit_common owns SKFeatureBlock, and the pipeline crate deliberately re-exports that same type rather than inventing a block of its own. Two doors, one room. The same test module proves the identity for the device vocabulary, SKOutlierLabel, SKKernel and the tree/ensemble split vocabulary: each helper function only compiles when both paths name one type.

A third shared name is quieter but recorded: SKSplitter is a split-selection enum in tree and the train/test partitioning trait in model_selection. One is a value, the other a contract, and neither is in the prelude, so the bare name never reaches a program unqualified — but the family module is always the safe door.

The build → fit → predict walk-through

The executable form of “the prelude is enough” is prelude_builds_fits_and_predicts in src/prelude_tests.rs. It imports only sciencekit::prelude::* and runs a complete, if tiny, learning program:

#![allow(unused)]
fn main() {
let scaler = SKStandardScaler::build().build().unwrap();
let scaled = scaler.fit(features.view()).unwrap();
let scaled_features = scaled.transform(features.view()).unwrap();

let model = SKLinearRegression::build()
    .build()
    .unwrap()
    .fit(scaled_features.view(), targets.view())
    .unwrap();
let predictions = model.predict(scaled_features.view()).unwrap();
}

Read it as three sentences. SKStandardScaler::build() starts a builder — the library’s uniform configuration surface — and the second .build() validates the configuration and returns the estimator. fit learns from the design and returns a distinct fitted model; the estimator itself never mutates, so “not yet fitted” is unrepresentable. The regression step solves the ordinary least-squares problem

$$ \hat{\beta} = \arg\min_{\beta \in \mathbb{R}^{p}} ; \lVert X\beta - y \rVert_2^2 , $$

and predict evaluates $\hat{y} = X\hat{\beta}$ on the same scaled design. The test then checks that every prediction is within $10^{-6}$ of its target — a trivial tolerance because the synthetic data is exactly linear.

The second test, prelude_exposes_metrics_for_a_fitted_model, closes the loop with a score reachable from the same prelude:

$$ \text{accuracy}(y, \hat{y}) = \frac{1}{n} \sum_{i=1}^{n} \mathbf{1}!\left[\hat{y}_i = y_i\right] . $$

Its inputs are plain slices and its output is generic over the scalar bound, so the test writes let score: f64 = sk_accuracy_score(&truth, &predicted).unwrap(); and asserts the expected $0.75$ on four labels.

Optional integrations behind features

The umbrella compiles the core by default and nothing else. Three integrations pull in substantial dependency trees — an OpenTelemetry SDK, the ONNX translator, the GPU runtime — and four engine adapters pull in Polars, DataFusion, Arrow/Parquet or memory mapping. Making them mandatory would tax every user for a capability most never use.

Cargo features solve this. A feature is a named switch that turns dependencies on. The umbrella forwards rather than duplicates:

[features]
default = []
opencl = [
    "dep:sciencekit_gpu_opencl",
    "sciencekit_gpu_opencl/gpu-opencl",
    "sciencekit_gpu/opencl",
]
telemetry = ["dep:sciencekit_telemetry", "sciencekit_telemetry/telemetry"]
otlp-grpc = ["dep:sciencekit_telemetry", "sciencekit_telemetry/otlp-grpc"]
onnx = ["dep:sciencekit_onnx"]
parquet = ["sciencekit_interop/parquet"]
allocator-jemalloc = ["sciencekit_common/allocator-jemalloc"]

Forwarding is not only about dependencies: telemetry also forwards the sub-crate’s own telemetry feature, because enabling the crate alone would leave every OTLP transport compiled out and the pipeline builder would answer “enable feature otlp-grpc or telemetry” forever. The separate otlp-grpc/otlp-http switches exist for a build that wants one exporter stack; allocator-jemalloc/-mimalloc, observability-export and the three compression-* codecs are forwarded the same way. Three sub-crate features are deliberately not forwarded: blas-backend needs a system BLAS at link time, and gpu-cuda/gpu-rocm have no backend to select yet.

The dep: syntax means “enable this optional dependency without also creating a public feature of the same name” — the umbrella’s feature names are its own vocabulary, not an accident of package names. sciencekit_gpu_opencl/gpu-opencl reaches into the sub-crate’s own feature, so the two switches cannot disagree.

Features are additive: enabling one never removes core code. The companion test optional_integrations_mirror_their_features in src/features_tests.rs wraps each reachability assertion in its #[cfg(feature = "...")], so the same test file proves the core in a bare build, the ONNX re-exports under --features onnx, the adapters under --features polars, and so on. The CI matrix runs cargo check -p sciencekit --no-default-features plus one build per feature; the test is the part that stays with the code.

Roads not taken

  • One giant crate. Folding every algorithm into sciencekit would remove the dependency graph but destroy independent consumption: a user who wants only a scaler would compile forests and ONNX with it. The workspace keeps twenty-one small packages and one thin door.
  • Flattening every family at the root. Convenient until the first collision, then either a rename that misleads or a silent omission. Named modules keep the taxonomy visible.
  • A prelude that re-exports everything. The prelude would become a second glob with worse documentation. The shortlist is intentional; the family modules remain the full catalogue.
  • Making the umbrella a version line of its own. It inherits version.workspace = true, so a release bumps one line and every re-export points at the matching sub-crate version.
  • Dropping a family module that grew later. The low-rank adapters landed in sciencekit_linear_model after the umbrella’s first draft, and an explicit item list would have hidden them. The linear_model family re-exports adapters and its types, and the_low_rank_adapter_api_resolves in src/reexports_tests.rs fails the build if that door closes again. The same test-backed discipline covers any future family: extend the module, add a compile test, then trust the list.

What the reader should take away

An umbrella crate is a documentation and onboarding decision, not an algorithmic one. It adds no logic, no state and no version line; it adds a stable set of doors, a curated prelude, and feature switches that keep the default build small. When you add a new family, extend the matching family module, add one or two headline names to the prelude only if they are broadly useful, gate any heavy dependency behind a forwarded feature, and extend the three companion tests — reexports_tests, prelude_tests and features_tests — so the book and the code keep telling the same story.

The workflows CLI: a reproducible experiment in one file

This chapter explains the sciencekit command-line interface from zero: why a library that already has a Rust API ships a binary, what a workflow file records and why it is versioned, how a value is resolved when a flag, an environment variable, a file and a default disagree, and why exit codes are part of the public contract. Every claim points at real code under crates/sciencekit_cli/src/ and at an integration test that runs the compiled binary.

The previous chapter opened one door into the library: the umbrella crate. This chapter adds a second door for people who do not write Rust. Both doors lead to the same algorithms; neither keeps a private copy.

Why a CLI over the library

A Rust API answers “how do I call a function”. It does not answer “how do I rerun last week’s experiment on a new machine”. That second question needs three things the library cannot own by itself:

  1. A file format for the experiment. Which dataset, which target column, which scaler, which estimator, which penalty grid, which metrics, which output paths.
  2. A resolution rule. The same experiment must accept an override from a shell script without editing the file.
  3. A process contract. Automation needs a number it can branch on, not a sentence printed to a terminal.

The binary is a thin orchestration layer. It parses arguments, resolves the configuration, calls the umbrella crate and writes the declared artifacts. It never reimplements a scaler, a metric or a model format. That boundary is a design decision, not a limitation: a second implementation would drift from the library every time an algorithm changed.

Reproducible means byte-reproducible. The Safetensors encoder writes its metadata from ordered maps and orders tensor payloads by descending alignment and then by name, so two runs of one workflow produce the same model bytes. tests/reproducibility_tests.rs runs one workflow twice into two directories and compares the model and predictions files byte for byte; the interop unit test safetensors_determinism_tests.rs pins the sorted header. A run also preflights every declared output — destination directory and format capability — before it writes the first file, so a failing predictions path or a missing Parquet feature exits non-zero without leaving a half-written experiment record (tests/preflight_tests.rs).

flowchart LR
    A["workflow.json<br/>the experiment record"] --> L["loader + validator<br/>typed paths"]
    F["CLI flags"] --> R["resolution<br/>flags > env > file > defaults"]
    E["SCIENCEKIT_*<br/>environment"] --> R
    L --> R
    R --> X["command dispatch"]
    X --> U["sciencekit umbrella"]
    U --> D["dataset adapters"]
    U --> M["estimators + metrics"]
    M --> O["model · predictions<br/>metrics · inspection"]
    X --> C["exit code contract"]
    style A fill:#FDE68A,stroke:#B45309,color:#111
    style F fill:#BFDBFE,stroke:#1D4ED8,color:#111
    style E fill:#DDD6FE,stroke:#6D28D9,color:#111
    style R fill:#FCA5A5,stroke:#B91C1C,color:#111
    style U fill:#A7F3D0,stroke:#047857,color:#111
    style C fill:#FBCFE8,stroke:#BE185D,color:#111
    accTitle: The CLI resolves one experiment and dispatches it to the library
    accDescr: A workflow file, CLI flags and environment variables feed one resolution step; the command then calls the umbrella crate for datasets, estimators, metrics and artifacts, and reports the outcome through stable exit codes.

The workflow schema is a reproducible experiment record

A workflow is a JSON or TOML document (YAML behind the yaml feature) with a version and up to five sections: dataset, pipeline, estimator, search, metrics and output. The structs live in crates/sciencekit_cli/src/workflow/schema.rs; the version is SK_WORKFLOW_SUPPORTED_VERSION = 1.

{
  "version": 1,
  "dataset": { "format": "csv", "path": "data.csv", "target": "y" },
  "pipeline": [{ "transformer": "standard_scaler", "with_mean": true }],
  "estimator": { "name": "ridge", "alpha": 1.0 },
  "search": { "kind": "grid", "alphas": [0.1, 1.0], "folds": 2 },
  "metrics": ["r2", "rmse"],
  "output": { "model": "model.safetensors", "predictions": "predictions.csv" }
}

The schema is deliberately versioned. A future release can add a section without guessing what an old file meant, and an old binary can refuse a future file instead of silently ignoring half of it. The loader (workflow/loader.rs) parses every format into one JSON value, runs sk_validate_workflow_value and only then deserializes into SKWorkflow. Validation is typed: SKWorkflowError in workflow/error.rs distinguishes an unsupported version, an unknown field, a missing field and a wrong type, and every variant exposes a dotted path() such as workflow.estimator.alpha. Unknown keys are rejected on purpose — a typo in alpha must fail loudly, not fall back to the default.

The version check happens before anything else, so a version-2 file never reaches an estimator. The integration test invalid_workflow_reports_the_offending_path_with_exit_code_two in tests/error_tests.rs runs the binary against {"version": 2} and against a misspelled estimator key, and asserts both the exit code and the exact dotted path on stderr.

Precedence is one equation

Four layers can supply the same value. They are merged in a fixed order, each layer overwriting only the fields it sets:

$$\text{flags} \succ \text{environment} \succ \text{workflow file} \succ \text{defaults}$$

The code makes that order literal. config/precedence.rs builds the defaults, applies sk_file_overrides, then the environment layer, then the flag layer. Each layer is a SKConfigurationOverrides value whose fields are Options: None means “this layer has no opinion”, which is exactly what lets a flag win without erasing the fields it does not set. SCIENCEKIT_ALPHA, SCIENCEKIT_ESTIMATOR, SCIENCEKIT_MODEL and the other SCIENCEKIT_* variables form the environment layer in config/environment.rs.

--dry-run renders the resolved configuration as JSON and stops before any artifact is written. It also validates that the dataset exists, that the output directories exist and that every enumerated value is one the commands accept: dataset, output and model formats, estimator and metric names, and the backend. A dry run that prints cleanly is therefore executable; tests/validation_tests.rs runs the binary with an invalid dataset format, output format, metric, estimator and backend, and with an invalid workflow output.format, and asserts each one fails here instead of halfway through a fit. tests/config_tests.rs proves all four levels in one test, precedence_resolves_flags_over_environment_over_file_over_defaults: the file sets alpha = 2.0, the environment sets 3.0, a flag sets 4.0, and the test asserts 4.0, then 3.0, then 2.0, then the default 1.0.

An artifact format is one of those layers: a flag, SCIENCEKIT_OUTPUT_FORMAT or the workflow’s output.format decides the format, and only when none of them has an opinion does the output file extension infer it. The resolved configuration records that provenance in output_format_explicit, so predict/transform cannot quietly fall back to CSV for a workflow that asked for JSON, and an empty environment variable is ignored rather than treated as a choice (tests/config_tests.rs covers both).

Exit codes are a contract

A shell script cannot parse prose. The binary therefore maps every failure to a documented number, defined by SKExitCode in cli/exit_codes.rs:

CodeMeaning
0success; every declared artifact was written
2usage or validation: bad flags, invalid workflow, bad value
3dataset or model I/O: missing file, malformed artifact
4a capability this build was compiled without
1an unexpected runtime failure

The classification lives next to the error type in src/error.rs, so a new command cannot invent a new number. Clap’s own usage failures already exit with 2, which is why the contract starts there rather than at 1. tests/error_tests.rs pins three of the five codes against the real process: an invalid workflow exits 2, a missing model exits 3, and a format whose Cargo feature is off exits 4 with a message naming that feature. The dry-run validation tests above extend the 2/4 cases to every enumerated configuration value.

Every subcommand in one pass

  • fit loads the dataset, optionally fits a feature pipeline, fits a regression estimator (ridge, linear_regression) or a transformer (standard_scaler, minmax_scaler, robust_scaler) and writes a model artifact. SKRidge receives the configured penalty and backend.
  • predict imports the artifact into a native model (sk_import_native_model_from_path), predicts on the input matrix and writes CSV, JSON or Parquet predictions.
  • transform imports a fitted transformer and writes the transformed matrix with one column per output feature.
  • evaluate predicts, then computes the selected metrics (r2, rmse, mse, mae) through sciencekit_metrics and prints or writes a JSON document.
  • export reads a neutral SKModelState and writes Safetensors, JSON or ONNX (the last behind the onnx feature).
  • inspect prints the estimator name, format version, feature count, tensor count and tensor names without loading a model for prediction.
  • run executes the workflow: it loads the dataset, applies every pipeline step, optionally runs a K-fold grid search over the penalty candidates (workflow/steps.rs), fits the winner on the full matrix, computes the metrics and writes every declared artifact.

The two end-to-end tests in tests/command_tests.rs walk through the whole surface. fit_then_predict_inspect_and_export_run_end_to_end fits ridge on a six-row linear dataset, predicts, parses the first prediction back into f64, inspects the model, exports it to JSON and inspects the export. transform_evaluate_and_run_workflow_produce_artifacts fits a scaler, transforms the matrix, evaluates ridge, then runs a workflow with a standard_scaler pipeline and a two-candidate grid, asserting that both the model and the predictions exist afterwards.

Features change what the binary can do, never what it means

CSV and Parquet input use the interop Arrow sources; model artifacts use the interop Safetensors and JSON formats. Parquet output, YAML workflows and ONNX translation are optional Cargo features. When one is missing, the binary does not fail with a generic “unsupported”: it names the feature and exits 4, so a caller can tell a missing build capability from a broken file. The feature tests in tests/feature_tests.rs prove the enabled paths — a_yaml_workflow_executes_end_to_end, a_parquet_dataset_fits_and_parquet_predictions_round_trip and onnx_export_and_import_round_trip_a_fitted_model — while the default build proves the disabled path with workflows-cli’s feature-absent error.

Telemetry is the same idea. When SCIENCEKIT_OTLP_ENDPOINT is set, src/telemetry.rs builds an SKTelemetryConfiguration from the environment, initializes the pipeline once, and holds a guard whose Drop implementation flushes and shuts it down. If the endpoint is set but the telemetry feature is off, the process exits 4 instead of pretending it exported anything.

Decisions and roads not taken

  • A CLI crate, not a binary in the umbrella. The umbrella adds no logic, so putting argument parsing inside it would break that promise and force every library user to compile clap. crates/sciencekit_cli depends on the umbrella and is the only package that knows about terminals.
  • Versioned JSON/TOML first, YAML optional. JSON is unambiguous and TOML is pleasant for humans; serde_yaml_ng is a small optional dependency rather than a mandatory parser.
  • Reject unknown fields. A permissive schema turns typos into silent defaults. The typed validator costs a few dozen lines and saves hours.
  • No server, scheduler, distributed execution, GUI or cloud storage. Those are different products. The binary is one process that finishes.
  • No second estimator implementation. The CLI composes the same builders the Rust API exposes; a feature it cannot express yet is an honest error, not a private code path.

Where to change what

  • A new subcommand starts in cli/arguments.rs, dispatches from cli/commands/mod.rs, and lives in its own file under cli/commands/.
  • A new workflow key starts in workflow/schema.rs, then the allowed-key list in workflow/validation.rs, then the file layer in config/precedence.rs.
  • A new exit-code meaning is a change to cli/exit_codes.rs and src/error.rs together, plus a test in tests/error_tests.rs.
  • A new format belongs in io/, behind a feature, with a disabled-feature test next to the enabled one.

When you change behaviour, edit this chapter rather than adding a parallel one, and run mdbook build docs so the Mermaid diagrams and the links stay truthful.

Maintaining this book

A textbook is only worth reading if it stays true. This book explains why sciencekit is built the way it is, and sciencekit is not finished — the roadmap (docs/PRD.md) maps out new algorithms in phases that stretch from preprocessing all the way to trees, ensembles, clustering and Python bindings. Every one of those algorithms will change the library, and every change risks turning a sentence in this book into a lie. This chapter is the contract that keeps the book truthful: a small set of rules that decide when to add a chapter, when to edit one, and how every update flows safely from a branch to the published site.


1. The problem we were solving

Documentation rots. It is not a bug in any single sentence; it is a slow drift. Someone adds a new algorithm, nobody updates the matching page, and six months later the book describes a SKKNeighborsClassifier that behaves nothing like the code. A reader who trusts the book builds the wrong mental model, and the wrong mental model produces subtle, expensive bugs.

You cannot stop change, so the only fix is to make keeping up a mechanical habit. sciencekit already commits to this habit at the repository level — its AGENTS.md requires that every code change ships a companion documentation change on its own branch, merged separately. This chapter is where that general rule becomes a concrete procedure for this book: when a feature lands you add a chapter; when behavior changes you update the chapter; and both are done through the same worktree-and-branch machinery that keeps main clean.


2. The decisions — and the roads not taken

DecisionWhy we chose itAlternatives we discarded
A new feature or algorithm → a NEW chapterA genuinely new algorithm is a new concept with new objects, new tests and new rationale. It deserves a teaching arc of its own; bolting it onto an existing chapter would bury it and make that chapter too long to follow. The roadmap’s phases arrive one algorithm at a time, so the book grows one chapter per algorithm.Amending every feature into a giant “everything” chapter — it becomes an unreadable dump.
A bug fix or refactor → UPDATE the existing chapterA bug fix or refactor changes behavior, not concept: the chapter’s question (“why does this object exist?”) stays valid, but some of its answers change. Editing in place keeps the story honest without duplicating it. The rule is therefore update, never fork — do not leave a stale chapter and add a “new and improved” twin.Copying the chapter and writing a parallel “v2” version — two chapters drift apart and readers never know which is current.
Every doc change ships on its own docs/<name> branch merged into docs/documentationsThe book is a deployable artifact: pushing to docs/documentations rebuilds and publishes it to GitHub Pages. Working on a dedicated branch means main and docs/documentations never receive half-finished prose, and the same change can be reviewed independently of the code PR that motivated it.Committing doc edits straight to docs/documentations — risky, unreviewed, and it bypasses the two-worktree discipline used for code.

3. The concepts, taught from zero

What “shipping a doc change” means

In most projects you might finish a feature and also remember to update the docs. In sciencekit that is not optional and not deferred: AGENTS.md says every code change is paired with a documentation change that updates the mdBook for the newly introduced behavior, “on its own doc branch and its own PR merged into docs/documentations”. The doc branch is created at the same time as the code change, not after it.

The two documentation branches

  • docs/documentations is the landing branch: the finished book lives here, and the GitHub Actions workflow (.github/workflows/deploy-documentation.yml) builds and deploys it to GitHub Pages on every push.
  • docs/<name> is a working branch. You never write on docs/documentations directly; you open a worktree for your change and merge it in when it is ready.

This is deliberately separate from the -openspec planning branch, which only holds the OpenSpec planning artifacts. Documentation (the book) and planning (the spec) are two different concerns and use two different branches.

What “worktree” means here

A git worktree lets you check out a branch into a separate folder without disturbing your current checkout. Every docs change lives in temporary/worktrees/docs/<name> on branch docs/<name>. temporary/ is git-ignored, so these working copies are never committed — they are scratch space that keeps each change isolated.


4. Each object, explained

The chapter file

What it is — a markdown file under docs/src/development-explained/, one per chapter, following the anatomy in the chapter template (CHAPTER_TEMPLATE.md).

Why it exists — each chapter is the durable record of one concept’s design rationale, taught from zero for a reader who knows programming but not Rust or numerical computing.

What we rejected — putting everything in one huge page; a single page cannot teach or be maintained.

The worktree and branch

What it is — temporary/worktrees/docs/<name> on branch docs/<name>.

Why it exists — it isolates a doc change so the deployable docs/documentations branch only ever receives finished, reviewed prose.

What we rejected — editing docs/documentations directly; unreviewed edits reach the published site immediately.

The build gate

What it is — mdbook build docs, run locally before pushing.

Why it exists — it validates every chapter and its links before the change is merged; the book’s config uses create-missing = false, so a broken link fails the build rather than silently generating an empty page. The gate must pass with zero warnings.

What we rejected — relying on the remote deploy workflow to catch errors; that would let broken content reach the published book.


5. A real walk-through: adding an algorithm’s chapter

Here is the exact procedure, using a hypothetical new algorithm from a later roadmap phase (say a tree model arriving in Phase 4).

Step 1 — open the worktree. Create the docs change alongside the code change:

git worktree add temporary/worktrees/docs/sk-decision-tree docs/sk-decision-tree

Step 2 — write the chapter. Create docs/src/development-explained/chNN-*.md following the template: the plain-language problem, the decisions table, concepts taught from zero, each object explained, and a walk-through built from the real *_tests.rs tests. Keep code identifiers exactly as they are in the source.

Step 3 — register the chapter. Add it to the table of contents in docs/src/SUMMARY.md under the right part of the book, in the position that matches the reading order.

Step 4 — run the gate.

mdbook build docs

Fix every warning. A warning here means the published book could be broken.

Step 5 — merge. Open a PR for branch docs/sk-decision-tree into docs/documentations. When it merges, the deploy workflow rebuilds and publishes the book automatically.

The successive-halving chapter (chapter 53) is the worked example of this path for a new algorithm: the search lives in crates/sciencekit_model_selection/src/halving/, its companion tests (halving_scheduler_tests.rs, halving_trace_tests.rs, halving_subsample_tests.rs, halving_evaluation_tests.rs, halving_aggressive_tests.rs, the per-family halving_refit_tests.rs modules, the concurrency and representation tests, and acceptance_tests/halving/) are cited by name in the chapter, and the chapter, its SUMMARY.md entry and the halving rows in docs/src/algorithms.md all landed together on the docs/halving-grid-search-book branch.

Updating, not forking

If the change is a bug fix or refactor, replace the affected part of the existing chapter — the decisions table, the object descriptions, the walk-through — and adjust any prose that now contradicts the code. Do not copy the chapter and add a “v2”. The book stays truthful because there is exactly one place where a given behavior is explained, and it is always the current explanation.

Keep the numbers honest. The book is a textbook, but it is also a status document: algorithm counts, phase pills and roadmap states must match the real roadmap state in docs/PRD.md. When a roadmap phase flips from "Planned" to "In progress", the roadmap page and the new chapter should move together.

6. Look inside

flowchart LR
    accTitle: How a code change flows into the documentation
    accDescr: A code change opens a code worktree branch and a docs worktree branch. The code branch becomes a code pull request. The docs branch must pass mdbook build with zero warnings, then becomes a doc pull request merged into docs/documentations, which deploys to GitHub Pages.
    C[code change] --> B1[worktree code branch]
    C --> B2["worktree docs branch"]
    B1 --> P1[code PR]
    B2 --> G["mdbook build docs<br/>zero warnings"]
    G --> P2["doc PR → docs/documentations"]
    P2 --> D["deploy → GitHub Pages"]

The docs branch is created at the same moment as the code branch, runs through its own build gate, and lands on docs/documentations through its own PR — the same “two coexisting worktrees, two separate PRs” discipline that governs code.


7. Recap

  • A new feature or algorithm → add a new chapter, registered in SUMMARY.md.
  • A bug fix or refactor → update the existing chapter in place; never add a parallel twin.
  • Every code change ships its doc change on a docs/<name> branch merged into docs/documentations — created alongside the code change, never deferred.
  • mdbook build docs must pass with zero warnings before you push; broken links fail the build, and the deploy happens automatically on merge.
  • Keep counts, phases and status in sync with docs/PRD.md.

Next chapter: we step down from the meta and back into the code, where the algorithms built with these rules — SKStandardScaler, SKMinMaxScaler, SKRobustScaler, the encoders, the imputers, the first supervised model SKLinearRegression, the first regularized one, SKRidge, and the L1-regularized pair SKLasso & SKElasticNet — and the first classifier, SKLogisticRegression — show the whole procedure in action. The stochastic-gradient family (SKSGDClassifier & SKSGDRegressor) then shows the same rules applied to an estimator whose cost does not depend on the dataset size. The source-provider chapter closes the streaming story: one seam that accepts both a concrete source and a reopenable factory, and the epoch rule each estimator class follows. The owned feature block chapter completes it: sparse data streams without ever being densified, and implicit zeros shape every statistic. The metrics foundation chapter then turns all of that work into numbers: a label space, a confusion matrix, per-class scores, regression errors and the mergeable accumulators that make evaluation streaming and parallel. The deterministic randomness chapter adds the seed convention every stochastic estimator shares: SplitMix64, pure sub-seed derivation and thread-count invariance. The sparse distance chapter then shows how one dispatcher serves all four dense/sparse representation pairs without ever densifying a sparse design. The ranking metrics chapter closes the evaluation story with ROC/AUC, precision-recall, log loss, balanced accuracy and MCC. The type-safe pipeline chapter then composes transformers and a final estimator into a chain whose validity is checked by the compiler, not at fit time. The spatial index chapter adds exact k-d and ball trees: lower bounds, deterministic tie ordering, and the dense-only exception applied to geometry. The dataset interop chapter adds the engine-neutral seam: ordered schema, explicit selection, one missing-value policy, typed batches, streaming sources and the async bridge. The k-means chapter adds the first unsupervised estimator: seeded k-means++, the Lloyd iteration, Elkan pruning, empty-cluster repair and the typed cluster assignments. The decision tree chapter adds CART: impurity, dense and sparse split search, deterministic ties, feature subsampling, class weights and importances. The model selection chapter adds train/test split, the three K-fold flavours, row gathering and cross-validation scoring. The C ABI chapter adds the stable boundary every non-Rust binding wraps: opaque handles, borrowed and owned arrays, status codes, panic containment and persistence. The clustering metrics chapter adds silhouette, ARI, NMI, homogeneity/completeness/V-measure and the centroid indices. The k-nearest neighbours chapter adds the brute-force searcher, the runtime strategy dispatch, weighting and the estimator representation parity. The k-NN imputer chapter adds the NaN-aware donor search, chunked distance blocks, weighting with a column-mean fallback and the dense-only contract. The grid search chapter adds candidate enumeration, shared folds, deterministic best selection, error policies and the refit. The Lua bindings chapter adds the embedded interpreter, userdata lifecycle, table conversion and the packaged module. The Go bindings chapter adds the cgo boundary, C-owned copies, finalizers, structured errors and the build/CI story. Both bindings now live in their own repositories — neurono-ml/sciencekit-go and neurono-ml/sciencekit-lua — and consume the sciencekit_ffi C ABI that this repository keeps. The Arrow interop chapter adds the neutral schema mapping, the borrowed primitive columns, the missing-value policies over Arrow nulls, the C Data Interface in both directions and the columnar file sources with projection pushdown. The GPU compute contracts chapter adds the device inventory and capabilities, the deterministic selection rule, the validated device buffers, the closed kernel catalogue and the execution plan that records a backend and a fallback reason. The randomized SVD chapter adds the seeded range finder, the thin Householder QR, the small Gram SVD, the sparse products without densification, the implicit centering and the accuracy bound against the exact decomposition. The random forest chapter opens sciencekit_ensemble with seeded per-tree bootstrap sampling, de-correlated Sqrt feature subsampling, lock-free parallel CART fitting, out-of-bag accuracy and $R^2$ scoring, normalized mean feature importances and non-densifying CSR parity. The support-vector machines chapter adds the Mercer and similarity kernel catalogue in sciencekit_math, the pure-Rust second-order SMO solver with a bounded LRU kernel-row cache, one-vs-one SKSVC with Platt scaling and Wu–Lin–Weng pairwise coupling, and $\varepsilon$-insensitive SKSVR over support-vector-only dense and CSR blocks. The DBSCAN chapter adds density reachability over spatial trees and sparse brute force, the core/border/noise taxonomy with typed SKClusterLabel::Noise, deterministic component numbering and the nearest-core predict_clusters extension. The PCA chapter builds SKPCA in sciencekit_decomposition on top of the randomized SVD kernel: feature centering, the Full/Randomized/CovarianceEigh solver portfolio and Auto resolution, component-sign determinism, epsilon-floored whitening, and the explicit sparse-densification contract. fallback reason. The feature union chapter adds parallel transformer fan-out inside sciencekit_pipeline: tuple and boxed member collections, CSR-preserving horizontal concatenation, member-indexed error context and nested pipeline composition. The JSON debug format chapter adds the deterministic human-readable SKModelState schema, the pretty and compact writer, the duplicate-aware validating reader and the round-trip acceptance guarantees across scalar and tensor types.

The Truncated SVD chapter adds SKTruncatedSVD in sciencekit_decomposition: uncentered randomized low-rank factorization for latent semantic analysis, non-densifying CSR fit/transform/inverse_transform parity, two-pass sparse variance ratios and thread-count-invariant 256-row chunking. The generic bagging chapter extends sciencekit_ensemble with SKBaggingClassifier<B> and SKBaggingRegressor<B>: compile-time supervision bounds over any base estimator, independent row and feature bootstrap streams, non-densifying CSR feature-subset routing, two-tier SKBaggingError<E> propagation and out-of-bag accuracy and $R^2$ scoring. The gradient boosting chapter extends sciencekit_ensemble with SKGradientBoostingClassifier<F> and SKGradientBoostingRegressor<F>: a loss-agnostic stage loop that fits structure-only trees to the negative gradient, replaces leaves with damped Newton steps $-\sum g / (\sum h + \lambda)$, shrinks every stage by the learning rate, subsamples rows without replacement from per-stage seeds, and early-stops by truncating back to the best held-out validation stage, over dense and non-densified CSR input for binary, multiclass and all three regression losses. The outlier detection chapter closes Wave 5 in sciencekit_outlier and sciencekit_common: the one-byte SKOutlierLabel and SKOutlierPredictor<F> contract, seeded random isolation trees over SKTree, harmonic BST path-length scoring, Auto and quantile contamination offsets, and non-densifying CSR-to-CSC representation parity. The incremental PCA chapter extends sciencekit_decomposition out-of-core with SKIncrementalPCA: exact Chan-Golub-LeVeque scatter merging, Neumaier-compensated sparse CSR Gram updates without densification, symmetric eigh finalization matching SKPCA, chained partial_fit updates and reopenable multi-epoch fit_streaming. The mini-batch k-means chapter adds SKMiniBatchKMeans<F> in sciencekit_cluster: the exact per-center learning-rate update in closed form over dense and non-densified CSR batches, seeded bounded-sample initialization with best-of-n_init inertia selection, deterministic low-count center reassignment, incremental partial_fit, multi-epoch fit_streaming over reopenable providers with positive-tolerance early stopping, and the typed SKMiniBatchKMeansModel<F> prediction, transform and state export surface. The extended Safetensors format chapter adds the binary SKModelState persistence adapter in sciencekit_interop::safetensors: standard single-file Safetensors compatibility, sciencekit.* header metadata, SKShardPlan multi-shard splitting with atomic .index.json manifests, dual-region header and payload padding for in-place seek appends with automatic shard overflow, and optional magic-byte auto-detected Gzip, Brotli and Snappy compression. The runtime DAG pipelines chapter adds SKPipelineGraph on top of sciencekit_pipeline: the mandatory builder and private constructors, cycle/single-sink/reachability validation, the deterministic level order with ascending node identifiers, the edge-weight merge order that concatenates incoming blocks in exact connect order without densifying CSR, the node-attributed SKPipelineGraphNodeError checked variants and the type-erased SKBoxedFinalModel behind the typed classifier and regressor wrappers. The OpenTelemetry export chapter adds production three-signal telemetry in sciencekit_telemetry: builder-validated OTLP gRPC and HTTP configuration, resource metadata propagation, error-enriched trace spans, trace-correlated structured logs, closed-vocabulary operation metrics and the process-wide SKTelemetry init, force_flush, shutdown and Drop lifecycle with a silent zero-traffic default. The streaming pipelines chapter extends sciencekit_pipeline with an out-of-core composition layer: the SKStreamingTransformer contract, the SKStreamingPipeline builder and its chained fitting through the shared prefetch executor, one-shot materialization within memory_budget_bytes, multi-epoch replay on reopenable providers, the bounded SKFinalizerBuffer that preserves CSR, stage-indexed error propagation and the Send + Sync fitted pipeline with its SKStreamingFitReport. The Polars and DataFusion sources chapter adds the feature-gated tabular sources in sciencekit_interop: the materialized SKTabularDataset<F> with SKColumnKind, SKTabularSourceConfig and the owned SKNominalMatrixOwned; Polars DataFrame/LazyFrame conversion with categorical labels read from their strings; DataFusion 46 DataFrame/RecordBatch conversion plus a true record-batch stream and Parquet-through-DataFusion; and the missing-value mapping shared by both engines. The memory-mapped sources chapter adds the memmap feature of sciencekit_interop: read-only memmap2 mappings behind SKMappableSource and SKLazySource, raw binary matrices with explicit descriptors and exact length validation, zero-copy NumPy .npy float rows with Fortran-order, endianness and alignment rejection plus an explicit casting path, footer-indexed Arrow IPC random access with per-batch decoding, bounded sequential blocks and Send + Sync concurrent readers.

The linear support-vector machines chapter completes sciencekit_svm with SKLinearSVC<F>: the LIBLINEAR-style dual coordinate descent for the L1-hinge and L2-squared-hinge losses, the SKDenseLinearSvcDesign / SKSparseLinearSvcDesign abstraction that scans CSR stored entries without densifying, the unpenalized intercept recovered by a one-dimensional bisection, parallel one-vs-rest heads with deterministic order and smallest-index tie-breaking, class-weighted box capacities, the explicit NotConverged { iterations } budget, and the deliberate UnsupportedOperation from predict_probabilities.

The histogram gradient boosting chapter adds the histogram_boosting module of sciencekit_ensemble: deterministic quantile binning (SKNumericBinning, SKFeatureBinning, SKBinnedDataset) with a reserved missing bin and a column-major u8 store, parallel gradient/Hessian accumulation, the Newton gain prefix scan, parent-child histogram subtraction, gain-ordered leaf-wise growth under maximum_leaf_nodes and minimum_samples_leaf, bitvec categorical membership masks with an unknown-category direction, learned default_left missing routing, and the SKHistGradientBoostingClassifier / SKHistGradientBoostingRegressor builders, models and prediction surface that reuse the W4.4 loss contract and early-stopping monitor while binning dense and CSR queries without densification.

The OpenCL backend chapter adds the first real device backend behind the contracts of sciencekit_gpu: the opencl feature (re-exported by the sciencekit_gpu_opencl package through gpu-opencl), the exact opencl3 0.12.0 pin whose dynamic loader opens libOpenCL.so.1, deterministic enumeration through the ICD loader, capability reporting with the full kernel catalogue, SKOpenClBackendBuilder with strict and fallback construction, resident SKOpenClBuffer<F> allocations with device-memory and capacity validation, explicit accounted transfers (SKOpenClTransferReport), runtime-compiled and cached pairwise-distance, tiled GEMM, elementwise and tree-prediction kernels with CPU-parity tests, concurrent dispatch parity, span fields recording opencl, the device and the bytes moved, and an honest SKFallbackReason::NoDeviceAvailable for feature-off, device-less and failed-build configurations.

The model export retrofit chapter adds the shared SKExportable / SKImportable round trip to every retrofitted family: the single SK_MODEL_FORMAT_VERSION, the dotted tensor naming scheme, the dense/CSR-preserving support-vector and training-design codecs, the NaN-aware determinism check (sk_states_equal), and the companion tests that fit, export, import and compare predictions — including the nested tree states of the forests and gradient boosters. The chapter’s coverage table names the families still pending so the book never claims more than the code delivers.

The ONNX export chapter extends the neutral export contract with a translator to ONNX: the sciencekit_onnx crate, the SKToOnnx<F> blanket implementation over SKExportable<F>, the validated SKOnnxGraphBuilder over prost-declared protobuf messages, opset 17 plus ai.onnx.ml 3, the per-family operator subset (scalers, one-hot, linear and logistic, ONNX-ML tree ensembles, neighbours, k-means, PCA/SVD and pipelines), the dtype/metadata rules, and the coverage matrix that keeps unsupported families explicit. When you add an exporter, extend sk_onnx_coverage, add a Rust-parity test that writes a fixture, and rerun crates/sciencekit_onnx/validation/compare_with_onnxruntime.py so the claim stays backed by a real runtime.

The ONNX import chapter closes the interoperability loop: sciencekit_onnx decodes a model into the shared serde-onnx IR (the exporter now assembles that same IR), validates the opset, the documented operator subset, external data and the interface, and runs the graph with a dependency-ordered interpreter behind SKOnnxPredictor<F> and SKOnnxPredictorBuilder<F>. When you add an importer operator, extend SK_ONNX_SUPPORTED_OPERATORS (or SK_ONNX_SUPPORTED_ML_OPERATORS), add the dispatch arm and a companion test, then rerun the three-way harness after cargo run -p sciencekit_onnx --example validate_import <fixture-root> so the imported prediction stays proven against both the Rust model and onnxruntime.

The native model import chapter closes the round trip: SKNativeImport<F> rebuilds a real fitted type from a neutral state, with structural format detection, typed rejections at the trust boundary, exact tensor-set and class-table validation, continued fitting for the families that keep a learning state, and an ONNX mapper for the documented affine/scaler/tree subset. When you add a family, extend sk_native_import_coverage and the ONNX mapper, add a round-trip test that compares predictions with the original, keep the external fixture in crates/sciencekit_onnx/validation/external/ reproducible with validation/compare_native_import.py, and update this chapter rather than adding a parallel one.

The low-rank adapter chapter adds the parameter-efficient path to the same export contract: SKLoraAdapter<F> and its builder, the frozen SKLoraBaseModel<F>, the A/B factors of SKLoraAttachedModel<F>, merge/unmerge parity, the persisted lora.<target>.a/.b tensors, and the registry that rejects duplicate identifiers. When you extend adapter coverage, keep the zero-adapter identity, the merge identity and the persisted-shape validation tests green, extend the lora_*_tests.rs companions and this chapter rather than adding a parallel one.

The umbrella crate chapter explains the entry point rather than an algorithm: why one package re-exports twenty-one, how the umbrella lives in the existing workspace-root package (a crates/sciencekit would have duplicated the package name), how the curated prelude differs from a glob import, which names collide across families (SKClassWeight is three distinct policies; SKFeatureBlock is one shared identity), and how the integration features forward with dep: while the default build stays core-only. When you add a family, extend src/<family>.rs, add the name to the prelude only when it is broadly useful, forward any heavy dependency through a feature, and extend reexports_tests, prelude_tests and features_tests so the chapter’s claims stay executable.

The workflows CLI chapter turns the library into a process: the sciencekit binary, the versioned workflow record, the flags > environment > file > defaults resolution, the stable exit-code contract, every subcommand, and the feature-gated Parquet/YAML/ONNX paths. When you add a command or a workflow key, extend cli/arguments.rs, workflow/schema.rs, workflow/validation.rs and config/precedence.rs together, add a process-level test beside the existing ones in crates/sciencekit_cli/tests/, and update this chapter rather than adding a parallel one.