Skip to main content

Crate tinymind

Crate tinymind 

Source
Expand description

Rust port of the tinymind (C++) neural network library. Both libraries run networks in fixed point (Q formats) and in floating point (f32 and f64).

Scope: Q16.16 and Q8.8 arithmetic and a fixed-point square root (Sqrt); ReLU, Linear and the tanh and sigmoid lookup-table activations; f32 and f64 as network value types (their Tanh and Sigmoid need the std or libm feature, as do the floating-point AdamFloat and RmsPropFloat and the f32/f64 softmax of head::DenseHead); trainable networks with up to seven hidden layers (NeuralNetwork over Dense layers, trained with SGD and momentum, Adam or RmsProp, with optional gradient clipping, L2 weight decay and a step-decay learning-rate schedule (training, which also has early stopping and scheduled sampling; the decay and the schedule also apply to MultilayerPerceptron and recurrent::LstmNetwork)) and their inference-only form (InferenceNetwork over InferenceDense layers: the weights only, tinymind (C++)’s IsTrainable = false); a one-hidden-layer perceptron that trains on the device (MultilayerPerceptron) or only runs trained weights (InferencePerceptron, tinymind (C++)’s IsTrainable = false); the trainable networks give a classifier’s class from the output logits (predicted_class), which the saturating sigmoid table cannot tie; int8 affine-quantized inference (int8: dense layers, 2D convolutions (standard, depthwise and pointwise), pooling, elementwise addition and multiplication, padding, concatenation, quantized activations, a TFLite-exact softmax, LSTM and GRU cells, and radix-2 FFTs on 16-bit samples, complex or real-input), quantized decision trees and gradient-boosted ensembles (tree), Q-learning, tabular or with a deep Q-network (qlearn), LSTM recurrent networks (recurrent::LstmNetwork), and head-only fine-tuning (head: a trainable dense head and a nearest-class-mean head that adapt a frozen model on the device from a few labelled samples). Every part produces the same bits as tinymind (C++) (floating point: with std on a glibc host). rand re-implements glibc’s rand(), which tinymind (C++)’s examples use for weight initialisation and sampling, so they can be reproduced bit for bit. The library is no_std and allocation-free, like tinymind (C++)’s freestanding build.

§Features

  • std: host-side int8 calibration (int8::calibration), and the math (tanh, exp, pow, sqrt) of the f32/f64 Tanh, Sigmoid, AdamFloat, RmsPropFloat and head::SoftmaxExp, from the platform (bit-identical to tinymind (C++) on a glibc host).
  • libm: the same float math without std, from the libm crate (for a Cortex-M4F, say); within a few ulps of glibc, not bit-identical.

§Example

Train a 2-4-1 network on XOR in Q16.16, as tinymind (C++)’s examples/xor does (the xor example in this repository is the full port, bit-exact with the C++):

use tinymind::rand::GlibcRand;
use tinymind::{MultilayerPerceptron, Q16_16, Sigmoid, Tanh};

// 2 inputs, 4 tanh hidden neurons, 1 sigmoid output.
type Net = MultilayerPerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;

// Initial weights in [-0.5, 0.5] (raw Q16.16 units), from glibc-compatible rand().
let mut init = GlibcRand::new(1);
let mut nn = Net::new(|| Q16_16::from_raw(init.next_i32() % 65537 - 32768));

let mut rng = GlibcRand::new(7);
for _ in 0..20_000 {
    let (a, b) = (rng.next_i32() & 1, rng.next_i32() & 1);
    let target = [Q16_16::from_int(a ^ b)];
    nn.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
    if !nn.calculate_error(&target).is_within_zero_tolerance() {
        nn.train(&target);
    }
}

for (a, b) in [(0, 0), (0, 1), (1, 0), (1, 1)] {
    nn.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
    let p = nn.learned_values()[0].to_f64();
    assert_eq!(p >= 0.5, a ^ b == 1, "{a} ^ {b}: p = {p}");
}

Re-exports§

pub use activation::Activation;
pub use activation::Linear;
pub use activation::Relu;
pub use activation::Sigmoid;
pub use activation::Tanh;
pub use network::Dense;
pub use network::InferenceDense;
pub use network::InferenceLayers;
pub use network::InferenceNetwork;
pub use network::Layers;
pub use network::NeuralNetwork;
pub use neuralnet::InferencePerceptron;
pub use neuralnet::MultilayerPerceptron;
pub use optimizer::Adam;
pub use optimizer::Optimizer;
pub use optimizer::RmsProp;
pub use optimizer::Sgd;
pub use optimizer::AdamFloat;
pub use optimizer::RmsPropFloat;
pub use qformat::Fixed;Deprecated
pub use qformat::Q8_8;
pub use qformat::Q16_16;
pub use qformat::QValue;
pub use qformat::Scalar;
pub use qformat::Sqrt;

Modules§

activation
Activation policies, ported from tinymind (C++) cpp/activationFunctions.hpp, cpp/lookupTable.hpp and cpp/interpolate.hpp.
head
Head-only fine-tuning: small classifiers that sit on top of a frozen model and learn on the device from a few labelled samples. Ported from tinymind (C++) cpp/densehead.hpp and cpp/prototypehead.hpp.
int8
Int8 affine-quantized inference, ported from tinymind (C++) cpp/qaffine.hpp, cpp/qdense.hpp, cpp/qconv2d.hpp, cpp/qdepthwiseconv2d.hpp, cpp/qpointwiseconv2d.hpp, cpp/qpool2d.hpp, cpp/qadd.hpp, cpp/qmul.hpp, cpp/qpad.hpp, cpp/qconcat.hpp, cpp/qactivations.hpp, cpp/qsoftmax_fixedpoint.hpp, cpp/qlstm.hpp, cpp/qgru.hpp and cpp/qfft1d.hpp.
network
A trainable feed-forward network with up to seven hidden layers, ported from tinymind (C++)’s NeuralNetwork<ValueType, Inputs, HiddenLayers<...>, Outputs, ...> (cpp/neuralnet.hpp, the chain-based path).
neuralnet
A multilayer perceptron with one hidden layer, ported from the NeuralNetwork / MultilayerPerceptron path of tinymind (C++) cpp/neuralnet.hpp, in two forms: MultilayerPerceptron trains on the device, and InferencePerceptron only runs a trained network (C++ IsTrainable = false).
optimizer
Weight-update rules for the trainable networks, ported from tinymind (C++) cpp/adam.hpp and cpp/rmsprop.hpp (C++ TransferFunctionOptimizerPolicy).
qformat
Signed fixed-point Q-format arithmetic, ported from tinymind (C++) cpp/qformat.hpp.
qlearn
Q-learning, ported from tinymind (C++)’s qlearn.hpp: QLearner (QLearner with DefaultLearningPolicy and ArgMaxPolicy), its Q values in a QTable (QValueTablePolicy) or a QNetwork (QValueNeuralNetworkPolicy), and the Environment trait (what the C++ example environments derive from QLearningEnvironment and supply as policies).
rand
A bit-exact re-implementation of glibc’s srand()/rand().
recurrent
Recurrent networks, ported from tinymind (C++)’s cpp/neuralnet.hpp: LstmNetwork is tinymind (C++)’s LstmNeuralNetwork with one LSTM hidden layer.
training
Training controls for the trainable networks, ported from tinymind (C++) cpp/weightDecay.hpp, cpp/learningRateSchedule.hpp, cpp/earlyStopping.hpp and cpp/teacherForcing.hpp.
tree
Quantized decision trees and gradient-boosted tree ensembles (C++ cpp/qtree.hpp).