neat/
runnable.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use crate::topology::*;

#[cfg(not(feature = "rayon"))]
use std::{cell::RefCell, rc::Rc};

#[cfg(feature = "rayon")]
use rayon::prelude::*;
#[cfg(feature = "rayon")]
use std::sync::{Arc, RwLock};

/// A runnable, stated Neural Network generated from a [NeuralNetworkTopology]. Use [`NeuralNetwork::from`] to go from stateles to runnable.
/// Because this has state, you need to run [`NeuralNetwork::flush_state`] between [`NeuralNetwork::predict`] calls.
#[derive(Debug)]
#[cfg(not(feature = "rayon"))]
pub struct NeuralNetwork<const I: usize, const O: usize> {
    input_layer: [Rc<RefCell<Neuron>>; I],
    hidden_layers: Vec<Rc<RefCell<Neuron>>>,
    output_layer: [Rc<RefCell<Neuron>>; O],
}

/// Parallelized version of the [`NeuralNetwork`] struct.
#[derive(Debug)]
#[cfg(feature = "rayon")]
pub struct NeuralNetwork<const I: usize, const O: usize> {
    input_layer: [Arc<RwLock<Neuron>>; I],
    hidden_layers: Vec<Arc<RwLock<Neuron>>>,
    output_layer: [Arc<RwLock<Neuron>>; O],
}

impl<const I: usize, const O: usize> NeuralNetwork<I, O> {
    /// Predicts an output for the given inputs.
    #[cfg(not(feature = "rayon"))]
    pub fn predict(&self, inputs: [f32; I]) -> [f32; O] {
        for (i, v) in inputs.iter().enumerate() {
            let mut nw = self.input_layer[i].borrow_mut();
            nw.state.value = *v;
            nw.state.processed = true;
        }

        (0..O)
            .map(NeuronLocation::Output)
            .map(|loc| self.process_neuron(loc))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap()
    }

    /// Parallelized prediction of outputs from inputs.
    #[cfg(feature = "rayon")]
    pub fn predict(&self, inputs: [f32; I]) -> [f32; O] {
        inputs.par_iter().enumerate().for_each(|(i, v)| {
            let mut nw = self.input_layer[i].write().unwrap();
            nw.state.value = *v;
            nw.state.processed = true;
        });

        (0..O)
            .map(NeuronLocation::Output)
            .collect::<Vec<_>>()
            .into_par_iter()
            .map(|loc| self.process_neuron(loc))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap()
    }

    #[cfg(not(feature = "rayon"))]
    fn process_neuron(&self, loc: NeuronLocation) -> f32 {
        let n = self.get_neuron(loc);

        {
            let nr = n.borrow();

            if nr.state.processed {
                return nr.state.value;
            }
        }

        let mut n = n.borrow_mut();

        for (l, w) in n.inputs.clone() {
            n.state.value += self.process_neuron(l) * w;
        }

        n.activate();

        n.state.value
    }

    #[cfg(feature = "rayon")]
    fn process_neuron(&self, loc: NeuronLocation) -> f32 {
        let n = self.get_neuron(loc);

        {
            let nr = n.read().unwrap();

            if nr.state.processed {
                return nr.state.value;
            }
        }

        let val: f32 = n
            .read()
            .unwrap()
            .inputs
            .par_iter()
            .map(|&(n2, w)| {
                let processed = self.process_neuron(n2);
                processed * w
            })
            .sum();

        let mut nw = n.write().unwrap();
        nw.state.value += val;
        nw.activate();

        nw.state.value
    }

    #[cfg(not(feature = "rayon"))]
    fn get_neuron(&self, loc: NeuronLocation) -> Rc<RefCell<Neuron>> {
        match loc {
            NeuronLocation::Input(i) => self.input_layer[i].clone(),
            NeuronLocation::Hidden(i) => self.hidden_layers[i].clone(),
            NeuronLocation::Output(i) => self.output_layer[i].clone(),
        }
    }

    #[cfg(feature = "rayon")]
    fn get_neuron(&self, loc: NeuronLocation) -> Arc<RwLock<Neuron>> {
        match loc {
            NeuronLocation::Input(i) => self.input_layer[i].clone(),
            NeuronLocation::Hidden(i) => self.hidden_layers[i].clone(),
            NeuronLocation::Output(i) => self.output_layer[i].clone(),
        }
    }

