optirs/lib.rs
1//! # OptiRS - Advanced ML Optimization Built on SciRS2
2//!
3//! **Version:** 0.3.2
4//!
5//! [](https://crates.io/crates/optirs)
6//! [](https://docs.rs/optirs)
7//! [](https://github.com/cool-japan/optirs)
8//!
9//! OptiRS is a comprehensive optimization library for machine learning, built exclusively on
10//! the [SciRS2](https://github.com/cool-japan/scirs) scientific computing ecosystem. It provides
11//! state-of-the-art optimization algorithms with advanced hardware acceleration.
12//!
13//! ## Dependencies
14//!
15//! - `scirs2-core` 0.6.5 - Required foundation
16//!
17//! ## Sub-Crate Status (v0.3.2)
18//!
19//! - ✅ `optirs-core` - Stable, production-ready (optimizers, schedulers, regularizers,
20//! SIMD and parallel paths, metrics)
21//! - ✅ `optirs-bench` - Available (benchmarking, profiling, regression detection)
22//! - 🚧 `optirs-gpu` - Real GPU compute path (Metal backend live end-to-end; WebGPU
23//! kernels implemented but blocked on an upstream `scirs2-core` adapter-probe bug;
24//! OpenCL is context-only; CUDA/ROCm have no backend) plus a fully-tested CPU
25//! library of GPU-aware algorithms
26//! - 🔬 `optirs-learned` - Research-grade learned optimizers and meta-learning (real,
27//! tested implementations; APIs may still change)
28//! - 🔬 `optirs-nas` - Research-grade neural architecture search (real, tested
29//! implementations; APIs may still change)
30//! - 📝 `optirs-tpu` - Working CPU-reference implementation of TPU-style coordination
31//! and an XLA-shaped compiler; no vendor TPU runtime is linked (proprietary hardware)
32//!
33//! ## Quick Start
34//!
35//! Add OptiRS to your `Cargo.toml`:
36//!
37//! ```toml
38//! [dependencies]
39//! optirs-core = "0.3.2"
40//! ```
41//!
42//! Basic usage:
43//!
44//! ```rust
45//! use optirs::prelude::*;
46//! use scirs2_core::ndarray::Array1;
47//!
48//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
49//! // Create Adam optimizer
50//! let mut optimizer = Adam::new(0.001);
51//!
52//! // Prepare parameters and gradients
53//! let params = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
54//! let gradients = Array1::from_vec(vec![0.1, 0.2, 0.15, 0.08]);
55//!
56//! // Perform optimization step
57//! let updated_params = optimizer.step(¶ms, &gradients)?;
58//! # Ok(())
59//! # }
60//! ```
61//!
62//! ## Features
63//!
64//! ### Core Optimizers (`optirs-core`)
65//!
66//! - **First-Order**: SGD, Adam, AdamW, AdaDelta, AdaBound, Adagrad, RMSprop, LAMB,
67//! LARS, Lion, RAdam, Ranger, SAM
68//! - **SIMD-Accelerated**: `SimdSGD`
69//! - **Sparse / grouped**: `SparseAdam`, `GroupedAdam`
70//! - **Meta-learning**: `MAML`, `MetaSGD`, `ReptileOptimizer`
71//! - **Wrapper**: `Lookahead`
72//! - **Second-Order** (`optirs_core::second_order`): L-BFGS, Newton, Newton-CG, K-FAC
73//! - **Distributed** (`optirs_core::distributed`): FedProx
74//!
75//! #### Performance Features
76//!
77//! - **SIMD** - vectorized optimizer steps through `scirs2_core::simd_ops`
78//! - **Parallel** - parameter groups distributed across cores through
79//! `scirs2_core::parallel_ops`
80//! - **Memory-Efficient** - gradient accumulation and chunked processing
81//! - **GPU** - see the `optirs-gpu` status below for which backends are real
82//! - **Production Metrics** - per-step monitoring with gradient and parameter statistics
83//!
84//! Speedups are workload- and hardware-dependent; measure them with the Criterion
85//! benchmarks in `optirs-core/benches/` rather than assuming a headline figure.
86//!
87//! ### GPU Acceleration (`optirs-gpu`)
88//!
89//! ```toml
90//! [dependencies]
91//! optirs-gpu = { version = "0.3.2", features = ["metal"] }
92//! ```
93//!
94//! - **Metal**: real compute shaders (MSL pipelines, buffers, dispatch, readback) run
95//! Adam, AdamW, SGD, RMSprop, Adagrad and LAMB end-to-end today
96//! - **WebGPU**: WGSL kernels are implemented, but blocked on an upstream `scirs2-core`
97//! adapter-probe bug; **OpenCL**: context creation only, no kernels shipped yet;
98//! **CUDA / ROCm**: no backend (`scirs2-core` 0.6.x dropped its CUDA backend)
99//! - **Tensor Cores**: real mixed-precision tiled GEMM on the wgpu path
100//! - **Memory Management**: CPU-side GPU memory pool models (arena/buddy/slab allocators)
101//! - **Multi-GPU**: single-device reduction kernels; true cross-device collectives
102//! return an explicit `UnsupportedOperation` error rather than a fabricated result
103//!
104//! ### TPU Coordination (`optirs-tpu`)
105//!
106//! ```toml
107//! [dependencies]
108//! optirs-tpu = "0.3.2"
109//! ```
110//!
111//! A working CPU-reference implementation - no vendor TPU runtime is linked (that is
112//! proprietary and not distributable as pure Rust); every path below runs and is tested
113//! on the CPU executor, and returns an explicit error where real TPU silicon would be
114//! required instead of a fabricated result.
115//!
116//! - **Pod Management**: device/channel topology, barrier sync, load balancing, fault detection
117//! - **XLA-shaped Compiler**: graph builder, dead-code elimination, constant folding,
118//! common-subexpression elimination, kernel-fusion legality checks, a real allocator,
119//! shape inference
120//! - **Fault Tolerance**: checkpoints serialized with a SHA-256 integrity hash, verified on restore
121//! - **Collectives**: ring all-reduce / broadcast / reduce-scatter
122//!
123//! ### Learned Optimizers (`optirs-learned`) [Research-Grade]
124//!
125//! - **Transformer-based**: self-attention optimizer with a real backward pass
126//! - **LSTM**: recurrent optimizer networks trained by truncated BPTT, with seeded,
127//! reproducible initialization
128//! - **Meta-Learning**: MAML, Reptile, Meta-SGD and online meta-learning across tasks
129//! - **Few-Shot**: prototypical networks, fast adaptation, episodic memory
130//! - **Continual Learning**: elastic weight consolidation, progressive networks
131//!
132//! ### Neural Architecture Search (`optirs-nas`) [Research-Grade]
133//!
134//! - **Search Strategies**: random, evolutionary, reinforcement-learning, Bayesian and
135//! differentiable (DARTS, PC-DARTS, RobustDARTS)
136//! - **Multi-Objective**: NSGA-II and MOEA/D with exact hypervolume
137//! - **Hyperparameter Search**: grid, TPE and a kernel-regression surrogate
138//! - **Progressive**: search with a gradually increasing complexity budget
139//! - **Hardware-Aware**: latency, memory and energy cost modelling
140//!
141//! ## Module Organization
142//!
143//! OptiRS is organized into feature-gated modules:
144//!
145//! - [`core`] - Core optimizers and utilities (always available)
146//! - `gpu` - GPU acceleration (feature: `gpu`)
147//! - `tpu` - TPU coordination (feature: `tpu`)
148//! - `learned` - Learned optimizers (feature: `learned`)
149//! - `nas` - Neural architecture search (feature: `nas`)
150//! - `bench` - Benchmarking tools (feature: `bench`)
151//!
152//! ## Examples
153//!
154//! ### SIMD Acceleration
155//!
156//! ```rust
157//! use optirs::prelude::*;
158//! use scirs2_core::ndarray::Array1;
159//!
160//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
161//! // Large parameter array (SIMD shines with 10k+ elements)
162//! let params = Array1::from_elem(100_000, 1.0f32);
163//! let grads = Array1::from_elem(100_000, 0.001f32);
164//!
165//! let mut optimizer = SimdSGD::new(0.01f32);
166//! let updated = optimizer.step(¶ms, &grads)?;
167//! # Ok(())
168//! # }
169//! ```
170//!
171//! ### Parallel Processing
172//!
173//! ```rust
174//! use optirs::prelude::*;
175//! use optirs::core::parallel_optimizer::parallel_step_array1;
176//! use scirs2_core::ndarray::Array1;
177//!
178//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
179//! let params_list = vec![
180//! Array1::from_elem(10_000, 1.0),
181//! Array1::from_elem(20_000, 1.0),
182//! ];
183//! let grads_list = vec![
184//! Array1::from_elem(10_000, 0.01),
185//! Array1::from_elem(20_000, 0.01),
186//! ];
187//!
188//! let mut optimizer = Adam::new(0.001);
189//! let results = parallel_step_array1(&mut optimizer, ¶ms_list, &grads_list)?;
190//! # Ok(())
191//! # }
192//! ```
193//!
194//! ### Production Monitoring
195//!
196//! ```rust
197//! use optirs::core::optimizer_metrics::MetricsCollector;
198//! use optirs::prelude::*;
199//! use scirs2_core::ndarray::Array1;
200//! use std::time::Instant;
201//!
202//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
203//! let mut collector = MetricsCollector::new();
204//! collector.register_optimizer("adam");
205//!
206//! let mut optimizer = Adam::new(0.001);
207//! let params = Array1::from_elem(1000, 1.0);
208//! let grads = Array1::from_elem(1000, 0.01);
209//!
210//! let params_before = params.clone();
211//! let start = Instant::now();
212//! let params = optimizer.step(¶ms, &grads)?;
213//! let duration = start.elapsed();
214//!
215//! collector.update(
216//! "adam",
217//! duration,
218//! 0.001,
219//! &grads.view(),
220//! ¶ms_before.view(),
221//! ¶ms.view(),
222//! )?;
223//!
224//! println!("{}", collector.summary_report());
225//! # Ok(())
226//! # }
227//! ```
228//!
229//! ## SciRS2 Integration
230//!
231//! OptiRS is built **exclusively** on SciRS2:
232//!
233//! - ✅ **Arrays**: `scirs2_core::ndarray` (NOT direct ndarray)
234//! - ✅ **Random**: `scirs2_core::random` (NOT direct rand)
235//! - ✅ **SIMD**: `scirs2_core::simd_ops`
236//! - ✅ **Parallel**: `scirs2_core::parallel_ops`
237//! - ✅ **GPU**: `scirs2_core::gpu`
238//! - ✅ **Metrics**: `scirs2_core::metrics`
239//!
240//! This ensures type safety, performance, and consistency across the ecosystem.
241//!
242//! ## Project health
243//!
244//! Measured on the 0.3.2 release candidate with `--all-features`:
245//!
246//! - more than 4,200 unit and integration tests passing workspace-wide, plus the
247//! doc tests
248//! - `cargo check` and `cargo clippy --workspace --all-targets` both at zero warnings,
249//! with no blanket `allow` attributes anywhere
250//! - `cargo deny check bans` passes
251//!
252//! Reproduce with `cargo nextest run --workspace --all-features` and
253//! `cargo clippy --workspace --all-features --all-targets`.
254//!
255//! ## Documentation
256//!
257//! - **API Documentation**: [docs.rs/optirs](https://docs.rs/optirs)
258//! - **User Guide**: `USAGE_GUIDE.md` in the repository
259//! - **Examples**: the `examples/` directory of this crate
260//! - **Release notes**: `CHANGELOG.md` in the repository
261//!
262//! ## Contributing
263//!
264//! Contributions are welcome! Ensure:
265//!
266//! - **100% SciRS2 usage** - No direct external dependencies
267//! - **All tests pass** - Run `cargo test`
268//! - **Zero warnings** - Run `cargo clippy`
269//! - **Documentation** - Add examples to public APIs
270//!
271//! ## License
272//!
273//! licensed under Apache-2.0
274
275pub use optirs_core as core;
276
277#[cfg(feature = "gpu")]
278pub use optirs_gpu as gpu;
279
280#[cfg(feature = "tpu")]
281pub use optirs_tpu as tpu;
282
283#[cfg(feature = "learned")]
284pub use optirs_learned as learned;
285
286#[cfg(feature = "nas")]
287pub use optirs_nas as nas;
288
289#[cfg(feature = "bench")]
290pub use optirs_bench as bench;
291
292/// Common imports for ease of use.
293///
294/// This intentionally covers only `optirs-core` (optimizers, regularizers,
295/// schedulers), which is always available and whose names are verified not
296/// to collide with one another. The `gpu`/`tpu`/`learned`/`nas` extension
297/// crates are deliberately **not** globbed in here: they are independently
298/// versioned and, with more than one enabled at once, their public names do
299/// collide with `core` and with each other (for example, both
300/// `optirs-core::optimizers` and `optirs-gpu` export a `SparseAdam`, and both
301/// `optirs-learned` and `optirs-nas` export their own `OptimError`/`Result`).
302/// A glob re-export of colliding names is ambiguous and unusable through the
303/// path that introduced the ambiguity (`ambiguous_glob_reexports`), so
304/// pulling them in here would silently break `optirs::prelude::SparseAdam`
305/// (etc.) the moment two of those features are enabled together.
306///
307/// Reach extension-crate types through their own namespace instead, e.g.
308/// `optirs::gpu::GpuAdam`, `optirs::learned::LSTMOptimizer`,
309/// `optirs::nas::ArchitectureSpace`.
310pub mod prelude {
311 pub use crate::core::optimizers::*;
312 pub use crate::core::regularizers::*;
313 pub use crate::core::schedulers::*;
314}
315
316// Re-export core functionality at the top level
317pub use crate::core::error::{OptimError, Result};
318pub use crate::core::optimizers;
319pub use crate::core::regularizers;
320pub use crate::core::schedulers;