1use 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#[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 pub const INPUT_SCALE: f32 = 0.003_921_568_627_450_98; pub const INPUT_ZERO_POINT: i32 = -128;
30 pub const HIDDEN_SCALE: f32 = 0.007_843_137_254_901_96; pub const HIDDEN_ZERO_POINT: i32 = -128;
32 pub const LOGIT_SCALE: f32 = 0.015_686_274_509_803_92; pub const LOGIT_ZERO_POINT: i32 = -1;
34 pub const SIGMOID_OUT_SCALE: f32 = 0.003_906_25; pub const SIGMOID_OUT_ZERO_POINT: i32 = -128;
36
37 pub const FC1_WEIGHT_SCALE: f32 = 0.007_874_015_748_031_496; pub const FC2_WEIGHT_SCALE: f32 = 0.031_496_062_992_125_984; 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
53struct 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 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 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
116pub 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 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}