tinymind/head.rs
1//! Head-only fine-tuning: small classifiers that sit on top of a frozen model
2//! and learn on the device from a few labelled samples. Ported from
3//! tinymind (C++) `cpp/densehead.hpp` and `cpp/prototypehead.hpp`.
4//!
5//! A model trained on the host meets data on the device that it never saw: a
6//! sensor ages, a user moves differently, a new class appears. Retraining the
7//! whole network on a microcontroller needs the training state of every layer.
8//! Head-only fine-tuning keeps the shipped model frozen and adapts only a head
9//! on top of its embedding. Nothing is backpropagated through the frozen model,
10//! so there are no stored activations and no gradients for it, and neither
11//! head allocates.
12//!
13//! - [`DenseHead`] is a trainable dense layer, trained by SGD with a softmax
14//! cross-entropy loss ([`SoftmaxCrossEntropyLoss`], the default) or a
15//! squared-error loss ([`SquaredErrorLoss`]). The update is fused into the
16//! backward pass, so its RAM is its parameters: `(IN + 1) x OUT` values.
17//! - [`PrototypeHead`] is a nearest-class-mean classifier: one running-mean
18//! embedding per class, no learning rate, no epochs, and a class can be
19//! added at any time. Distance: [`SquaredEuclideanDistance`] (the default)
20//! or [`ManhattanDistance`].
21//!
22//! The frozen model can be anything that produces an embedding: an
23//! [`InferenceNetwork`](crate::InferenceNetwork), an [`int8`](crate::int8)
24//! pipeline whose output the application converts to a Q format, or the
25//! layers in front of the last one of a trained network. The `gas_sensor_drift` example adapts a Q16.16
26//! 128 -> 32 -> 6 classifier to drifted sensor data both ways.
27//!
28//! Both heads run on [`Q16_16`], [`Q8_8`], `f32` and `f64`. The softmax needs
29//! an exponential ([`SoftmaxExp`]): the 96-entry exp lookup table for the Q
30//! formats, the math library for the float types (feature `std` or `libm`).
31//! [`SquaredErrorLoss`] and [`PrototypeHead`] need only arithmetic.
32//!
33//! Every operation produces the same bits as tinymind (C++) (floating point:
34//! with `std` on a glibc host).
35//!
36//! ```
37//! use tinymind::Q16_16;
38//! use tinymind::head::{DenseHead, PrototypeHead};
39//!
40//! // A 4-value embedding and 2 classes.
41//! let a = [1, 1, 0, 0].map(Q16_16::from_int);
42//! let b = [0, 0, 1, 1].map(Q16_16::from_int);
43//!
44//! let mut dense = DenseHead::<Q16_16, 4, 2>::new();
45//! let rate = Q16_16::pow2_neg(2); // 0.25
46//! for _ in 0..20 {
47//! dense.train_class(&a, 0, rate, None);
48//! dense.train_class(&b, 1, rate, None);
49//! }
50//! assert_eq!((dense.predict(&a), dense.predict(&b)), (0, 1));
51//!
52//! let mut prototypes = PrototypeHead::<Q16_16, 4, 2>::new();
53//! prototypes.learn(&a, 0);
54//! prototypes.learn(&b, 1);
55//! assert_eq!((prototypes.predict(&a), prototypes.predict(&b)), (0, 1));
56//! ```
57
58use core::marker::PhantomData;
59
60use crate::activation::lookup;
61use crate::lut::{EXP_Q8_8, EXP_Q16_16};
62use crate::neuralnet::argmax;
63use crate::qformat::{Q8_8, Q16_16, Scalar};
64
65/// `exp(x)` for the softmax's shifted logits, `x <= 0` (C++
66/// `detail::HeadExp`).
67///
68/// For the Q formats it is the 96-entry exp lookup table, which spans
69/// `[-6, 6]` and clamps below. A class 6 or more behind the largest logit
70/// would then keep `e^-6 ~ 0.0025` of the probability, the softmax would never
71/// reach a one-hot and the logits of a well separated head would grow until
72/// the format wraps; at or below -6 the true value is under 0.0025, so it is
73/// taken as 0. For `f32` and `f64` it is the math library's `exp` (feature
74/// `std` or `libm`).
75pub trait SoftmaxExp: Scalar {
76 /// `exp(self)` for `self <= 0`.
77 fn softmax_exp(self) -> Self;
78}
79
80impl SoftmaxExp for Q16_16 {
81 fn softmax_exp(self) -> Self {
82 if self <= Q16_16::from_int(-6) {
83 Q16_16::ZERO
84 } else {
85 lookup(self, &EXP_Q16_16)
86 }
87 }
88}
89
90impl SoftmaxExp for Q8_8 {
91 fn softmax_exp(self) -> Self {
92 if self <= Q8_8::from_int(-6) {
93 Q8_8::ZERO
94 } else {
95 lookup(self, &EXP_Q8_8)
96 }
97 }
98}
99
100#[cfg(feature = "std")]
101impl SoftmaxExp for f32 {
102 fn softmax_exp(self) -> Self {
103 self.exp()
104 }
105}
106
107#[cfg(feature = "std")]
108impl SoftmaxExp for f64 {
109 fn softmax_exp(self) -> Self {
110 self.exp()
111 }
112}
113
114#[cfg(all(feature = "libm", not(feature = "std")))]
115impl SoftmaxExp for f32 {
116 fn softmax_exp(self) -> Self {
117 libm::expf(self)
118 }
119}
120
121#[cfg(all(feature = "libm", not(feature = "std")))]
122impl SoftmaxExp for f64 {
123 fn softmax_exp(self) -> Self {
124 libm::exp(self)
125 }
126}
127
128/// How a [`DenseHead`] turns its logits and a target into output deltas,
129/// following the library's convention `delta = -dL/dz`: a parameter moves by
130/// `+learning rate x delta x input`.
131pub trait HeadLoss<V> {
132 /// `deltas[k]` for `logits[k]` and `targets[k]`.
133 fn output_deltas<const N: usize>(logits: &[V; N], targets: &[V; N]) -> [V; N];
134}
135
136/// Softmax over the logits with cross-entropy loss, the usual classifier head
137/// (C++ `SoftmaxCrossEntropyHeadLoss`): `delta = t - softmax(z)`.
138///
139/// The largest logit is subtracted before `exp`, so every argument is `<= 0`
140/// and every `exp` lies in `[0, 1]`: no format overflows however large the
141/// logits grow. See [`SoftmaxExp`] for the classes 6 or more behind.
142pub struct SoftmaxCrossEntropyLoss;
143
144impl SoftmaxCrossEntropyLoss {
145 /// The softmax of `logits`. In the Q formats the probabilities are
146 /// rounded by the format, so they need not sum to exactly 1.
147 pub fn probabilities<V: SoftmaxExp, const N: usize>(logits: &[V; N]) -> [V; N] {
148 let mut largest = match logits.first() {
149 Some(&first) => first,
150 None => return *logits,
151 };
152 for &z in logits.iter().skip(1) {
153 if z > largest {
154 largest = z;
155 }
156 }
157
158 let mut probabilities = [V::ZERO; N];
159 let mut sum = V::ZERO;
160 for (p, &z) in probabilities.iter_mut().zip(logits) {
161 *p = (z - largest).softmax_exp();
162 sum += *p;
163 }
164
165 // exp(0) = 1 is in the sum, so it is never 0.
166 if sum != V::ZERO {
167 for p in &mut probabilities {
168 *p = *p / sum;
169 }
170 }
171 probabilities
172 }
173}
174
175impl<V: SoftmaxExp> HeadLoss<V> for SoftmaxCrossEntropyLoss {
176 fn output_deltas<const N: usize>(logits: &[V; N], targets: &[V; N]) -> [V; N] {
177 let mut deltas = Self::probabilities(logits);
178 for (d, &t) in deltas.iter_mut().zip(targets) {
179 *d = t - *d;
180 }
181 deltas
182 }
183}
184
185/// A linear output with squared-error loss `L = 0.5 x sum((t - z)^2)`, for a
186/// regression head or a classifier that regresses a one-hot target (C++
187/// `SquaredErrorHeadLoss`): `delta = t - z`. Arithmetic only.
188pub struct SquaredErrorLoss;
189
190impl<V: Scalar> HeadLoss<V> for SquaredErrorLoss {
191 fn output_deltas<const N: usize>(logits: &[V; N], targets: &[V; N]) -> [V; N] {
192 let mut deltas = *targets;
193 for (d, &z) in deltas.iter_mut().zip(logits) {
194 *d = *d - z;
195 }
196 deltas
197 }
198}
199
200/// A trainable dense layer to put on top of a frozen model: head-only
201/// fine-tuning (C++ `DenseHead`).
202///
203/// The frozen model turns a sample into an embedding of `IN` values; the head
204/// maps it to `OUT` logits and learns from labelled samples. The training
205/// state is the head's parameters and one embedding: the update is fused into
206/// the backward pass, so there is no gradient buffer, and the RAM is
207/// `(IN + 1) x OUT` values.
208///
209/// The SGD step is plain gradient descent, `learning rate x (delta x input)`,
210/// the product with the learning rate rounded to nearest
211/// ([`Scalar::mul_round_nearest`]), as the crate's SGD step is.
212/// There is no momentum. The Q formats wrap on overflow, so keep the
213/// embedding and the logits well inside the format: z-scored inputs and a
214/// Q16.16 head are the working recipe, and Q8.8 is too narrow for a wide head.
215///
216/// To undo an adaptation, reload the shipped parameters with
217/// [`load_weights`](Self::load_weights), keeping them in flash rather than
218/// spending RAM on a copy.
219pub struct DenseHead<V, const IN: usize, const OUT: usize, L = SoftmaxCrossEntropyLoss> {
220 /// `weights[o][i]` connects input `i` to output `o`.
221 pub weights: [[V; IN]; OUT],
222 /// One bias per output.
223 pub biases: [V; OUT],
224 loss: PhantomData<L>,
225}
226
227impl<V: Copy, const IN: usize, const OUT: usize, L> Clone for DenseHead<V, IN, OUT, L> {
228 fn clone(&self) -> Self {
229 *self
230 }
231}
232
233impl<V: Copy, const IN: usize, const OUT: usize, L> Copy for DenseHead<V, IN, OUT, L> {}
234
235impl<V: Scalar, const IN: usize, const OUT: usize, L> Default for DenseHead<V, IN, OUT, L> {
236 fn default() -> Self {
237 Self::new()
238 }
239}
240
241impl<V, const IN: usize, const OUT: usize, L> DenseHead<V, IN, OUT, L> {
242 /// A head with the given parameters, for example the shipped head kept in
243 /// flash.
244 pub const fn from_weights(weights: [[V; IN]; OUT], biases: [V; OUT]) -> Self {
245 Self {
246 weights,
247 biases,
248 loss: PhantomData,
249 }
250 }
251}
252
253impl<V: Scalar, const IN: usize, const OUT: usize, L> DenseHead<V, IN, OUT, L> {
254 /// A head with every weight and bias 0. It predicts class 0 for every
255 /// input until it is trained.
256 pub fn new() -> Self {
257 Self::from_weights([[V::ZERO; IN]; OUT], [V::ZERO; OUT])
258 }
259
260 /// Set every weight and bias to 0.
261 pub fn clear(&mut self) {
262 *self = Self::new();
263 }
264
265 /// Draw every weight from `random_weight`, output by output, and set the
266 /// biases to 0 (C++ `initializeWeights`).
267 pub fn initialize_weights(&mut self, mut random_weight: impl FnMut() -> V) {
268 for row in &mut self.weights {
269 for w in row {
270 *w = random_weight();
271 }
272 }
273 self.biases = [V::ZERO; OUT];
274 }
275
276 /// Replace every parameter, for example to restore the shipped head.
277 pub fn load_weights(&mut self, weights: &[[V; IN]; OUT], biases: &[V; OUT]) {
278 self.weights = *weights;
279 self.biases = *biases;
280 }
281
282 /// `logits[o] = bias[o] + sum_i weight[o][i] x input[i]`.
283 pub fn forward(&self, input: &[V; IN]) -> [V; OUT] {
284 let mut logits = self.biases;
285 for (z, row) in logits.iter_mut().zip(&self.weights) {
286 let mut sum = *z;
287 for (&w, &x) in row.iter().zip(input) {
288 sum += w * x;
289 }
290 *z = sum;
291 }
292 logits
293 }
294
295 /// The index of the largest logit (the first one on a tie).
296 pub fn predict(&self, input: &[V; IN]) -> usize {
297 argmax(&self.forward(input))
298 }
299
300 /// `input_deltas[i] = sum_o weight[o][i] x output_deltas[o]`, with the
301 /// weights as they are now: the gradient with respect to the embedding
302 /// (times -1, the same delta convention), for a caller that also adapts
303 /// what lies in front of the head. Call it before [`update`](Self::update).
304 pub fn backward(&self, output_deltas: &[V; OUT]) -> [V; IN] {
305 let mut input_deltas = [V::ZERO; IN];
306 for (row, &delta) in self.weights.iter().zip(output_deltas) {
307 for (d, &w) in input_deltas.iter_mut().zip(row) {
308 *d += w * delta;
309 }
310 }
311 input_deltas
312 }
313
314 /// One SGD step: `weight[o][i] += learning rate x (delta[o] x input[i])`
315 /// and `bias[o] += learning rate x delta[o]`, each product with the
316 /// learning rate rounded to nearest.
317 pub fn update(&mut self, output_deltas: &[V; OUT], input: &[V; IN], learning_rate: V) {
318 for ((row, b), &delta) in self
319 .weights
320 .iter_mut()
321 .zip(&mut self.biases)
322 .zip(output_deltas)
323 {
324 update_row(row, input, delta, learning_rate);
325 *b += learning_rate.mul_round_nearest(delta);
326 }
327 }
328}
329
330impl<V: Scalar, const IN: usize, const OUT: usize, L: HeadLoss<V>> DenseHead<V, IN, OUT, L> {
331 /// The output deltas (`t - y` under the loss) for logits from
332 /// [`forward`](Self::forward).
333 pub fn output_deltas(&self, logits: &[V; OUT], targets: &[V; OUT]) -> [V; OUT] {
334 L::output_deltas(logits, targets)
335 }
336
337 /// Forward, loss, optional backward and update on one sample.
338 /// `input_deltas`, when given, receives [`backward`](Self::backward) of
339 /// this sample's deltas, computed before the update. Returns the
340 /// prediction made before the update, for a running accuracy.
341 pub fn train(
342 &mut self,
343 input: &[V; IN],
344 targets: &[V; OUT],
345 learning_rate: V,
346 input_deltas: Option<&mut [V; IN]>,
347 ) -> usize {
348 let logits = self.forward(input);
349 let predicted = argmax(&logits);
350 let deltas = L::output_deltas(&logits, targets);
351 if let Some(input_deltas) = input_deltas {
352 *input_deltas = self.backward(&deltas);
353 }
354 self.update(&deltas, input, learning_rate);
355 predicted
356 }
357
358 /// [`train`](Self::train) with a one-hot target for `class`. A `class` of
359 /// `OUT` or more gives an all-zero target, as in the C++.
360 pub fn train_class(
361 &mut self,
362 input: &[V; IN],
363 class: usize,
364 learning_rate: V,
365 input_deltas: Option<&mut [V; IN]>,
366 ) -> usize {
367 let targets = core::array::from_fn(|o| if o == class { V::ONE } else { V::ZERO });
368 self.train(input, &targets, learning_rate, input_deltas)
369 }
370}
371
372/// One row of [`DenseHead::update`]. Never inlined: inlined, LLVM unrolls
373/// the loop over the rows at `opt-level = 3`, which cost about 1.5 KB of
374/// flash on Cortex-M and made the Cortex-M0+ slower, not faster.
375#[inline(never)]
376fn update_row<V: Scalar, const IN: usize>(
377 row: &mut [V; IN],
378 input: &[V; IN],
379 delta: V,
380 learning_rate: V,
381) {
382 for (w, &x) in row.iter_mut().zip(input) {
383 *w += learning_rate.mul_round_nearest(delta * x);
384 }
385}
386
387/// The distance a [`PrototypeHead`] compares embeddings with.
388pub trait Distance<V> {
389 /// The distance between `a` and `b`.
390 fn distance<const N: usize>(a: &[V; N], b: &[V; N]) -> V;
391}
392
393/// `sum_i (a[i] - b[i])^2`, the usual nearest-class-mean distance (C++
394/// `SquaredEuclideanDistance`). In a Q format the sum must stay inside the
395/// format (it wraps): with Q16.16, `N x (largest difference)^2` below 32767.
396pub struct SquaredEuclideanDistance;
397
398impl<V: Scalar> Distance<V> for SquaredEuclideanDistance {
399 fn distance<const N: usize>(a: &[V; N], b: &[V; N]) -> V {
400 let mut sum = V::ZERO;
401 for (&x, &y) in a.iter().zip(b) {
402 let difference = x - y;
403 sum += difference * difference;
404 }
405 sum
406 }
407}
408
409/// `sum_i |a[i] - b[i]|` (C++ `ManhattanDistance`). No multiplies, so it is
410/// cheaper on a core without a fast multiplier and has far more headroom
411/// before it overflows.
412pub struct ManhattanDistance;
413
414impl<V: Scalar> Distance<V> for ManhattanDistance {
415 fn distance<const N: usize>(a: &[V; N], b: &[V; N]) -> V {
416 let mut sum = V::ZERO;
417 for (&x, &y) in a.iter().zip(b) {
418 let difference = x - y;
419 sum += if difference < V::ZERO {
420 V::ZERO - difference
421 } else {
422 difference
423 };
424 }
425 sum
426 }
427}
428
429/// A nearest-class-mean (prototype) classifier to put on top of a frozen
430/// model: head-only adaptation without gradients (C++ `PrototypeHead`).
431///
432/// The head keeps one prototype per class, the running mean of the embeddings
433/// it was shown for that class, and predicts the class whose prototype is
434/// nearest. Learning is one pass with no learning rate and no epochs; a class
435/// can be added at any time; a class never shown is never predicted. RAM:
436/// `CLASSES x IN` values plus one `u16` count per class.
437///
438/// Each [`learn`](Self::learn) moves the prototype by `(input - prototype) /
439/// count`. Once a class's count reaches the cap set by
440/// [`set_maximum_count`](Self::set_maximum_count), the count stops growing and
441/// the prototype becomes an exponential moving average with weight `1 / cap`,
442/// so it keeps tracking a slowly drifting input instead of freezing on old
443/// samples. The default cap, `u16::MAX`, is effectively unlimited.
444///
445/// Class indices of `CLASSES` or more are ignored by the methods that change
446/// the head, and read as an unlearned class.
447pub struct PrototypeHead<V, const IN: usize, const CLASSES: usize, D = SquaredEuclideanDistance> {
448 prototypes: [[V; IN]; CLASSES],
449 counts: [u16; CLASSES],
450 maximum_count: u16,
451 distance: PhantomData<D>,
452}
453
454impl<V: Copy, const IN: usize, const CLASSES: usize, D> Clone for PrototypeHead<V, IN, CLASSES, D> {
455 fn clone(&self) -> Self {
456 *self
457 }
458}
459
460impl<V: Copy, const IN: usize, const CLASSES: usize, D> Copy for PrototypeHead<V, IN, CLASSES, D> {}
461
462impl<V: Scalar, const IN: usize, const CLASSES: usize, D> Default
463 for PrototypeHead<V, IN, CLASSES, D>
464{
465 fn default() -> Self {
466 Self::new()
467 }
468}
469
470impl<V: Scalar, const IN: usize, const CLASSES: usize, D> PrototypeHead<V, IN, CLASSES, D> {
471 /// A head that knows no class, with the cap at `u16::MAX`.
472 pub fn new() -> Self {
473 Self {
474 prototypes: [[V::ZERO; IN]; CLASSES],
475 counts: [0; CLASSES],
476 maximum_count: u16::MAX,
477 distance: PhantomData,
478 }
479 }
480
481 /// Forget every class (the cap is kept).
482 pub fn clear(&mut self) {
483 self.prototypes = [[V::ZERO; IN]; CLASSES];
484 self.counts = [0; CLASSES];
485 }
486
487 /// Forget one class: it is not predicted again until it is learned.
488 pub fn forget(&mut self, class: usize) {
489 if let (Some(p), Some(c)) = (self.prototypes.get_mut(class), self.counts.get_mut(class)) {
490 *p = [V::ZERO; IN];
491 *c = 0;
492 }
493 }
494
495 /// Fold one labelled embedding into its class's prototype.
496 pub fn learn(&mut self, input: &[V; IN], class: usize) {
497 let (Some(prototype), Some(count)) =
498 (self.prototypes.get_mut(class), self.counts.get_mut(class))
499 else {
500 return;
501 };
502 if *count < self.maximum_count {
503 *count += 1;
504 }
505 let n = i32::from(*count);
506 for (p, &x) in prototype.iter_mut().zip(input) {
507 let difference = x - *p;
508 *p += difference.div_int(n);
509 }
510 }
511
512 /// The cap on a class's count (at least 1; 0 is taken as 1). Counts
513 /// above the new cap are lowered to it.
514 pub fn set_maximum_count(&mut self, maximum_count: u16) {
515 self.maximum_count = maximum_count.max(1);
516 for c in &mut self.counts {
517 if *c > self.maximum_count {
518 *c = self.maximum_count;
519 }
520 }
521 }
522
523 /// The cap on a class's count.
524 pub fn maximum_count(&self) -> u16 {
525 self.maximum_count
526 }
527
528 /// How many samples a class's prototype holds (0: not learned).
529 pub fn count(&self, class: usize) -> u16 {
530 self.counts.get(class).copied().unwrap_or(0)
531 }
532
533 /// A class's prototype, or `None` for a class index out of range.
534 pub fn prototype(&self, class: usize) -> Option<&[V; IN]> {
535 self.prototypes.get(class)
536 }
537
538 /// Load one class's prototype, for example a shipped one, with the weight
539 /// it carries against later samples (capped; count 0 forgets the class).
540 pub fn set_prototype(&mut self, class: usize, prototype: &[V; IN], count: u16) {
541 if let (Some(p), Some(c)) = (self.prototypes.get_mut(class), self.counts.get_mut(class)) {
542 *p = *prototype;
543 *c = count.min(self.maximum_count);
544 }
545 }
546}
547
548impl<V: Scalar, const IN: usize, const CLASSES: usize, D: Distance<V>>
549 PrototypeHead<V, IN, CLASSES, D>
550{
551 /// The distance from `input` to a class's prototype, or `None` for a
552 /// class index out of range.
553 pub fn distance(&self, input: &[V; IN], class: usize) -> Option<V> {
554 self.prototypes.get(class).map(|p| D::distance(input, p))
555 }
556
557 /// The learned class whose prototype is nearest (the first one on a tie),
558 /// or `CLASSES` when no class has been learned.
559 pub fn predict(&self, input: &[V; IN]) -> usize {
560 let mut best = CLASSES;
561 let mut best_distance = V::ZERO;
562 for (c, (p, &count)) in self.prototypes.iter().zip(&self.counts).enumerate() {
563 if count == 0 {
564 continue;
565 }
566 let d = D::distance(input, p);
567 if best == CLASSES || d < best_distance {
568 best = c;
569 best_distance = d;
570 }
571 }
572 best
573 }
574}
575
576#[cfg(test)]
577mod tests {
578 use super::*;
579
580 #[test]
581 fn softmax_exp_is_zero_beyond_the_table() {
582 assert_eq!(Q16_16::from_int(-6).softmax_exp(), Q16_16::ZERO);
583 assert_eq!(Q16_16::from_int(-100).softmax_exp(), Q16_16::ZERO);
584 assert!(Q16_16::from_raw(-6 * 65536 + 1).softmax_exp() > Q16_16::ZERO);
585 assert_eq!(Q16_16::ZERO.softmax_exp(), Q16_16::ONE);
586 assert_eq!(Q8_8::from_int(-6).softmax_exp(), Q8_8::ZERO);
587 assert_eq!(Q8_8::ZERO.softmax_exp(), Q8_8::ONE);
588 }
589
590 #[test]
591 fn softmax_of_equal_logits_is_uniform() {
592 let p = SoftmaxCrossEntropyLoss::probabilities(&[Q16_16::from_int(3); 4]);
593 assert_eq!(p, [Q16_16::pow2_neg(2); 4]);
594 }
595
596 #[test]
597 fn a_separated_head_stops_moving() {
598 // Logits 10 apart: the softmax is one-hot, so the deltas are 0.
599 let mut head = DenseHead::<Q16_16, 1, 2>::from_weights(
600 [[Q16_16::ZERO], [Q16_16::ZERO]],
601 [Q16_16::from_int(10), Q16_16::ZERO],
602 );
603 let before = head;
604 head.train_class(&[Q16_16::ONE], 0, Q16_16::ONE, None);
605 assert_eq!(head.biases, before.biases);
606 }
607
608 #[test]
609 fn train_class_out_of_range_trains_toward_zero() {
610 let mut head = DenseHead::<Q16_16, 2, 2, SquaredErrorLoss>::from_weights(
611 [[Q16_16::ONE; 2]; 2],
612 [Q16_16::ZERO; 2],
613 );
614 let input = [Q16_16::ONE; 2];
615 let mut deltas = [Q16_16::ZERO; 2];
616 head.train_class(&input, 7, Q16_16::pow2_neg(3), Some(&mut deltas));
617 // Logits were 2, targets 0: delta -2, backward -2 - 2 = -4.
618 assert_eq!(deltas, [Q16_16::from_int(-4); 2]);
619 assert_eq!(head.biases, [Q16_16::from_raw(-16384); 2]);
620 }
621
622 #[test]
623 fn prototype_head_running_mean_and_cap() {
624 let mut head = PrototypeHead::<Q16_16, 1, 3>::new();
625 assert_eq!(head.predict(&[Q16_16::ZERO]), 3);
626 for v in [1, 2, 3] {
627 head.learn(&[Q16_16::from_int(v)], 1);
628 }
629 assert_eq!(head.prototype(1), Some(&[Q16_16::from_int(2)]));
630 assert_eq!(head.count(1), 3);
631 assert_eq!(head.predict(&[Q16_16::from_int(-50)]), 1);
632
633 head.set_maximum_count(2);
634 assert_eq!(head.count(1), 2);
635 head.learn(&[Q16_16::from_int(4)], 1);
636 assert_eq!(head.prototype(1), Some(&[Q16_16::from_int(3)]));
637
638 head.learn(&[Q16_16::from_int(10)], 7); // ignored
639 head.forget(1);
640 assert_eq!(head.predict(&[Q16_16::ZERO]), 3);
641 assert_eq!(head.distance(&[Q16_16::ZERO], 3), None);
642 }
643
644 #[test]
645 fn manhattan_distance() {
646 let a = [Q16_16::from_int(1), Q16_16::from_int(-2)];
647 let b = [Q16_16::from_int(-1), Q16_16::from_int(1)];
648 assert_eq!(ManhattanDistance::distance(&a, &b), Q16_16::from_int(5));
649 assert_eq!(
650 SquaredEuclideanDistance::distance(&a, &b),
651 Q16_16::from_int(13)
652 );
653 }
654}