Skip to main content

imported_cnn/common/
imported_cnn_driver.rs

1//! The imported_cnn example's program, shared by `examples/imported_cnn.rs` and
2//! `tests/imported_cnn_golden.rs` (which runs it in-process against the C++
3//! output).
4
5use std::io::{self, Write};
6
7use tinymind::int8::calibration::quantize;
8use tinymind::int8::{Requantizer, qrelu};
9
10#[path = "imported_cnn_model.rs"]
11mod cnn;
12
13#[path = "imported_cnn_flat_model.rs"]
14mod cnn_flat;
15
16/// What the C++ check prints, model by model: each layer's integer
17/// requantizer (multiplier, shift, zero point: a ReLU is folded into the
18/// requantizer's lower bound here and applied after it in the C++, so the
19/// bounds differ), the softmax parameters or a hash of the tanh table, then for
20/// 16 test inputs a hash of every intermediate tensor and the outputs.
21pub fn run(out: &mut dyn Write) -> io::Result<()> {
22    run_cnn(out)?;
23    run_cnn_flat(out)
24}
25
26fn print_rq(out: &mut dyn Write, model: &str, name: &str, rq: &Requantizer) -> io::Result<()> {
27    writeln!(
28        out,
29        "{model} {name} rq={},{},{}",
30        rq.multiplier, rq.shift, rq.zero_point
31    )
32}
33
34/// Test input `s`, element `k` of the flat NHWC tensor, as the C++ computes it.
35fn input<const H: usize, const W: usize, const C: usize>(
36    s: usize,
37    scale: f32,
38    zero_point: i8,
39) -> [[[i8; C]; W]; H] {
40    let mut x = [[[0i8; C]; W]; H];
41    for (k, v) in x.iter_mut().flatten().flatten().enumerate() {
42        let real = ((s * 23 + k * 29 + s * k * 7) % 37) as f32 / 18.0 - 1.0;
43        *v = quantize(real, scale, i32::from(zero_point), -128, 127);
44    }
45    x
46}
47
48/// FNV-1a over every byte of the tensors, continuing from `h`.
49fn fnv<'a>(h: u32, tensor: impl IntoIterator<Item = &'a i8>) -> u32 {
50    tensor.into_iter().fold(h, |h, &v| {
51        (h ^ u32::from(v as u8)).wrapping_mul(0x0100_0193)
52    })
53}
54
55fn run_cnn(out: &mut dyn Write) -> io::Result<()> {
56    print_rq(out, "cnn", "conv1", &cnn::BN1.requantizer)?;
57    print_rq(out, "cnn", "conv2", &cnn::BN2_REQUANTIZERS[0])?;
58    print_rq(out, "cnn", "conv3", &cnn::CONV3.requantizer)?;
59    print_rq(out, "cnn", "fc1", &cnn::FC1.requantizer)?;
60    let p = cnn::PROBS;
61    writeln!(
62        out,
63        "cnn softmax={},{},{}",
64        p.input_multiplier, p.input_left_shift, p.diff_min
65    )?;
66    for s in 0..16 {
67        let x: cnn::Input = input(s, cnn::INPUT_SCALE, cnn::INPUT_ZERO_POINT);
68        // Layer by layer, for the hash of every intermediate tensor.
69        let mut a1 = [[[0i8; 4]; 12]; 12];
70        cnn::BN1.forward(&x, &mut a1);
71        let mut p1 = [[[0i8; 4]; 6]; 6];
72        cnn::POOL1.forward(&a1, &mut p1);
73        let mut a2 = [[[0i8; 4]; 6]; 6];
74        cnn::BN2.forward(&p1, &mut a2);
75        let mut a3 = [[[0i8; 8]; 6]; 6];
76        cnn::CONV3.forward(&a2, &mut a3);
77        let g = cnn::GAP.forward(&a3);
78        let mut h = 0x811C_9DC5;
79        h = fnv(h, a1.iter().flatten().flatten());
80        h = fnv(h, p1.iter().flatten().flatten());
81        h = fnv(h, a2.iter().flatten().flatten());
82        h = fnv(h, a3.iter().flatten().flatten());
83        h = fnv(h, &g);
84        // The generated forward for the output.
85        let y = cnn::forward(&x);
86        let mut best = 0;
87        for (k, &v) in y.iter().enumerate() {
88            if v > y[best] {
89                best = k;
90            }
91        }
92        writeln!(
93            out,
94            "cnn s={s} layers=0x{h:08X} probs={},{},{} class={best}",
95            y[0], y[1], y[2]
96        )?;
97    }
98    Ok(())
99}
100
101fn run_cnn_flat(out: &mut dyn Write) -> io::Result<()> {
102    print_rq(out, "cnn_flat", "conv1", &cnn_flat::CONV1.requantizer)?;
103    print_rq(out, "cnn_flat", "fc1", &cnn_flat::FC1.requantizer)?;
104    print_rq(out, "cnn_flat", "fc2", &cnn_flat::FC2.requantizer)?;
105    writeln!(
106        out,
107        "cnn_flat lut fnv=0x{:08X}",
108        fnv(0x811C_9DC5, &cnn_flat::OUT_LUT)
109    )?;
110    for s in 0..16 {
111        let x: cnn_flat::Input = input(s, cnn_flat::INPUT_SCALE, cnn_flat::INPUT_ZERO_POINT);
112        let mut a1 = [[[0i8; 5]; 10]; 4];
113        cnn_flat::CONV1.forward(&x, &mut a1);
114        let mut p1 = [[[0i8; 5]; 5]; 2];
115        cnn_flat::POOL1.forward(&a1, &mut p1);
116        let mut flat = [0i8; 50];
117        for (o, &v) in flat.iter_mut().zip(p1.iter().flatten().flatten()) {
118            *o = v;
119        }
120        let h1 = cnn_flat::FC1
121            .forward(&flat)
122            .map(|v| qrelu(v, cnn_flat::RELU2_ZERO_POINT));
123        let lg = cnn_flat::FC2.forward(&h1);
124        let mut h = 0x811C_9DC5;
125        h = fnv(h, a1.iter().flatten().flatten());
126        h = fnv(h, p1.iter().flatten().flatten());
127        h = fnv(h, &h1);
128        h = fnv(h, &lg);
129        let y = cnn_flat::forward(&x);
130        writeln!(out, "cnn_flat s={s} layers=0x{h:08X} out={},{}", y[0], y[1])?;
131    }
132    Ok(())
133}