Skip to Content
OchreML
Architecture & Benchmarks

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 Rust f64 parallel execution across all logical cores; also acts as the automatic fallback if any accelerator is unavailable.
  • CUDA (src/backends/cuda.rs): Runtime dynamic loading of libcuda.so.1 and libcublas.so.12 (.11 fallback) via libloading, with cached CUcontext/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 of libtpu.so / libpjrt_c_api_tpu.so via the OpenXLA PJRT C API, emitting StableHLO MLIR with HIGHEST precision 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:

IDPrimitiveCore OperationCPUCUDAwgpuTPU
E1matmul(A, B)Dense GEMM (A * B)RayoncuBLAS FP64Split-K WGSLdot_general
E2matmul_at_b(A, B)Transposed GEMM (A^T * B)RayoncuBLAS FP64Split-K WGSLdot_general
E3matvec(A, v)Dense GEMV (A * v)RayoncuBLAS FP64WGSLdot_general
E4compute_normal_equationGram matrix & RHS (X^T X, X^T y)RayoncublasDsyrk_v2Split-K WGSLdot_general
E5compute_normal_equation_multiWeighted multi-output (X^T W X, X^T W y)RayoncuBLAS + DdgmmSplit-K WGSLdot_general
N1col_reduce_stats(X)Column mean, variance/std, min, max, sumRayonCUDA kernelWGSLStableHLO
N2elementwise_op(A, op)sigmoid, tanh, relu, exp, log, clip, soft_threshold, axpyRayonCUDA kernelWGSLStableHLO
N3pairwise_l2_sq(A, B)GEMM-based squared Euclidean distance matrixRayoncuBLASWGSLdot_general
N4topk_argmin(D, k)Per-row minimum / top-k index selectionRayonCUDA kernelWGSLStableHLO
N5small_sym_eig_svd(M)Small symmetric eigendecomposition / SVDRayonHost / CUDAHostHost
N6batched_histogram_splitQuantized u8 SoA binning + grad/hessian/impurity splitsRayonCUDA HistWGSL HistCPU 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) and memoryview objects 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 StatementCPU 4c LatencyCPU 4c ModulesCUDA 2xGPU LatencyCUDA 2xGPU Modules
import ochreml0.85 ms2000.61 ms204
from ochreml.linear_model import Ridge103.44 ms30086.11 ms304
import ochreml.nn106.26 ms30086.45 ms304
import sklearn1,202.19 ms1,384987.45 ms1,388
from sklearn.linear_model import Ridge1,316.47 ms1,4831,098.61 ms1,487
import torch1,708.71 ms1,1371,497.92 ms1,147
  • Top-level import ochreml is 1,414x faster than import sklearn on cpu_4c (0.85 ms vs. 1,202.19 ms) and 1,619x faster on cuda_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 than from sklearn.linear_model import Ridge.

On this page