use core::marker::PhantomData;
use crate::activation::lookup;
use crate::lut::{EXP_Q8_8, EXP_Q16_16};
use crate::neuralnet::argmax;
use crate::qformat::{Q8_8, Q16_16, Scalar};
pub trait SoftmaxExp: Scalar {
fn softmax_exp(self) -> Self;
}
impl SoftmaxExp for Q16_16 {
fn softmax_exp(self) -> Self {
if self <= Q16_16::from_int(-6) {
Q16_16::ZERO
} else {
lookup(self, &EXP_Q16_16)
}
}
}
impl SoftmaxExp for Q8_8 {
fn softmax_exp(self) -> Self {
if self <= Q8_8::from_int(-6) {
Q8_8::ZERO
} else {
lookup(self, &EXP_Q8_8)
}
}
}
#[cfg(feature = "std")]
impl SoftmaxExp for f32 {
fn softmax_exp(self) -> Self {
self.exp()
}
}
#[cfg(feature = "std")]
impl SoftmaxExp for f64 {
fn softmax_exp(self) -> Self {
self.exp()
}
}
#[cfg(all(feature = "libm", not(feature = "std")))]
impl SoftmaxExp for f32 {
fn softmax_exp(self) -> Self {
libm::expf(self)
}
}
#[cfg(all(feature = "libm", not(feature = "std")))]
impl SoftmaxExp for f64 {
fn softmax_exp(self) -> Self {
libm::exp(self)
}
}
pub trait HeadLoss<V> {
fn output_deltas<const N: usize>(logits: &[V; N], targets: &[V; N]) -> [V; N];
}
pub struct SoftmaxCrossEntropyLoss;
impl SoftmaxCrossEntropyLoss {
pub fn probabilities<V: SoftmaxExp, const N: usize>(logits: &[V; N]) -> [V; N] {
let mut largest = match logits.first() {
Some(&first) => first,
None => return *logits,
};
for &z in logits.iter().skip(1) {
if z > largest {
largest = z;
}
}
let mut probabilities = [V::ZERO; N];
let mut sum = V::ZERO;
for (p, &z) in probabilities.iter_mut().zip(logits) {
*p = (z - largest).softmax_exp();
sum += *p;
}
if sum != V::ZERO {
for p in &mut probabilities {
*p = *p / sum;
}
}
probabilities
}
}
impl<V: SoftmaxExp> HeadLoss<V> for SoftmaxCrossEntropyLoss {
fn output_deltas<const N: usize>(logits: &[V; N], targets: &[V; N]) -> [V; N] {
let mut deltas = Self::probabilities(logits);
for (d, &t) in deltas.iter_mut().zip(targets) {
*d = t - *d;
}
deltas
}
}
pub struct SquaredErrorLoss;
impl<V: Scalar> HeadLoss<V> for SquaredErrorLoss {
fn output_deltas<const N: usize>(logits: &[V; N], targets: &[V; N]) -> [V; N] {
let mut deltas = *targets;
for (d, &z) in deltas.iter_mut().zip(logits) {
*d = *d - z;
}
deltas
}
}
pub struct DenseHead<V, const IN: usize, const OUT: usize, L = SoftmaxCrossEntropyLoss> {
pub weights: [[V; IN]; OUT],
pub biases: [V; OUT],
loss: PhantomData<L>,
}
impl<V: Copy, const IN: usize, const OUT: usize, L> Clone for DenseHead<V, IN, OUT, L> {
fn clone(&self) -> Self {
*self
}
}
impl<V: Copy, const IN: usize, const OUT: usize, L> Copy for DenseHead<V, IN, OUT, L> {}
impl<V: Scalar, const IN: usize, const OUT: usize, L> Default for DenseHead<V, IN, OUT, L> {
fn default() -> Self {
Self::new()
}
}
impl<V, const IN: usize, const OUT: usize, L> DenseHead<V, IN, OUT, L> {
pub const fn from_weights(weights: [[V; IN]; OUT], biases: [V; OUT]) -> Self {
Self {
weights,
biases,
loss: PhantomData,
}
}
}
impl<V: Scalar, const IN: usize, const OUT: usize, L> DenseHead<V, IN, OUT, L> {
pub fn new() -> Self {
Self::from_weights([[V::ZERO; IN]; OUT], [V::ZERO; OUT])
}
pub fn clear(&mut self) {
*self = Self::new();
}
pub fn initialize_weights(&mut self, mut random_weight: impl FnMut() -> V) {
for row in &mut self.weights {
for w in row {
*w = random_weight();
}
}
self.biases = [V::ZERO; OUT];
}
pub fn load_weights(&mut self, weights: &[[V; IN]; OUT], biases: &[V; OUT]) {
self.weights = *weights;
self.biases = *biases;
}
pub fn forward(&self, input: &[V; IN]) -> [V; OUT] {
let mut logits = self.biases;
for (z, row) in logits.iter_mut().zip(&self.weights) {
let mut sum = *z;
for (&w, &x) in row.iter().zip(input) {
sum += w * x;
}
*z = sum;
}
logits
}
pub fn predict(&self, input: &[V; IN]) -> usize {
argmax(&self.forward(input))
}
pub fn backward(&self, output_deltas: &[V; OUT]) -> [V; IN] {
let mut input_deltas = [V::ZERO; IN];
for (row, &delta) in self.weights.iter().zip(output_deltas) {
for (d, &w) in input_deltas.iter_mut().zip(row) {
*d += w * delta;
}
}
input_deltas
}
pub fn update(&mut self, output_deltas: &[V; OUT], input: &[V; IN], learning_rate: V) {
for ((row, b), &delta) in self
.weights
.iter_mut()
.zip(&mut self.biases)
.zip(output_deltas)
{
update_row(row, input, delta, learning_rate);
*b += learning_rate.mul_round_nearest(delta);
}
}
}
impl<V: Scalar, const IN: usize, const OUT: usize, L: HeadLoss<V>> DenseHead<V, IN, OUT, L> {
pub fn output_deltas(&self, logits: &[V; OUT], targets: &[V; OUT]) -> [V; OUT] {
L::output_deltas(logits, targets)
}
pub fn train(
&mut self,
input: &[V; IN],
targets: &[V; OUT],
learning_rate: V,
input_deltas: Option<&mut [V; IN]>,
) -> usize {
let logits = self.forward(input);
let predicted = argmax(&logits);
let deltas = L::output_deltas(&logits, targets);
if let Some(input_deltas) = input_deltas {
*input_deltas = self.backward(&deltas);
}
self.update(&deltas, input, learning_rate);
predicted
}
pub fn train_class(
&mut self,
input: &[V; IN],
class: usize,
learning_rate: V,
input_deltas: Option<&mut [V; IN]>,
) -> usize {
let targets = core::array::from_fn(|o| if o == class { V::ONE } else { V::ZERO });
self.train(input, &targets, learning_rate, input_deltas)
}
}
#[inline(never)]
fn update_row<V: Scalar, const IN: usize>(
row: &mut [V; IN],
input: &[V; IN],
delta: V,
learning_rate: V,
) {
for (w, &x) in row.iter_mut().zip(input) {
*w += learning_rate.mul_round_nearest(delta * x);
}
}
pub trait Distance<V> {
fn distance<const N: usize>(a: &[V; N], b: &[V; N]) -> V;
}
pub struct SquaredEuclideanDistance;
impl<V: Scalar> Distance<V> for SquaredEuclideanDistance {
fn distance<const N: usize>(a: &[V; N], b: &[V; N]) -> V {
let mut sum = V::ZERO;
for (&x, &y) in a.iter().zip(b) {
let difference = x - y;
sum += difference * difference;
}
sum
}
}
pub struct ManhattanDistance;
impl<V: Scalar> Distance<V> for ManhattanDistance {
fn distance<const N: usize>(a: &[V; N], b: &[V; N]) -> V {
let mut sum = V::ZERO;
for (&x, &y) in a.iter().zip(b) {
let difference = x - y;
sum += if difference < V::ZERO {
V::ZERO - difference
} else {
difference
};
}
sum
}
}
pub struct PrototypeHead<V, const IN: usize, const CLASSES: usize, D = SquaredEuclideanDistance> {
prototypes: [[V; IN]; CLASSES],
counts: [u16; CLASSES],
maximum_count: u16,
distance: PhantomData<D>,
}
impl<V: Copy, const IN: usize, const CLASSES: usize, D> Clone for PrototypeHead<V, IN, CLASSES, D> {
fn clone(&self) -> Self {
*self
}
}
impl<V: Copy, const IN: usize, const CLASSES: usize, D> Copy for PrototypeHead<V, IN, CLASSES, D> {}
impl<V: Scalar, const IN: usize, const CLASSES: usize, D> Default
for PrototypeHead<V, IN, CLASSES, D>
{
fn default() -> Self {
Self::new()
}
}
impl<V: Scalar, const IN: usize, const CLASSES: usize, D> PrototypeHead<V, IN, CLASSES, D> {
pub fn new() -> Self {
Self {
prototypes: [[V::ZERO; IN]; CLASSES],
counts: [0; CLASSES],
maximum_count: u16::MAX,
distance: PhantomData,
}
}
pub fn clear(&mut self) {
self.prototypes = [[V::ZERO; IN]; CLASSES];
self.counts = [0; CLASSES];
}
pub fn forget(&mut self, class: usize) {
if let (Some(p), Some(c)) = (self.prototypes.get_mut(class), self.counts.get_mut(class)) {
*p = [V::ZERO; IN];
*c = 0;
}
}
pub fn learn(&mut self, input: &[V; IN], class: usize) {
let (Some(prototype), Some(count)) =
(self.prototypes.get_mut(class), self.counts.get_mut(class))
else {
return;
};
if *count < self.maximum_count {
*count += 1;
}
let n = i32::from(*count);
for (p, &x) in prototype.iter_mut().zip(input) {
let difference = x - *p;
*p += difference.div_int(n);
}
}
pub fn set_maximum_count(&mut self, maximum_count: u16) {
self.maximum_count = maximum_count.max(1);
for c in &mut self.counts {
if *c > self.maximum_count {
*c = self.maximum_count;
}
}
}
pub fn maximum_count(&self) -> u16 {
self.maximum_count
}
pub fn count(&self, class: usize) -> u16 {
self.counts.get(class).copied().unwrap_or(0)
}
pub fn prototype(&self, class: usize) -> Option<&[V; IN]> {
self.prototypes.get(class)
}
pub fn set_prototype(&mut self, class: usize, prototype: &[V; IN], count: u16) {
if let (Some(p), Some(c)) = (self.prototypes.get_mut(class), self.counts.get_mut(class)) {
*p = *prototype;
*c = count.min(self.maximum_count);
}
}
}
impl<V: Scalar, const IN: usize, const CLASSES: usize, D: Distance<V>>
PrototypeHead<V, IN, CLASSES, D>
{
pub fn distance(&self, input: &[V; IN], class: usize) -> Option<V> {
self.prototypes.get(class).map(|p| D::distance(input, p))
}
pub fn predict(&self, input: &[V; IN]) -> usize {
let mut best = CLASSES;
let mut best_distance = V::ZERO;
for (c, (p, &count)) in self.prototypes.iter().zip(&self.counts).enumerate() {
if count == 0 {
continue;
}
let d = D::distance(input, p);
if best == CLASSES || d < best_distance {
best = c;
best_distance = d;
}
}
best
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn softmax_exp_is_zero_beyond_the_table() {
assert_eq!(Q16_16::from_int(-6).softmax_exp(), Q16_16::ZERO);
assert_eq!(Q16_16::from_int(-100).softmax_exp(), Q16_16::ZERO);
assert!(Q16_16::from_raw(-6 * 65536 + 1).softmax_exp() > Q16_16::ZERO);
assert_eq!(Q16_16::ZERO.softmax_exp(), Q16_16::ONE);
assert_eq!(Q8_8::from_int(-6).softmax_exp(), Q8_8::ZERO);
assert_eq!(Q8_8::ZERO.softmax_exp(), Q8_8::ONE);
}
#[test]
fn softmax_of_equal_logits_is_uniform() {
let p = SoftmaxCrossEntropyLoss::probabilities(&[Q16_16::from_int(3); 4]);
assert_eq!(p, [Q16_16::pow2_neg(2); 4]);
}
#[test]
fn a_separated_head_stops_moving() {
let mut head = DenseHead::<Q16_16, 1, 2>::from_weights(
[[Q16_16::ZERO], [Q16_16::ZERO]],
[Q16_16::from_int(10), Q16_16::ZERO],
);
let before = head;
head.train_class(&[Q16_16::ONE], 0, Q16_16::ONE, None);
assert_eq!(head.biases, before.biases);
}
#[test]
fn train_class_out_of_range_trains_toward_zero() {
let mut head = DenseHead::<Q16_16, 2, 2, SquaredErrorLoss>::from_weights(
[[Q16_16::ONE; 2]; 2],
[Q16_16::ZERO; 2],
);
let input = [Q16_16::ONE; 2];
let mut deltas = [Q16_16::ZERO; 2];
head.train_class(&input, 7, Q16_16::pow2_neg(3), Some(&mut deltas));
assert_eq!(deltas, [Q16_16::from_int(-4); 2]);
assert_eq!(head.biases, [Q16_16::from_raw(-16384); 2]);
}
#[test]
fn prototype_head_running_mean_and_cap() {
let mut head = PrototypeHead::<Q16_16, 1, 3>::new();
assert_eq!(head.predict(&[Q16_16::ZERO]), 3);
for v in [1, 2, 3] {
head.learn(&[Q16_16::from_int(v)], 1);
}
assert_eq!(head.prototype(1), Some(&[Q16_16::from_int(2)]));
assert_eq!(head.count(1), 3);
assert_eq!(head.predict(&[Q16_16::from_int(-50)]), 1);
head.set_maximum_count(2);
assert_eq!(head.count(1), 2);
head.learn(&[Q16_16::from_int(4)], 1);
assert_eq!(head.prototype(1), Some(&[Q16_16::from_int(3)]));
head.learn(&[Q16_16::from_int(10)], 7); head.forget(1);
assert_eq!(head.predict(&[Q16_16::ZERO]), 3);
assert_eq!(head.distance(&[Q16_16::ZERO], 3), None);
}
#[test]
fn manhattan_distance() {
let a = [Q16_16::from_int(1), Q16_16::from_int(-2)];
let b = [Q16_16::from_int(-1), Q16_16::from_int(1)];
assert_eq!(ManhattanDistance::distance(&a, &b), Q16_16::from_int(5));
assert_eq!(
SquaredEuclideanDistance::distance(&a, &b),
Q16_16::from_int(13)
);
}
}