Architecture & Lazy Imports
How OchreML's Backend<'a> enum dispatch, E1-E5 and N1-N6 primitives, zero-copy PyBuffer, and PEP 562 lazy imports work.
OchreML is designed around three core architectural choices: zero-cost backend dispatch over a small set of shared primitives, zero-copy Python buffer ingestion, and PEP 562 lazy module loading. (^▽^)
Unified Backend<'a> Dispatch
Rather than re-implementing every algorithm separately for CPU, CUDA, wgpu, and TPU, OchreML isolates hardware execution inside src/backend.rs. Calling get_backend(&DeviceType) returns a zero-cost Backend<'a> enum that dispatches dense linear algebra, reductions, distances, and histogram splits across all supported targets:
- CPU (
Rayon): Native Rustf64parallel execution across all logical cores; also acts as the automatic fallback if any accelerator is unavailable. - CUDA (
src/backends/cuda.rs): Runtime dynamic loading oflibcuda.so.1andlibcublas.so.12(.11fallback) vialibloading, with cachedCUcontext/cuBLAS handles and multi-GPU row sharding (cuda:all). wgpu(src/backends/wgpu_gpu.rs): Pure-Rust Vulkan/Metal/DX12 WGSL compute shaders with Split-K reduction and Kahan compensated summation; software rasterizers are explicitly rejected.- TPU (
src/backends/tpu.rs): Runtime dynamic loading oflibtpu.so/libpjrt_c_api_tpu.sovia the OpenXLA PJRT C API, emitting StableHLO MLIR withHIGHESTprecision and explicit row-major ([1, 0]) host layouts.
Classical ML Primitives (E1–E5 & N1–N6)
All 63 Classical ML estimators and preprocessing transformers are composed from 11 reusable primitives:
| ID | Primitive | Core Operation | CPU | CUDA | wgpu | TPU |
|---|---|---|---|---|---|---|
| E1 | matmul(A, B) | Dense GEMM (A * B) | Rayon | cuBLAS FP64 | Split-K WGSL | dot_general |
| E2 | matmul_at_b(A, B) | Transposed GEMM (A^T * B) | Rayon | cuBLAS FP64 | Split-K WGSL | dot_general |
| E3 | matvec(A, v) | Dense GEMV (A * v) | Rayon | cuBLAS FP64 | WGSL | dot_general |
| E4 | compute_normal_equation | Gram matrix & RHS (X^T X, X^T y) | Rayon | cublasDsyrk_v2 | Split-K WGSL | dot_general |
| E5 | compute_normal_equation_multi | Weighted multi-output (X^T W X, X^T W y) | Rayon | cuBLAS + Ddgmm | Split-K WGSL | dot_general |
| N1 | col_reduce_stats(X) | Column mean, variance/std, min, max, sum | Rayon | CUDA kernel | WGSL | StableHLO |
| N2 | elementwise_op(A, op) | sigmoid, tanh, relu, exp, log, clip, soft_threshold, axpy | Rayon | CUDA kernel | WGSL | StableHLO |
| N3 | pairwise_l2_sq(A, B) | GEMM-based squared Euclidean distance matrix | Rayon | cuBLAS | WGSL | dot_general |
| N4 | topk_argmin(D, k) | Per-row minimum / top-k index selection | Rayon | CUDA kernel | WGSL | StableHLO |
| N5 | small_sym_eig_svd(M) | Small symmetric eigendecomposition / SVD | Rayon | Host / CUDA | Host | Host |
| N6 | batched_histogram_split | Quantized u8 SoA binning + grad/hessian/impurity splits | Rayon | CUDA Hist | WGSL Hist | CPU Fallback |
Deep learning (ochreml.nn) builds four additional tensor primitives (N7–N10: batched matmul, fused LayerNorm/RMSNorm/GELU/SiLU/causal mask, fused cross-entropy + AdamW, and im2col/pool2d) on top of the exact same Backend<'a> dispatcher.
Zero-Copy Python Buffer Protocol
Input arrays pass through python/ochreml/_utils.py (process_features, process_target, process_sample_weight) into Rust PyBuffer<f64> paths:
- C-contiguous
numpy.ndarray(float64) andmemoryviewobjects are read directly in Rust with zero host copy. - Nested Python lists and non-contiguous slices are validated and packed cleanly without requiring NumPy to be installed.
PEP 562 Lazy Imports
Importing ochreml does not eagerly load the compiled Rust extension (_ochreml), NumPy, or any of the 29 submodules. Instead, python/ochreml/__init__.py implements module-level __getattr__ and __dir__ (PEP 562), resolving submodules and public estimators on first access and caching them in globals().
Measured Startup Latency & Module Count (v0.3.7a1)
Measured in isolated subprocesses on both cpu_4c (Python 3.13.18) and cuda_2gpu (Python 3.13.16):
| Import Statement | CPU 4c Latency | CPU 4c Modules | CUDA 2xGPU Latency | CUDA 2xGPU Modules |
|---|---|---|---|---|
import ochreml | 0.85 ms | 200 | 0.61 ms | 204 |
from ochreml.linear_model import Ridge | 103.44 ms | 300 | 86.11 ms | 304 |
import ochreml.nn | 106.26 ms | 300 | 86.45 ms | 304 |
import sklearn | 1,202.19 ms | 1,384 | 987.45 ms | 1,388 |
from sklearn.linear_model import Ridge | 1,316.47 ms | 1,483 | 1,098.61 ms | 1,487 |
import torch | 1,708.71 ms | 1,137 | 1,497.92 ms | 1,147 |
- Top-level
import ochremlis 1,414x faster thanimport sklearnoncpu_4c(0.85 ms vs. 1,202.19 ms) and 1,619x faster oncuda_2gpu(0.61 ms vs. 987.45 ms). - Even after resolving a compiled estimator (
from ochreml.linear_model import Ridge), OchreML loads 4.9x fewer Python modules and starts 12.7x faster thanfrom sklearn.linear_model import Ridge.