    /// Flushes the network's state after a [prediction][NeuralNetwork::predict].
    #[cfg(not(feature = "rayon"))]
    pub fn flush_state(&self) {
        for n in &self.input_layer {
            n.borrow_mut().flush_state();
        }

        for n in &self.hidden_layers {
            n.borrow_mut().flush_state();
        }

        for n in &self.output_layer {
            n.borrow_mut().flush_state();
        }
    }

    /// Flushes the neural network's state.
    #[cfg(feature = "rayon")]
    pub fn flush_state(&self) {
        self.input_layer
            .par_iter()
            .for_each(|n| n.write().unwrap().flush_state());

        self.hidden_layers
            .par_iter()
            .for_each(|n| n.write().unwrap().flush_state());

        self.output_layer
            .par_iter()
            .for_each(|n| n.write().unwrap().flush_state());
    }
}

impl<const I: usize, const O: usize> From<&NeuralNetworkTopology<I, O>> for NeuralNetwork<I, O> {
    #[cfg(not(feature = "rayon"))]
    fn from(value: &NeuralNetworkTopology<I, O>) -> Self {
        let input_layer = value
            .input_layer
            .iter()
            .map(|n| Rc::new(RefCell::new(Neuron::from(&n.read().unwrap().clone()))))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        let hidden_layers = value
            .hidden_layers
            .iter()
            .map(|n| Rc::new(RefCell::new(Neuron::from(&n.read().unwrap().clone()))))
            .collect();

        let output_layer = value
            .output_layer
            .iter()
            .map(|n| Rc::new(RefCell::new(Neuron::from(&n.read().unwrap().clone()))))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        Self {
            input_layer,
            hidden_layers,
            output_layer,
        }
    }

    #[cfg(feature = "rayon")]
    fn from(value: &NeuralNetworkTopology<I, O>) -> Self {
        let input_layer = value
            .input_layer
            .iter()
            .map(|n| Arc::new(RwLock::new(Neuron::from(&n.read().unwrap().clone()))))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        let hidden_layers = value
            .hidden_layers
            .iter()
            .map(|n| Arc::new(RwLock::new(Neuron::from(&n.read().unwrap().clone()))))
            .collect();

        let output_layer = value
            .output_layer
            .iter()
            .map(|n| Arc::new(RwLock::new(Neuron::from(&n.read().unwrap().clone()))))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        Self {
            input_layer,
            hidden_layers,
            output_layer,
        }
    }
}

/// A state-filled neuron.
#[derive(Clone, Debug)]
pub struct Neuron {
    inputs: Vec<(NeuronLocation, f32)>,
    bias: f32,

    /// The current state of the neuron.
    pub state: NeuronState,

    /// The neuron's activation function
    pub activation: ActivationFn,
}

impl Neuron {
    /// Flushes a neuron's state. Called by [`NeuralNetwork::flush_state`]
    pub fn flush_state(&mut self) {
        self.state.value = self.bias;
    }

    /// Applies the activation function to the neuron
    pub fn activate(&mut self) {
        self.state.value = self.activation.func.activate(self.state.value);
    }
}

impl From<&NeuronTopology> for Neuron {
    fn from(value: &NeuronTopology) -> Self {
        Self {
            inputs: value.inputs.clone(),
            bias: value.bias,
            state: NeuronState {
                value: value.bias,
                ..Default::default()
            },
            activation: value.activation.clone(),
        }
    }
}

/// A state used in [`Neuron`]s for cache.
#[derive(Clone, Debug, Default)]
pub struct NeuronState {
    /// The current value of the neuron. Initialized to a neuron's bias when flushed.
    pub value: f32,

    /// Whether or not [`value`][NeuronState::value] has finished processing.
    pub processed: bool,
}

/// A blanket trait for iterators meant to help with interpreting the output of a [`NeuralNetwork`]
#[cfg(feature = "max-index")]
pub trait MaxIndex<T: PartialOrd> {
    /// Retrieves the index of the max value.
    fn max_index(self) -> usize;
}

#[cfg(feature = "max-index")]
impl<I: Iterator<Item = T>, T: PartialOrd> MaxIndex<T> for I {
    // slow and lazy implementation but it works (will prob optimize in the future)
    fn max_index(self) -> usize {
        self.enumerate()
            .max_by(|(_, v), (_, v2)| v.partial_cmp(v2).unwrap())
            .unwrap()
            .0
    }
}