1use 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
21pub trait Activation<V> {
23 fn activate(x: V) -> V;
25 fn derivative(y: V) -> V;
28}
29
30pub struct Relu;
32
33pub struct Linear;
36
37pub struct Tanh;
40
41pub 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 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 fn derivative(_y: V) -> V {
64 V::ONE
65 }
66}
67
68macro_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#[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
133const 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
139pub(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
168pub(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 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
213fn 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 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 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 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); }
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 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}