Skip to main content

tinymind/
activation.rs

1//! Activation policies, ported from tinymind (C++) `cpp/activationFunctions.hpp`,
2//! `cpp/lookupTable.hpp` and `cpp/interpolate.hpp`.
3//!
4//! C++ policy classes with static member functions become zero-sized Rust types
5//! implementing a trait. `Relu` and `Linear` need no table and work for every
6//! value type.
7//! `Tanh` and `Sigmoid` are implemented for the formats that have lookup
8//! tables (`Q16_16`, `Q8_8`): asking for `Tanh` on another format is a compile
9//! error, as it is in C++ when the matching `TINYMIND_USE_TANH_x_y` table is not
10//! compiled in. For `f32` and `f64` they compute `tanh(x)` and `1 / (1 +
11//! exp(-x))`, as tinymind (C++)'s floating-point activations do, with the `std`
12//! feature (the platform's math library, glibc on a Linux host, which the C++
13//! uses too: the results are bit-identical there) or the `libm` feature (the
14//! `libm` crate, for `no_std`: within a few ulps of glibc, not bit-identical).
15
16use crate::lut::{
17    NUMBER_OF_ACTIVATION_TABLE_VALUES, SIGMOID_Q8_8, SIGMOID_Q16_16, TANH_Q8_8, TANH_Q16_16,
18};
19use crate::qformat::{Q8_8, Q16_16, QValue, Scalar};
20
21/// A neuron activation function and its derivative.
22pub trait Activation<V> {
23    /// The activation of the weighted input sum `x`.
24    fn activate(x: V) -> V;
25    /// Derivative expressed in terms of the activation's *output* `y`, the way
26    /// tinymind (C++) computes it during back-propagation.
27    fn derivative(y: V) -> V;
28}
29
30/// Rectified linear unit, `max(0, x)` (C++ `ReluActivationPolicy`).
31pub struct Relu;
32
33/// The identity, for a regression output layer (C++ `LinearActivationPolicy`).
34/// Its gradient is unbounded; see `set_gradient_clip` on the networks.
35pub struct Linear;
36
37/// Hyperbolic tangent: the 96-entry lookup table for the Q formats, `tanh` for
38/// `f32` and `f64` (feature `std` or `libm`).
39pub struct Tanh;
40
41/// Logistic sigmoid: the 96-entry lookup table for the Q formats, `1 / (1 +
42/// exp(-x))` for `f32` and `f64` (feature `std` or `libm`).
43pub struct Sigmoid;
44
45impl<V: Scalar> Activation<V> for Relu {
46    fn activate(x: V) -> V {
47        if x <= V::ZERO { V::ZERO } else { x }
48    }
49
50    /// 1 where the neuron is active, else 0. The output is positive exactly when
51    /// the input was, so deciding from the output gives the C++ result.
52    fn derivative(y: V) -> V {
53        if y <= V::ZERO { V::ZERO } else { V::ONE }
54    }
55}
56
57impl<V: Scalar> Activation<V> for Linear {
58    fn activate(x: V) -> V {
59        x
60    }
61
62    /// Always 1.0 (the C++ returns `Constants<ValueType>::one()`, a real 1.0).
63    fn derivative(_y: V) -> V {
64        V::ONE
65    }
66}
67
68/// `Tanh` and `Sigmoid` for one format, given its two tables.
69macro_rules! impl_table_activations {
70    ($v:ty, $tanh:expr, $sigmoid:expr) => {
71        impl Activation<$v> for Tanh {
72            fn activate(x: $v) -> $v {
73                lookup(x, &$tanh)
74            }
75
76            fn derivative(y: $v) -> $v {
77                <$v>::ONE - (y * y)
78            }
79        }
80
81        impl Activation<$v> for Sigmoid {
82            fn activate(x: $v) -> $v {
83                lookup(x, &$sigmoid)
84            }
85
86            fn derivative(y: $v) -> $v {
87                y * (<$v>::ONE - y)
88            }
89        }
90    };
91}
92
93impl_table_activations!(Q16_16, TANH_Q16_16, SIGMOID_Q16_16);
94impl_table_activations!(Q8_8, TANH_Q8_8, SIGMOID_Q8_8);
95
96/// `Tanh` and `Sigmoid` for a float type, as tinymind (C++)'s floating-point
97/// activation policies write them: `tanh(x)` and `1 / (1 + exp(-x))`, with the
98/// derivatives taken from the output, `1 - y * y` and `y * (1 - y)`.
99#[cfg(any(feature = "std", feature = "libm"))]
100macro_rules! impl_float_activations {
101    ($t:ty, $tanh:path, $exp:path) => {
102        impl Activation<$t> for Tanh {
103            fn activate(x: $t) -> $t {
104                $tanh(x)
105            }
106
107            fn derivative(y: $t) -> $t {
108                1.0 - (y * y)
109            }
110        }
111
112        impl Activation<$t> for Sigmoid {
113            fn activate(x: $t) -> $t {
114                1.0 / (1.0 + $exp(-x))
115            }
116
117            fn derivative(y: $t) -> $t {
118                y * (1.0 - y)
119            }
120        }
121    };
122}
123
124#[cfg(feature = "std")]
125impl_float_activations!(f32, f32::tanh, f32::exp);
126#[cfg(feature = "std")]
127impl_float_activations!(f64, f64::tanh, f64::exp);
128#[cfg(all(feature = "libm", not(feature = "std")))]
129impl_float_activations!(f32, libm::tanhf, libm::expf);
130#[cfg(all(feature = "libm", not(feature = "std")))]
131impl_float_activations!(f64, libm::tanh, libm::exp);
132
133/// Table domain is [-6, 6] with knots 1/8 apart (`cpp/activation.hpp`).
134const MIN_X_TABLE_VALUE: i32 = -6;
135const MAX_X_TABLE_VALUE: i32 = 6;
136const ACTIVATION_DELTA_SHIFT: u32 = 3;
137const MAX_ACTIVATION_INDEX: usize = NUMBER_OF_ACTIVATION_TABLE_VALUES - 1;
138
139/// What [`lookup`] needs from a format beyond [`Scalar`]: its raw value widened
140/// to `i32` (exact for both storage types; every intermediate stays far inside
141/// `i32`), and the reverse for values known to fit.
142pub(crate) trait TableFormat: Scalar {
143    const FRAC: u32;
144    fn raw_i32(self) -> i32;
145    fn from_raw_i32(raw: i32) -> Self;
146}
147
148impl<const FRAC: u32> TableFormat for QValue<i32, FRAC> {
149    const FRAC: u32 = FRAC;
150    fn raw_i32(self) -> i32 {
151        self.raw()
152    }
153    fn from_raw_i32(raw: i32) -> Self {
154        Self::from_raw(raw)
155    }
156}
157
158impl<const FRAC: u32> TableFormat for QValue<i16, FRAC> {
159    const FRAC: u32 = FRAC;
160    fn raw_i32(self) -> i32 {
161        i32::from(self.raw())
162    }
163    fn from_raw_i32(raw: i32) -> Self {
164        Self::from_raw(raw as i16)
165    }
166}
167
168/// Piecewise-linear table lookup (C++ `LookupTable::getValue`). Table entries
169/// are the unsigned bit patterns of the raw values (`uint16_t`/`uint32_t` in
170/// C++); the cast through `i32` and back to the storage type reinterprets them.
171pub(crate) fn lookup<V: TableFormat, T: Copy + Into<u32>>(
172    x: V,
173    table: &[T; NUMBER_OF_ACTIVATION_TABLE_VALUES],
174) -> V {
175    let entry = |i: usize| V::from_raw_i32(table[i].into() as i32);
176
177    let min_x = MIN_X_TABLE_VALUE << V::FRAC;
178    let max_x = MAX_X_TABLE_VALUE << V::FRAC;
179    let delta_x = 1i32 << (V::FRAC - ACTIVATION_DELTA_SHIFT);
180    let v = x.raw_i32();
181
182    if v <= min_x {
183        return entry(0);
184    }
185    if v >= max_x {
186        return entry(MAX_ACTIVATION_INDEX);
187    }
188
189    let lower = ((v - min_x) / delta_x) as usize;
190    if lower >= MAX_ACTIVATION_INDEX {
191        return entry(MAX_ACTIVATION_INDEX);
192    }
193    let upper = lower + 1;
194    let lower_x = min_x + (lower as i32) * delta_x;
195    let upper_x = min_x + (upper as i32) * delta_x;
196
197    if table[lower].into() == table[upper].into() {
198        entry(upper)
199    } else if v == lower_x {
200        // x sits on a knot: the table value is exact.
201        entry(lower)
202    } else {
203        linear_interpolation(
204            x,
205            V::from_raw_i32(lower_x),
206            V::from_raw_i32(upper_x),
207            entry(lower),
208            entry(upper),
209        )
210    }
211}
212
213/// C++ `linearInterpolation`: `y0 + (y1 - y0) * ((x - x0) / (x1 - x0))`, in
214/// fixed point, with the same operation order (it matters for truncation).
215fn linear_interpolation<V: Scalar>(x: V, x0: V, x1: V, y0: V, y1: V) -> V {
216    if x1 == x0 {
217        return y0;
218    }
219    y0 + ((y1 - y0) * ((x - x0) / (x1 - x0)))
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn knots_and_clamps() {
228        assert_eq!(Tanh::activate(Q16_16::ZERO).raw(), 0);
229        assert_eq!(
230            Sigmoid::activate(Q16_16::from_int(-100)).raw(),
231            SIGMOID_Q16_16[0] as i32
232        );
233        assert_eq!(
234            Sigmoid::activate(Q16_16::from_int(100)).raw(),
235            SIGMOID_Q16_16[MAX_ACTIVATION_INDEX] as i32
236        );
237        // sigmoid(0) is the knot at index 48 (= 6 / (1/8)).
238        assert_eq!(
239            Sigmoid::activate(Q16_16::ZERO).raw(),
240            SIGMOID_Q16_16[48] as i32
241        );
242    }
243
244    #[test]
245    fn interpolates_between_knots() {
246        // Halfway between the knots at 0 and 1/8.
247        let x = Q16_16::from_raw(4096);
248        let y0 = TANH_Q16_16[48] as i32;
249        let y1 = TANH_Q16_16[49] as i32;
250        let got = Tanh::activate(x).raw();
251        assert!(got > y0 && got < y1);
252    }
253
254    #[test]
255    fn q8_8_knots_and_clamps() {
256        // A Q8.8 table entry's u16 bit pattern is the i16 raw value.
257        assert_eq!(Tanh::activate(Q8_8::ZERO).raw(), TANH_Q8_8[48] as i16);
258        assert_eq!(
259            Tanh::activate(Q8_8::from_int(-100)).raw(),
260            TANH_Q8_8[0] as i16
261        );
262        assert_eq!(TANH_Q8_8[0] as i16, -255);
263        assert_eq!(
264            Sigmoid::activate(Q8_8::from_int(100)).raw(),
265            SIGMOID_Q8_8[MAX_ACTIVATION_INDEX] as i16
266        );
267        assert_eq!(Sigmoid::activate(Q8_8::ZERO).raw(), 128); // 0.5
268    }
269
270    #[test]
271    fn relu() {
272        for (x, y, dy) in [(-3, 0, 0), (0, 0, 0), (1, 1, 1), (5, 5, 1)] {
273            let x16 = Q16_16::from_int(x);
274            assert_eq!(Relu::activate(x16), Q16_16::from_int(y));
275            assert_eq!(Relu::derivative(Relu::activate(x16)), Q16_16::from_int(dy));
276            let x8 = Q8_8::from_int(x);
277            assert_eq!(Relu::activate(x8), Q8_8::from_int(y));
278            assert_eq!(Relu::derivative(Relu::activate(x8)), Q8_8::from_int(dy));
279        }
280        // The smallest positive value passes through.
281        assert_eq!(Relu::activate(Q16_16::from_raw(1)).raw(), 1);
282        assert_eq!(Relu::activate(Q16_16::from_raw(-1)).raw(), 0);
283    }
284}