tinymind 0.3.2

Neural networks for embedded Rust: a no_std, allocation-free port of the tinymind (C++) library, bit-exact with it
Documentation
//! The xor example's program, shared by `examples/xor.rs` (which parses the
//! command line) and `tests/xor_golden.rs` (which runs it in-process against the
//! C++ goldens). Port of tinymind (C++) `examples/xor/xor.cpp`; see `examples/xor.rs`.

use std::fmt::Display;
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::path::Path;

use tinymind::rand::GlibcRand;

#[path = "cppfmt.rs"]
mod cppfmt;
use cppfmt::fmt_g;
use tinymind::{Activation, MultilayerPerceptron, Q8_8, Q16_16, Scalar, Sigmoid, Tanh};

const TRAINING_ITERATIONS: u32 = 20_000;
const NUM_SAMPLES_AVG_ERROR: u32 = 100;
const RANDOM_SEED: u32 = 7;
/// C++ `WEIGHT_INIT_SEED`: seeds the initial weights only.
const WEIGHT_INIT_SEED: u32 = 1;

const NUMBER_OF_INPUTS: usize = 2;
const NUMBER_OF_NEURONS_PER_HIDDEN_LAYER: usize = 4;
const NUMBER_OF_OUTPUTS: usize = 1;

type NeuralNetwork<V> = MultilayerPerceptron<
    V,
    Tanh,
    Sigmoid,
    NUMBER_OF_INPUTS,
    NUMBER_OF_NEURONS_PER_HIDDEN_LAYER,
    NUMBER_OF_OUTPUTS,
>;

const XOR_CASES: [[i32; 3]; 4] = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]];

/// What the driver needs from a value type beyond [`Scalar`]. Both formats have
/// these as inherent methods; the trait lets [`run`] be generic over them.
trait Format: Scalar + Display {
    fn from_int(n: i32) -> Self;
    fn from_f64_trunc(x: f64) -> Self;
    fn to_f64(self) -> f64;
    fn is_within_zero_tolerance(self) -> bool;
    /// C++ `ValueType(abs(error.getValue()))`.
    fn abs(self) -> Self;
    /// C++ `RandomNumberGenerator::generateRandomWeight` given one `rand()` draw.
    fn random_weight(rand: i32) -> Self;
}

macro_rules! impl_format {
    ($v:ty, $s:ty) => {
        impl Format for $v {
            fn from_int(n: i32) -> Self {
                <$v>::from_int(n)
            }
            fn from_f64_trunc(x: f64) -> Self {
                <$v>::from_f64_trunc(x)
            }
            fn to_f64(self) -> f64 {
                <$v>::to_f64(self)
            }
            fn is_within_zero_tolerance(self) -> bool {
                <$v>::is_within_zero_tolerance(self)
            }
            fn abs(self) -> Self {
                <$v>::from_raw(self.raw().wrapping_abs())
            }
            fn random_weight(rand: i32) -> Self {
                // C++: `static_cast<FullWidthValueType>((rand() % (2 * half + 1)) - half)`
                // with `half` = 0.5: a weight in [-0.5, 0.5], computed in int and
                // then narrowed. (Before tinymind #239 the cast came first, which
                // truncated rand() for 16-bit storage.)
                let half = i32::from(<$v>::ONE.raw() / 2);
                let weight = rand % (2 * half + 1) - half;
                <$v>::from_raw(weight as $s)
            }
        }
    };
}

impl_format!(Q16_16, i32);
impl_format!(Q8_8, i16);

/// The formats the example runs in, as `--format` spells them.
pub const FORMATS: [&str; 2] = ["q16.16", "q8.8"];

/// Train and evaluate the network in `format` (one of [`FORMATS`]), writing the
/// three output files into `out_dir` and the summary to `stdout`.
pub fn run_format(
    format: &str,
    out_dir: &Path,
    learning_rate: Option<f64>,
    momentum: Option<f64>,
    stdout: &mut dyn Write,
) -> io::Result<()> {
    match format {
        "q16.16" => run::<Q16_16>(out_dir, learning_rate, momentum, stdout),
        "q8.8" => run::<Q8_8>(out_dir, learning_rate, momentum, stdout),
        other => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("unknown format {other:?}"),
        )),
    }
}

