tinymind/lib.rs
1//! Rust port of the tinymind (C++) neural network library. Both libraries run
2//! networks in fixed point (Q formats) and in floating point (`f32` and `f64`).
3//!
4//! Scope: Q16.16 and Q8.8 arithmetic and a fixed-point square root ([`Sqrt`]); ReLU, [`Linear`] and the tanh and sigmoid
5//! lookup-table activations; `f32` and `f64` as network value types (their
6//! [`Tanh`] and [`Sigmoid`] need the `std` or `libm` feature, as do the
7//! floating-point `AdamFloat` and `RmsPropFloat` and the `f32`/`f64` softmax
8//! of `head::DenseHead`); trainable networks with up
9//! to seven hidden layers
10//! ([`NeuralNetwork`] over [`Dense`] layers, trained with SGD and momentum,
11//! [`Adam`] or [`RmsProp`], with optional gradient clipping, L2 weight decay
12//! and a step-decay learning-rate schedule ([`training`], which also has
13//! early stopping and scheduled sampling; the decay and the schedule also apply to
14//! [`MultilayerPerceptron`] and [`recurrent::LstmNetwork`])) and their
15//! inference-only form ([`InferenceNetwork`] over [`InferenceDense`] layers:
16//! the weights only, tinymind (C++)'s `IsTrainable = false`); a one-hidden-layer
17//! perceptron that
18//! trains on the device ([`MultilayerPerceptron`]) or only runs trained weights
19//! ([`InferencePerceptron`], tinymind (C++)'s `IsTrainable = false`); the
20//! trainable networks give a classifier's class from the output logits
21//! (`predicted_class`), which the saturating sigmoid table cannot tie; int8
22//! affine-quantized inference ([`int8`]: dense layers, 2D convolutions (standard,
23//! depthwise and pointwise), pooling, elementwise addition and multiplication,
24//! padding, concatenation, quantized activations,
25//! a TFLite-exact softmax, LSTM and GRU cells, and radix-2 FFTs on 16-bit
26//! samples, complex or real-input), quantized decision trees and gradient-boosted
27//! ensembles ([`tree`]), Q-learning, tabular or with a deep Q-network
28//! ([`qlearn`]), LSTM recurrent
29//! networks ([`recurrent::LstmNetwork`]), and head-only fine-tuning ([`head`]:
30//! a trainable dense head and a nearest-class-mean head that adapt a frozen
31//! model on the device from a few labelled samples). Every part produces the same bits as
32//! tinymind (C++) (floating point: with `std` on a glibc host). [`rand`] re-implements glibc's `rand()`, which tinymind (C++)'s
33//! examples use for weight initialisation and sampling, so they can be
34//! reproduced bit for bit. The library is `no_std` and allocation-free, like tinymind (C++)'s
35//! freestanding build.
36//!
37//! # Features
38//!
39//! - `std`: host-side int8 calibration (`int8::calibration`), and the math
40//! (`tanh`, `exp`, `pow`, `sqrt`) of the `f32`/`f64` [`Tanh`], [`Sigmoid`],
41//! `AdamFloat`, `RmsPropFloat` and `head::SoftmaxExp`, from the platform (bit-identical to
42//! tinymind (C++) on a glibc host).
43//! - `libm`: the same float math without `std`, from the `libm` crate (for a
44//! Cortex-M4F, say); within a few ulps of glibc, not bit-identical.
45//!
46//! # Example
47//!
48//! Train a 2-4-1 network on XOR in Q16.16, as tinymind (C++)'s `examples/xor` does
49//! (the `xor` example in this repository is the full port, bit-exact with the C++):
50//!
51//! ```
52//! use tinymind::rand::GlibcRand;
53//! use tinymind::{MultilayerPerceptron, Q16_16, Sigmoid, Tanh};
54//!
55//! // 2 inputs, 4 tanh hidden neurons, 1 sigmoid output.
56//! type Net = MultilayerPerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
57//!
58//! // Initial weights in [-0.5, 0.5] (raw Q16.16 units), from glibc-compatible rand().
59//! let mut init = GlibcRand::new(1);
60//! let mut nn = Net::new(|| Q16_16::from_raw(init.next_i32() % 65537 - 32768));
61//!
62//! let mut rng = GlibcRand::new(7);
63//! for _ in 0..20_000 {
64//! let (a, b) = (rng.next_i32() & 1, rng.next_i32() & 1);
65//! let target = [Q16_16::from_int(a ^ b)];
66//! nn.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
67//! if !nn.calculate_error(&target).is_within_zero_tolerance() {
68//! nn.train(&target);
69//! }
70//! }
71//!
72//! for (a, b) in [(0, 0), (0, 1), (1, 0), (1, 1)] {
73//! nn.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
74//! let p = nn.learned_values()[0].to_f64();
75//! assert_eq!(p >= 0.5, a ^ b == 1, "{a} ^ {b}: p = {p}");
76//! }
77//! ```
78#![no_std]
79#![forbid(unsafe_code)]
80#![warn(missing_docs)]
81
82// Host-side calibration (`int8::calibration`) needs f32::exp and f32::tanh.
83#[cfg(feature = "std")]
84extern crate std;
85
86pub mod activation;
87pub mod head;
88pub mod int8;
89mod lut;
90pub mod network;
91pub mod neuralnet;
92pub mod optimizer;
93pub mod qformat;
94pub mod qlearn;
95pub mod rand;
96pub mod recurrent;
97pub mod training;
98pub mod tree;
99
100#[cfg(kani)]
101mod kani_proofs;
102
103pub use activation::{Activation, Linear, Relu, Sigmoid, Tanh};
104pub use network::{
105 Dense, InferenceDense, InferenceLayers, InferenceNetwork, Layers, NeuralNetwork,
106};
107pub use neuralnet::{InferencePerceptron, MultilayerPerceptron};
108pub use optimizer::{Adam, Optimizer, RmsProp, Sgd};
109#[cfg(any(feature = "std", feature = "libm"))]
110pub use optimizer::{AdamFloat, RmsPropFloat};
111#[allow(deprecated)]
112pub use qformat::Fixed;
113pub use qformat::{Q8_8, Q16_16, QValue, Scalar, Sqrt};