Skip to main content

int8_xor/common/
int8_xor_driver.rs

1//! The int8 XOR example's program, shared by `examples/int8_xor.rs` and
2//! `tests/int8_xor_golden.rs` (which runs it in-process against the C++
3//! goldens). Port of tinymind (C++) `examples/pytorch_quant/xor/xor_quant.cpp`.
4
5use std::fs::File;
6use std::io::{self, BufWriter, Write};
7use std::path::Path;
8
9use tinymind::int8::calibration::{build_requantizer, build_sigmoid_lut, dequantize, quantize};
10use tinymind::int8::{LUT_SIZE, QDense, apply_lut, qrelu};
11
12#[path = "cppfmt.rs"]
13mod cppfmt;
14use cppfmt::{fmt_fixed, fmt_g};
15
16/// The trained model: tinymind (C++) `examples/pytorch_quant/xor/weights.hpp`, emitted
17/// by its `xor_quant.py` from a PyTorch model. Copied by hand; any difference
18/// fails the golden test and `scripts/compare-with-cpp.sh`.
19// The float literals keep the C++ digits so the files compare by eye; they
20// round to the same f32 values.
21#[allow(clippy::excessive_precision)]
22mod weights {
23    pub const NUM_INPUTS: usize = 2;
24    pub const HIDDEN_SIZE: usize = 4;
25    pub const NUM_OUTPUTS: usize = 1;
26
27    // Activation calibration (per-tensor, asymmetric int8).
28    pub const INPUT_SCALE: f32 = 0.003_921_568_627_450_98; // 1/255
29    pub const INPUT_ZERO_POINT: i32 = -128;
30    pub const HIDDEN_SCALE: f32 = 0.007_843_137_254_901_96; // 2/255
31    pub const HIDDEN_ZERO_POINT: i32 = -128;
32    pub const LOGIT_SCALE: f32 = 0.015_686_274_509_803_92; // 4/255
33    pub const LOGIT_ZERO_POINT: i32 = -1;
34    pub const SIGMOID_OUT_SCALE: f32 = 0.003_906_25; // 1/256
35    pub const SIGMOID_OUT_ZERO_POINT: i32 = -128;
36
37    // Weight calibration (per-tensor, symmetric int8).
38    pub const FC1_WEIGHT_SCALE: f32 = 0.007_874_015_748_031_496; // 1/127
39    pub const FC2_WEIGHT_SCALE: f32 = 0.031_496_062_992_125_984; // 4/127
40
41    pub static FC1_WEIGHTS: [[i8; NUM_INPUTS]; HIDDEN_SIZE] =
42        [[127, 127], [127, 127], [127, 127], [127, 127]];
43    pub static FC1_BIASES: [i32; HIDDEN_SIZE] = [0, -32385, 0, -32385];
44    pub static FC2_WEIGHTS: [[i8; HIDDEN_SIZE]; NUM_OUTPUTS] = [[64, -127, 64, -127]];
45    pub static FC2_BIASES: [i32; NUM_OUTPUTS] = [-8096];
46}
47
48use weights::*;
49
50const XOR: [[f32; 2]; 4] = [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]];
51const XOR_LABELS: [i32; 4] = [0, 1, 1, 0];
52
53/// The two-layer int8 network: fc1, quantized ReLU, fc2, sigmoid table.
54struct Model {
55    fc1: QDense<'static, NUM_INPUTS, HIDDEN_SIZE>,
56    fc2: QDense<'static, HIDDEN_SIZE, NUM_OUTPUTS>,
57    sigmoid: [i8; LUT_SIZE],
58}
59
60impl Model {
61    /// Rebuild the requantizers and the sigmoid table from the float scales, as
62    /// the C++ example does. An inference-only firmware build would embed the
63    /// resulting integers instead.
64    fn new() -> Self {
65        Model {
66            fc1: QDense {
67                weights: &FC1_WEIGHTS,
68                biases: Some(&FC1_BIASES),
69                input_zero_point: INPUT_ZERO_POINT as i8,
70                requantizer: build_requantizer(
71                    INPUT_SCALE,
72                    FC1_WEIGHT_SCALE,
73                    HIDDEN_SCALE,
74                    HIDDEN_ZERO_POINT,
75                    -128,
76                    127,
77                ),
78            },
79            fc2: QDense {
80                weights: &FC2_WEIGHTS,
81                biases: Some(&FC2_BIASES),
82                input_zero_point: HIDDEN_ZERO_POINT as i8,
83                requantizer: build_requantizer(
84                    HIDDEN_SCALE,
85                    FC2_WEIGHT_SCALE,
86                    LOGIT_SCALE,
87                    LOGIT_ZERO_POINT,
88                    -128,
89                    127,
90                ),
91            },
92            sigmoid: build_sigmoid_lut(
93                LOGIT_SCALE,
94                LOGIT_ZERO_POINT,
95                SIGMOID_OUT_SCALE,
96                SIGMOID_OUT_ZERO_POINT,
97            ),
98        }
99    }
100
101    fn quantize_input(x: [f32; NUM_INPUTS]) -> [i8; NUM_INPUTS] {
102        x.map(|v| quantize(v, INPUT_SCALE, INPUT_ZERO_POINT, -128, 127))
103    }
104
105    /// Returns the int8 logit and the int8 sigmoid output.
106    fn predict(&self, input: &[i8; NUM_INPUTS]) -> (i8, i8) {
107        let hidden = self
108            .fc1
109            .forward(input)
110            .map(|h| qrelu(h, HIDDEN_ZERO_POINT as i8));
111        let logit = self.fc2.forward(&hidden)[0];
112        (logit, apply_lut(logit, &self.sigmoid))
113    }
114}
115
116/// Run the example: print the four XOR cases to `stdout` and write
117/// `xor_decision_surface.csv` into `out_dir`. Returns how many of the four
118/// were classified correctly.
119pub fn run(out_dir: &Path, stdout: &mut dyn Write) -> io::Result<usize> {
120    let model = Model::new();
121
122    writeln!(stdout, "PyTorch -> tinymind int8 XOR inference")?;
123    writeln!(
124        stdout,
125        "  input_scale={} input_zp={} hidden_scale={} hidden_zp={}",
126        fmt_fixed(INPUT_SCALE.into(), 4),
127        INPUT_ZERO_POINT,
128        fmt_fixed(HIDDEN_SCALE.into(), 4),
129        HIDDEN_ZERO_POINT
130    )?;
131    writeln!(
132        stdout,
133        "  logit_scale={} logit_zp={} out_scale={} out_zp={}\n",
134        fmt_fixed(LOGIT_SCALE.into(), 4),
135        LOGIT_ZERO_POINT,
136        fmt_fixed(SIGMOID_OUT_SCALE.into(), 4),
137        SIGMOID_OUT_ZERO_POINT
138    )?;
139
140    let mut correct = 0;
141    for (x, label) in XOR.iter().zip(XOR_LABELS) {
142        let input = Model::quantize_input(*x);
143        let (logit, out) = model.predict(&input);
144        let prob = dequantize(out, SIGMOID_OUT_SCALE, SIGMOID_OUT_ZERO_POINT);
145        let predicted = i32::from(prob > 0.5);
146        if predicted == label {
147            correct += 1;
148        }
149        writeln!(
150            stdout,
151            "  in=({},{})  q_input=({},{})  q_logit={}  prob={}  pred={}  label={}",
152            fmt_fixed(x[0].into(), 4),
153            fmt_fixed(x[1].into(), 4),
154            input[0],
155            input[1],
156            logit,
157            fmt_fixed(prob.into(), 4),
158            predicted,
159            label
160        )?;
161    }
162    writeln!(stdout, "\nint8 XOR accuracy: {correct}/4")?;
163
164    // Decision surface over the [0,1]^2 grid, in f32 as the C++ computes it.
165    let mut surf = BufWriter::new(File::create(out_dir.join("xor_decision_surface.csv"))?);
166    writeln!(surf, "x0,x1,prob")?;
167    const G: i32 = 41;
168    for a in 0..G {
169        for b in 0..G {
170            let x0 = a as f32 / (G - 1) as f32;
171            let x1 = b as f32 / (G - 1) as f32;
172            let (_, out) = model.predict(&Model::quantize_input([x0, x1]));
173            let prob = dequantize(out, SIGMOID_OUT_SCALE, SIGMOID_OUT_ZERO_POINT);
174            writeln!(
175                surf,
176                "{},{},{}",
177                fmt_g(x0.into()),
178                fmt_g(x1.into()),
179                fmt_g(prob.into())
180            )?;
181        }
182    }
183    surf.flush()?;
184    stdout.flush()?;
185    Ok(correct)
186}