fn run<V: Format>(
    out_dir: &Path,
    learning_rate: Option<f64>,
    momentum: Option<f64>,
    stdout: &mut dyn Write,
) -> io::Result<()>
where
    Tanh: Activation<V>,
    Sigmoid: Activation<V>,
{
    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
    // the network (which draws the initial weights), then srand(7) for the
    // training samples. Re-seeding a global generator becomes two independent
    // generator values in Rust. (The two seeds exist because the C++ network used
    // to be a global, built before main() seeded rand(), i.e. from glibc's default
    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
    let mut rng = GlibcRand::new(RANDOM_SEED);
    if let Some(lr) = learning_rate {
        nn.set_learning_rate(V::from_f64_trunc(lr));
    }
    if let Some(m) = momentum {
        nn.set_momentum_rate(V::from_f64_trunc(m));
    }

    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
    writeln!(curve, "iteration,avg_error")?;

    write_header(&mut results)?;

    let mut avg_error = V::ZERO;
    for i in 0..TRAINING_ITERATIONS {
        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);

        nn.feed_forward(&inputs);
        let error = nn.calculate_error(&target);
        if !error.is_within_zero_tolerance() {
            nn.train(&target);
        }
        let learned = nn.learned_values();

        store_network_properties(&nn, &mut results, &target, &learned)?;
        writeln!(results, "{error}")?;

        // Accumulate |error| in raw LSBs; the average divides it back down.
        avg_error += error.abs();
        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
            avg_error = V::ZERO;
        }
    }

    // Success = every XOR pattern lands on the correct side of 0.5.
    let mut correct = 0;
    for [a, b, expected] in XOR_CASES {
        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
        let ok = (pred >= 0.5) == (expected == 1);
        correct += u32::from(ok);
        writeln!(
            stdout,
            "  {a} ^ {b} = {expected}  pred={}{}",
            fmt_g(pred),
            if ok { "  ok" } else { "  WRONG" }
        )?;
    }
    writeln!(
        stdout,
        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
        fmt_g(evaluate_xor_error(&mut nn))
    )?;

    // Decision surface over the [0,1]^2 grid.
    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
    writeln!(surf, "x0,x1,prob")?;
    const G: i32 = 41;
    for a in 0..G {
        for b in 0..G {
            let x0 = f64::from(a) / f64::from(G - 1);
            let x1 = f64::from(b) / f64::from(G - 1);
            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
        }
    }

    // Flush explicitly so a write error is reported rather than lost in Drop.
    results.flush()?;
    curve.flush()?;
    surf.flush()?;
    stdout.flush()
}

fn generate_xor_training_value<V: Format>(rng: &mut GlibcRand) -> ([V; 2], [V; 1]) {
    let x = rng.next_i32() & 1;
    let y = rng.next_i32() & 1;
    ([V::from_int(x), V::from_int(y)], [V::from_int(x ^ y)])
}

fn predict<V: Format>(nn: &mut NeuralNetwork<V>, x0: V, x1: V) -> f64
where
    Tanh: Activation<V>,
    Sigmoid: Activation<V>,
{
    nn.feed_forward(&[x0, x1]);
    nn.learned_values()[0].to_f64()
}

/// Mean |prediction - target| over the four XOR cases, in real units.
fn evaluate_xor_error<V: Format>(nn: &mut NeuralNetwork<V>) -> f64
where
    Tanh: Activation<V>,
    Sigmoid: Activation<V>,
{
    let mut sum = 0.0;
    for [a, b, expected] in XOR_CASES {
        let pred = predict(nn, V::from_int(a), V::from_int(b));
        sum += (pred - f64::from(expected)).abs();
    }
    sum / 4.0
}

fn write_header(out: &mut impl Write) -> io::Result<()> {
    for i in 0..NUMBER_OF_INPUTS {
        for h in 0..NUMBER_OF_NEURONS_PER_HIDDEN_LAYER {
            write!(out, "Input{i}{h}Weight,")?;
        }
    }
    for h in 0..NUMBER_OF_NEURONS_PER_HIDDEN_LAYER {
        write!(out, "InputBias0{h}Weight,")?;
    }
    for h in 0..NUMBER_OF_NEURONS_PER_HIDDEN_LAYER {
        for o in 0..NUMBER_OF_OUTPUTS {
            write!(out, "Hidden0{h}{o}Weight,")?;
        }
    }
    for o in 0..NUMBER_OF_OUTPUTS {
        write!(out, "Hidden0Bias{o}Weight,")?;
    }
    for o in 0..NUMBER_OF_OUTPUTS {
        write!(out, "Expected{o},")?;
    }
    for o in 0..NUMBER_OF_OUTPUTS {
        write!(out, "Learned{o},")?;
    }
    writeln!(out, "Error")
}

fn store_network_properties<V: Format>(
    nn: &NeuralNetwork<V>,
    out: &mut impl Write,
    expected: &[V; NUMBER_OF_OUTPUTS],
    learned: &[V; NUMBER_OF_OUTPUTS],
) -> io::Result<()> {
    for row in nn.input_weights() {
        for w in row {
            write!(out, "{w},")?;
        }
    }
    for w in nn.input_bias_weights() {
        write!(out, "{w},")?;
    }
    for row in nn.hidden_weights() {
        for w in row {
            write!(out, "{w},")?;
        }
    }
    for w in nn.hidden_bias_weights() {
        write!(out, "{w},")?;
    }
    for value in expected.iter().chain(learned) {
        write!(out, "{value},")?;
    }
    Ok(())
}