Skip to main content

anomaly/common/
anomaly_demo.rs

1//! On-device anomaly detection with a dense autoencoder: the program shared by
2//! `examples/anomaly.rs` (host) and the bench firmware (`bench/`, on the
3//! boards), which run it bit for bit identically. `no_std`, integer only.
4//!
5//! A machine's vibration is simulated as a sine tone with random phase and
6//! amplitude plus noise, sampled in windows of 8. An 8-4-8 autoencoder learns to
7//! reconstruct *normal* windows only, on the device; a window whose
8//! reconstruction error is far above anything seen on normal data is flagged.
9//! Four kinds of fault are then injected: the tone at the wrong frequency, an
10//! added harmonic, an impulse spike, and a stalled sensor.
11//!
12//! The signal is synthetic, so the demo needs no dataset and the same program
13//! runs on a 32 KB part. Everything is deterministic (glibc `rand()`
14//! re-implementation, integer sine table), so the host and the boards produce
15//! the same report and the same hash.
16
17use core::fmt::{self, Write};
18
19use tinymind::rand::GlibcRand;
20use tinymind::{Dense, Linear, NeuralNetwork, Q16_16, Tanh};
21
22/// Samples per window, the autoencoder's input and output width.
23pub const WINDOW: usize = 8;
24/// Bottleneck width.
25pub const CODE: usize = 4;
26/// Training steps, each on a fresh normal window.
27pub const TRAIN_STEPS: u32 = 3_000;
28/// Normal windows used to set the threshold, and normal test windows.
29pub const NORMAL_WINDOWS: u32 = 256;
30/// Test windows per fault type.
31pub const FAULT_WINDOWS: u32 = 64;
32
33/// The autoencoder: 8 inputs -> 4 tanh -> 8 linear outputs.
34pub type Autoencoder = NeuralNetwork<(
35    Dense<Q16_16, Tanh, WINDOW, CODE>,
36    Dense<Q16_16, Linear, CODE, WINDOW>,
37)>;
38
39/// One period of a sine in Q16.16 (sin(2 pi k / 64) * 65536, rounded).
40const SINE: [i32; 64] = [
41    0, 6424, 12785, 19024, 25080, 30893, 36410, 41576, 46341, 50660, 54491, 57798, 60547, 62714,
42    64277, 65220, 65536, 65220, 64277, 62714, 60547, 57798, 54491, 50660, 46341, 41576, 36410,
43    30893, 25080, 19024, 12785, 6424, 0, -6424, -12785, -19024, -25080, -30893, -36410, -41576,
44    -46341, -50660, -54491, -57798, -60547, -62714, -64277, -65220, -65536, -65220, -64277, -62714,
45    -60547, -57798, -54491, -50660, -46341, -41576, -36410, -30893, -25080, -19024, -12785, -6424,
46];
47
48/// The kinds of window the demo generates.
49#[derive(Clone, Copy, PartialEq, Eq)]
50pub enum Kind {
51    Normal,
52    /// The tone at a different frequency.
53    Frequency,
54    /// The normal tone plus its third harmonic.
55    Harmonic,
56    /// The normal tone plus a single large impulse.
57    Spike,
58    /// The sensor stalls: the window holds one value.
59    Stall,
60}
61
62pub const FAULTS: [(Kind, &str); 4] = [
63    (Kind::Frequency, "frequency"),
64    (Kind::Harmonic, "harmonic"),
65    (Kind::Spike, "spike"),
66    (Kind::Stall, "stall"),
67];
68
69/// Deterministic signal source.
70pub struct Signal(GlibcRand);
71
72impl Signal {
73    pub fn new(seed: u32) -> Self {
74        Self(GlibcRand::new(seed))
75    }
76
77    /// A uniform integer in 0..n.
78    fn below(&mut self, n: u32) -> i32 {
79        (self.0.next_i32() as u32 % n) as i32
80    }
81
82    /// One window of the given kind, in Q16.16, within about [-1, 1].
83    pub fn window(&mut self, kind: Kind) -> [Q16_16; WINDOW] {
84        // Normal: step 3 through the table (period 21.3 samples), amplitude
85        // 0.4 to 0.6, any phase, noise within +-0.02.
86        let step = if kind == Kind::Frequency { 9 } else { 3 };
87        let amplitude = 26_214 + self.below(13_108); // 0.4 + [0, 0.2)
88        let phase = self.below(64);
89        let mut w = [Q16_16::ZERO; WINDOW];
90        for (n, s) in w.iter_mut().enumerate() {
91            let k = (phase + n as i32 * step) as usize % 64;
92            let mut v = Q16_16::from_raw(amplitude) * Q16_16::from_raw(SINE[k]);
93            if kind == Kind::Harmonic {
94                let k3 = (phase + 3 * n as i32 * step) as usize % 64;
95                v += Q16_16::from_raw(19_661) * Q16_16::from_raw(SINE[k3]); // + 0.3 sin(3x)
96            }
97            let noise = self.below(2_623) - 1_311; // +-0.02
98            *s = v + Q16_16::from_raw(noise);
99        }
100        match kind {
101            Kind::Spike => {
102                let at = self.below(WINDOW as u32) as usize;
103                w[at] += Q16_16::from_raw(52_429); // + 0.8
104            }
105            Kind::Stall => {
106                let held = w[0];
107                w = [held; WINDOW];
108            }
109            _ => {}
110        }
111        w
112    }
113}
114
115/// The reconstruction error of one window: tinymind's mean squared error of
116/// the output against the input.
117#[inline(never)]
118pub fn score(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
119    nn.feed_forward(w);
120    nn.calculate_error(w)
121}
122
123/// Initial weights in [-0.5, 0.5], as tinymind's examples draw them.
124pub fn new_autoencoder(seed: u32) -> Autoencoder {
125    let mut rng = GlibcRand::new(seed);
126    let half = Q16_16::ONE.raw() / 2;
127    let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128    nn.set_learning_rate(Q16_16::from_raw(1 << 11)); // 1/32
129    nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); // 1/2
130    nn.set_acceleration_rate(Q16_16::ZERO);
131    nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132    nn
133}
134
135/// One training step on window `w` (forward pass, error, back-propagation);
136/// returns the error before the step. Out of line, so the training loop and the
137/// board's timing loop share one copy (the 32 KB board has no room for two).
138#[inline(never)]
139pub fn train_step(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
140    let error = score(nn, w);
141    nn.train(w);
142    error
143}
144
145/// Train on `steps` normal windows; returns the mean error (raw) over the last
146/// 500 steps.
147#[inline(never)]
148pub fn train(nn: &mut Autoencoder, signal: &mut Signal, steps: u32) -> i32 {
149    // Errors at the end of training are a few hundred raw units at most, so
150    // the sum of 500 fits easily; saturate rather than wrap if it ever does not.
151    let mut recent = 0i32;
152    for step in 0..steps {
153        let w = signal.window(Kind::Normal);
154        let error = train_step(nn, &w);
155        if step + 500 >= steps {
156            recent = recent.saturating_add(error.raw());
157        }
158    }
159    recent / 500
160}
161
162/// 32-bit FNV-1a over everything written, to compare host and board runs.
163pub struct Fnv(pub u32);
164
165impl Fnv {
166    pub fn new() -> Self {
167        Self(0x811C_9DC5)
168    }
169    pub fn add(&mut self, raw: i32) {
170        for b in raw.to_le_bytes() {
171            self.0 ^= u32::from(b);
172            self.0 = self.0.wrapping_mul(0x0100_0193);
173        }
174    }
175}
176
177/// Everything after training: set the threshold from normal windows, test
178/// normal and faulty windows, and print the report. `each` sees every test
179/// window's kind name and score (raw), for a plot. Returns the hash of the
180/// trained weights and every score.
181#[inline(never)]
182pub fn evaluate(
183    nn: &mut Autoencoder,
184    signal: &mut Signal,
185    out: &mut dyn Write,
186    each: &mut dyn FnMut(&str, i32),
187) -> Result<u32, fmt::Error> {
188    let mut hash = Fnv::new();
189    let (l0, l1) = nn.layers();
190    for row in l0.weights() {
191        for w in row {
192            hash.add(w.raw());
193        }
194    }
195    for w in l0.bias_weights() {
196        hash.add(w.raw());
197    }
198    for row in l1.weights() {
199        for w in row {
200            hash.add(w.raw());
201        }
202    }
203    for w in l1.bias_weights() {
204        hash.add(w.raw());
205    }
206
207    // Threshold: twice the largest error on normal validation windows.
208    let mut max_normal = 0;
209    for _ in 0..NORMAL_WINDOWS {
210        let e = score(nn, &signal.window(Kind::Normal)).raw();
211        hash.add(e);
212        max_normal = max_normal.max(e);
213    }
214    let threshold = max_normal.saturating_mul(2);
215    writeln!(
216        out,
217        "threshold={threshold} (2 x the largest error on {NORMAL_WINDOWS} normal windows, raw Q16.16)"
218    )?;
219
220    let mut flagged = |kind: Kind, name: &str, n: u32, hash: &mut Fnv| {
221        let mut count = 0;
222        for _ in 0..n {
223            let e = score(nn, &signal.window(kind)).raw();
224            hash.add(e);
225            each(name, e);
226            count += u32::from(e > threshold);
227        }
228        count
229    };
230    let fp = flagged(Kind::Normal, "normal", NORMAL_WINDOWS, &mut hash);
231    writeln!(out, "normal: flagged {fp}/{NORMAL_WINDOWS} (false alarms)")?;
232    for (kind, name) in FAULTS {
233        let tp = flagged(kind, name, FAULT_WINDOWS, &mut hash);
234        writeln!(out, "{name}: flagged {tp}/{FAULT_WINDOWS}")?;
235    }
236    writeln!(out, "hash=0x{:08X}", hash.0)?;
237    Ok(hash.0)
238}
239
240/// The whole demo: train on normal windows, then evaluate. Seeds are fixed.
241/// (The board firmware calls the pieces itself, to time them.)
242#[allow(dead_code)]
243pub fn run(out: &mut dyn Write, each: &mut dyn FnMut(&str, i32)) -> Result<u32, fmt::Error> {
244    let mut nn = new_autoencoder(1);
245    let mut signal = Signal::new(7);
246    writeln!(
247        out,
248        "autoencoder {WINDOW}-{CODE}-{WINDOW} (tanh, linear), Q16.16, {TRAIN_STEPS} training steps on normal windows"
249    )?;
250    let recent = train(&mut nn, &mut signal, TRAIN_STEPS);
251    writeln!(
252        out,
253        "training error, mean of the last 500 steps={recent} (raw Q16.16)"
254    )?;
255    evaluate(&mut nn, &mut signal, out, each)
256}