Skip to main content

xor/common/
xor_driver.rs

1//! The xor example's program, shared by `examples/xor.rs` (which parses the
2//! command line) and `tests/xor_golden.rs` (which runs it in-process against the
3//! C++ goldens). Port of tinymind (C++) `examples/xor/xor.cpp`; see `examples/xor.rs`.
4
5use std::fmt::Display;
6use std::fs::File;
7use std::io::{self, BufWriter, Write};
8use std::path::Path;
9
10use tinymind::rand::GlibcRand;
11
12#[path = "cppfmt.rs"]
13mod cppfmt;
14use cppfmt::fmt_g;
15use tinymind::{Activation, MultilayerPerceptron, Q8_8, Q16_16, Scalar, Sigmoid, Tanh};
16
17const TRAINING_ITERATIONS: u32 = 20_000;
18const NUM_SAMPLES_AVG_ERROR: u32 = 100;
19const RANDOM_SEED: u32 = 7;
20/// C++ `WEIGHT_INIT_SEED`: seeds the initial weights only.
21const WEIGHT_INIT_SEED: u32 = 1;
22
23const NUMBER_OF_INPUTS: usize = 2;
24const NUMBER_OF_NEURONS_PER_HIDDEN_LAYER: usize = 4;
25const NUMBER_OF_OUTPUTS: usize = 1;
26
27type NeuralNetwork<V> = MultilayerPerceptron<
28    V,
29    Tanh,
30    Sigmoid,
31    NUMBER_OF_INPUTS,
32    NUMBER_OF_NEURONS_PER_HIDDEN_LAYER,
33    NUMBER_OF_OUTPUTS,
34>;
35
36const XOR_CASES: [[i32; 3]; 4] = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]];
37
38/// What the driver needs from a value type beyond [`Scalar`]. Both formats have
39/// these as inherent methods; the trait lets [`run`] be generic over them.
40trait Format: Scalar + Display {
41    fn from_int(n: i32) -> Self;
42    fn from_f64_trunc(x: f64) -> Self;
43    fn to_f64(self) -> f64;
44    fn is_within_zero_tolerance(self) -> bool;
45    /// C++ `ValueType(abs(error.getValue()))`.
46    fn abs(self) -> Self;
47    /// C++ `RandomNumberGenerator::generateRandomWeight` given one `rand()` draw.
48    fn random_weight(rand: i32) -> Self;
49}
50
51macro_rules! impl_format {
52    ($v:ty, $s:ty) => {
53        impl Format for $v {
54            fn from_int(n: i32) -> Self {
55                <$v>::from_int(n)
56            }
57            fn from_f64_trunc(x: f64) -> Self {
58                <$v>::from_f64_trunc(x)
59            }
60            fn to_f64(self) -> f64 {
61                <$v>::to_f64(self)
62            }
63            fn is_within_zero_tolerance(self) -> bool {
64                <$v>::is_within_zero_tolerance(self)
65            }
66            fn abs(self) -> Self {
67                <$v>::from_raw(self.raw().wrapping_abs())
68            }
69            fn random_weight(rand: i32) -> Self {
70                // C++: `static_cast<FullWidthValueType>((rand() % (2 * half + 1)) - half)`
71                // with `half` = 0.5: a weight in [-0.5, 0.5], computed in int and
72                // then narrowed. (Before tinymind #239 the cast came first, which
73                // truncated rand() for 16-bit storage.)
74                let half = i32::from(<$v>::ONE.raw() / 2);
75                let weight = rand % (2 * half + 1) - half;
76                <$v>::from_raw(weight as $s)
77            }
78        }
79    };
80}
81
82impl_format!(Q16_16, i32);
83impl_format!(Q8_8, i16);
84
85/// The formats the example runs in, as `--format` spells them.
86pub const FORMATS: [&str; 2] = ["q16.16", "q8.8"];
87
88/// Train and evaluate the network in `format` (one of [`FORMATS`]), writing the
89/// three output files into `out_dir` and the summary to `stdout`.
90pub fn run_format(
91    format: &str,
92    out_dir: &Path,
93    learning_rate: Option<f64>,
94    momentum: Option<f64>,
95    stdout: &mut dyn Write,
96) -> io::Result<()> {
97    match format {
98        "q16.16" => run::<Q16_16>(out_dir, learning_rate, momentum, stdout),
99        "q8.8" => run::<Q8_8>(out_dir, learning_rate, momentum, stdout),
100        other => Err(io::Error::new(
101            io::ErrorKind::InvalidInput,
102            format!("unknown format {other:?}"),
103        )),
104    }
105}
106
107fn run<V: Format>(
108    out_dir: &Path,
109    learning_rate: Option<f64>,
110    momentum: Option<f64>,
111    stdout: &mut dyn Write,
112) -> io::Result<()>
113where
114    Tanh: Activation<V>,
115    Sigmoid: Activation<V>,
116{
117    // The C++ example seeds rand() twice: srand(WEIGHT_INIT_SEED = 1), construct
118    // the network (which draws the initial weights), then srand(7) for the
119    // training samples. Re-seeding a global generator becomes two independent
120    // generator values in Rust. (The two seeds exist because the C++ network used
121    // to be a global, built before main() seeded rand(), i.e. from glibc's default
122    // seed of 1; tinymind PR #236 made that explicit without changing any output.)
123    let mut init_rng = GlibcRand::new(WEIGHT_INIT_SEED);
124    let mut nn = NeuralNetwork::<V>::new(|| V::random_weight(init_rng.next_i32()));
125    let mut rng = GlibcRand::new(RANDOM_SEED);
126    if let Some(lr) = learning_rate {
127        nn.set_learning_rate(V::from_f64_trunc(lr));
128    }
129    if let Some(m) = momentum {
130        nn.set_momentum_rate(V::from_f64_trunc(m));
131    }
132
133    let mut results = BufWriter::new(File::create(out_dir.join("nn_fixed_xor.txt"))?);
134    let mut curve = BufWriter::new(File::create(out_dir.join("xor_training.csv"))?);
135    writeln!(curve, "iteration,avg_error")?;
136
137    write_header(&mut results)?;
138
139    let mut avg_error = V::ZERO;
140    for i in 0..TRAINING_ITERATIONS {
141        let (inputs, target) = generate_xor_training_value::<V>(&mut rng);
142
143        nn.feed_forward(&inputs);
144        let error = nn.calculate_error(&target);
145        if !error.is_within_zero_tolerance() {
146            nn.train(&target);
147        }
148        let learned = nn.learned_values();
149
150        store_network_properties(&nn, &mut results, &target, &learned)?;
151        writeln!(results, "{error}")?;
152
153        // Accumulate |error| in raw LSBs; the average divides it back down.
154        avg_error += error.abs();
155        if (i + 1) % NUM_SAMPLES_AVG_ERROR == 0 {
156            avg_error = avg_error / V::from_int(NUM_SAMPLES_AVG_ERROR as i32);
157            writeln!(stdout, "Iteration: {} Average Error: {}", i + 1, avg_error)?;
158            writeln!(curve, "{},{}", i + 1, fmt_g(evaluate_xor_error(&mut nn)))?;
159            avg_error = V::ZERO;
160        }
161    }
162
163    // Success = every XOR pattern lands on the correct side of 0.5.
164    let mut correct = 0;
165    for [a, b, expected] in XOR_CASES {
166        let pred = predict(&mut nn, V::from_int(a), V::from_int(b));
167        let ok = (pred >= 0.5) == (expected == 1);
168        correct += u32::from(ok);
169        writeln!(
170            stdout,
171            "  {a} ^ {b} = {expected}  pred={}{}",
172            fmt_g(pred),
173            if ok { "  ok" } else { "  WRONG" }
174        )?;
175    }
176    writeln!(
177        stdout,
178        "{correct}/4 patterns classified correctly. Final 4-case error: {}",
179        fmt_g(evaluate_xor_error(&mut nn))
180    )?;
181
182    // Decision surface over the [0,1]^2 grid.
183    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
184    writeln!(surf, "x0,x1,prob")?;
185    const G: i32 = 41;
186    for a in 0..G {
187        for b in 0..G {
188            let x0 = f64::from(a) / f64::from(G - 1);
189            let x1 = f64::from(b) / f64::from(G - 1);
190            let prob = predict(&mut nn, V::from_f64_trunc(x0), V::from_f64_trunc(x1));
191            writeln!(surf, "{},{},{}", fmt_g(x0), fmt_g(x1), fmt_g(prob))?;
192        }
193    }
194
195    // Flush explicitly so a write error is reported rather than lost in Drop.
196    results.flush()?;
197    curve.flush()?;
198    surf.flush()?;
199    stdout.flush()
200}
201
202fn generate_xor_training_value<V: Format>(rng: &mut GlibcRand) -> ([V; 2], [V; 1]) {
203    let x = rng.next_i32() & 1;
204    let y = rng.next_i32() & 1;
205    ([V::from_int(x), V::from_int(y)], [V::from_int(x ^ y)])
206}
207
208fn predict<V: Format>(nn: &mut NeuralNetwork<V>, x0: V, x1: V) -> f64
209where
210    Tanh: Activation<V>,
211    Sigmoid: Activation<V>,
212{
213    nn.feed_forward(&[x0, x1]);
214    nn.learned_values()[0].to_f64()
215}
216
217/// Mean |prediction - target| over the four XOR cases, in real units.
218fn evaluate_xor_error<V: Format>(nn: &mut NeuralNetwork<V>) -> f64
219where
220    Tanh: Activation<V>,
221    Sigmoid: Activation<V>,
222{
223    let mut sum = 0.0;
224    for [a, b, expected] in XOR_CASES {
225        let pred = predict(nn, V::from_int(a), V::from_int(b));
226        sum += (pred - f64::from(expected)).abs();
227    }
228    sum / 4.0
229}
230
231fn write_header(out: &mut impl Write) -> io::Result<()> {
232    for i in 0..NUMBER_OF_INPUTS {
233        for h in 0..NUMBER_OF_NEURONS_PER_HIDDEN_LAYER {
234            write!(out, "Input{i}{h}Weight,")?;
235        }
236    }
237    for h in 0..NUMBER_OF_NEURONS_PER_HIDDEN_LAYER {
238        write!(out, "InputBias0{h}Weight,")?;
239    }
240    for h in 0..NUMBER_OF_NEURONS_PER_HIDDEN_LAYER {
241        for o in 0..NUMBER_OF_OUTPUTS {
242            write!(out, "Hidden0{h}{o}Weight,")?;
243        }
244    }
245    for o in 0..NUMBER_OF_OUTPUTS {
246        write!(out, "Hidden0Bias{o}Weight,")?;
247    }
248    for o in 0..NUMBER_OF_OUTPUTS {
249        write!(out, "Expected{o},")?;
250    }
251    for o in 0..NUMBER_OF_OUTPUTS {
252        write!(out, "Learned{o},")?;
253    }
254    writeln!(out, "Error")
255}
256
257fn store_network_properties<V: Format>(
258    nn: &NeuralNetwork<V>,
259    out: &mut impl Write,
260    expected: &[V; NUMBER_OF_OUTPUTS],
261    learned: &[V; NUMBER_OF_OUTPUTS],
262) -> io::Result<()> {
263    for row in nn.input_weights() {
264        for w in row {
265            write!(out, "{w},")?;
266        }
267    }
268    for w in nn.input_bias_weights() {
269        write!(out, "{w},")?;
270    }
271    for row in nn.hidden_weights() {
272        for w in row {
273            write!(out, "{w},")?;
274        }
275    }
276    for w in nn.hidden_bias_weights() {
277        write!(out, "{w},")?;
278    }
279    for value in expected.iter().chain(learned) {
280        write!(out, "{value},")?;
281    }
282    Ok(())
283}