scirs2-neural 0.3.3

Neural network building blocks module for SciRS2 (scirs2-neural) - Minimal Version
Documentation
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Sequential model implementation
//!
//! This module provides a sequential model implementation that chains
//! layers together in a linear sequence.

use crate::error::{NeuralError, Result};
use crate::layers::{Layer, ParamLayer};
use crate::losses::Loss;
use crate::models::{History, Model, TrainingConfig};
use crate::optimizers::Optimizer;
use scirs2_core::ndarray::{Array, ScalarOperand};
use scirs2_core::numeric::{Float, FromPrimitive, NumAssign};
use std::fmt::{Debug, Display};
/// A sequential model that chains layers together in a linear sequence
pub struct Sequential<F: Float + Debug + ScalarOperand + NumAssign + 'static> {
    layers: Vec<Box<dyn Layer<F> + Send + Sync>>,
    layer_outputs: Vec<Array<F, scirs2_core::ndarray::IxDyn>>,
    input: Option<Array<F, scirs2_core::ndarray::IxDyn>>,
    history: History<F>,
}
impl<F: Float + Debug + ScalarOperand + FromPrimitive + Display + NumAssign + 'static> Default
    for Sequential<F>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + Display + NumAssign + 'static> Clone
    for Sequential<F>
{
    fn clone(&self) -> Self {
        // Note: We can't clone the layer trait objects directly
        // This creates a new empty model - the Clone trait is mainly for testing
        Sequential {
            layers: Vec::new(), // Cannot clone trait objects
            layer_outputs: Vec::new(),
            input: None,
            history: History::default(),
        }
    }
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + Display + NumAssign + 'static>
    Sequential<F>
{
    /// Create a new empty sequential model
    pub fn new() -> Self {
        Self {
            layers: Vec::new(),
            layer_outputs: Vec::new(),
            input: None,
            history: History::default(),
        }
    }

    /// Create a new sequential model from existing layers
    pub fn from_layers(layers: Vec<Box<dyn Layer<F> + Send + Sync>>) -> Self {
        Self {
            layers,
            layer_outputs: Vec::new(),
            input: None,
            history: History::default(),
        }
    }

    /// Add a layer to the model
    pub fn add_layer<L: Layer<F> + 'static + Send + Sync>(&mut self, layer: L) -> &mut Self {
        self.layers.push(Box::new(layer));
        self
    }

    /// Get the number of layers in the model
    pub fn num_layers(&self) -> usize {
        self.layers.len()
    }

    /// Get the layers in the model
    pub fn layers(&self) -> &[Box<dyn Layer<F> + Send + Sync>] {
        &self.layers
    }

    /// Get a mutable reference to the layers in the model
    pub fn layers_mut(&mut self) -> &mut Vec<Box<dyn Layer<F> + Send + Sync>> {
        &mut self.layers
    }

    /// Get the training history
    pub fn training_history(&self) -> &History<F> {
        &self.history
    }

    /// Get a mutable reference to the training history
    pub fn training_history_mut(&mut self) -> &mut History<F> {
        &mut self.history
    }
    /// Predict on batched input data
    pub fn predict_batched(
        &self,
        inputs: &Array<F, scirs2_core::ndarray::IxDyn>,
        batch_size: usize,
    ) -> Result<Array<F, scirs2_core::ndarray::IxDyn>> {
        let inputshape = inputs.shape();
        let num_samples = inputshape[0];
        let mut outputs = Vec::new();
        for i in (0..num_samples).step_by(batch_size) {
            let end_idx = std::cmp::min(i + batch_size, num_samples);
            let batch = inputs
                .slice(scirs2_core::ndarray::s![i..end_idx, ..])
                .to_owned()
                .into_dyn();
            let batch_output = self.forward(&batch)?;
            outputs.push(batch_output);
        }

        // Concatenate all batch outputs
        if outputs.len() == 1 {
            Ok(outputs.into_iter().next().expect("Operation failed"))
        } else {
            // For multiple batches, concatenate along the first axis
            let mut concatenated = outputs[0].clone();
            for output in outputs.into_iter().skip(1) {
                concatenated = scirs2_core::ndarray::concatenate![
                    scirs2_core::ndarray::Axis(0),
                    concatenated,
                    output
                ];
            }
            Ok(concatenated)
        }
    }

    /// Fit the model to training data
    pub fn fit(
        &mut self,
        x_train: &Array<F, scirs2_core::ndarray::IxDyn>,
        y_train: &Array<F, scirs2_core::ndarray::IxDyn>,
        config: &TrainingConfig,
        loss_fn: &dyn Loss<F>,
        optimizer: &mut dyn Optimizer<F>,
    ) -> Result<()> {
        let num_samples = x_train.shape()[0];
        let val_split_idx = if config.validation_split > 0.0 {
            ((1.0 - config.validation_split) * num_samples as f64) as usize
        } else {
            num_samples
        };
        // Split data into training and validation sets
        let (x_train_split, x_val) = if config.validation_split > 0.0 {
            let x_train_split = x_train
                .slice(scirs2_core::ndarray::s![0..val_split_idx, ..])
                .to_owned()
                .into_dyn();
            let x_val = x_train
                .slice(scirs2_core::ndarray::s![val_split_idx.., ..])
                .to_owned()
                .into_dyn();
            (x_train_split, Some(x_val))
        } else {
            (x_train.clone(), None)
        };
        let (y_train_split, y_val) = if config.validation_split > 0.0 {
            let y_train_split = y_train
                .slice(scirs2_core::ndarray::s![0..val_split_idx, ..])
                .to_owned()
                .into_dyn();
            let y_val = y_train
                .slice(scirs2_core::ndarray::s![val_split_idx.., ..])
                .to_owned()
                .into_dyn();
            (y_train_split, Some(y_val))
        } else {
            (y_train.clone(), None)
        };
        // Training loop
        for epoch in 0..config.epochs {
            let mut epoch_loss = F::zero();
            let num_batches = x_train_split.shape()[0].div_ceil(config.batch_size);
            // Training phase
            for i in 0..num_batches {
                let start_idx = i * config.batch_size;
                let end_idx =
                    std::cmp::min(start_idx + config.batch_size, x_train_split.shape()[0]);
                let batch_x = x_train_split
                    .slice(scirs2_core::ndarray::s![start_idx..end_idx, ..])
                    .to_owned()
                    .into_dyn();
                let batch_y = y_train_split
                    .slice(scirs2_core::ndarray::s![start_idx..end_idx, ..])
                    .to_owned()
                    .into_dyn();
                let batch_loss = self.train_batch(&batch_x, &batch_y, loss_fn, optimizer)?;
                epoch_loss += batch_loss;
            }
            let avg_train_loss =
                epoch_loss / F::from_usize(num_batches).unwrap_or_else(|| F::one());
            self.history.train_loss.push(avg_train_loss);
            // Validation phase
            if let (Some(x_val), Some(y_val)) = (&x_val, &y_val) {
                let val_loss = self.evaluate(x_val, y_val, loss_fn)?;
                self.history.val_loss.push(val_loss);
            } else {
                // If no validation split, use training loss as validation loss
                self.history.val_loss.push(avg_train_loss);
            }

            if config.verbose > 0 {
                println!(
                    "Epoch {}/{} - loss: {:.4}",
                    epoch + 1,
                    config.epochs,
                    avg_train_loss
                );
            }
        }

        Ok(())
    }
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + Display + NumAssign + 'static> Model<F>
    for Sequential<F>
{
    fn forward(
        &self,
        input: &Array<F, scirs2_core::ndarray::IxDyn>,
    ) -> Result<Array<F, scirs2_core::ndarray::IxDyn>> {
        let mut current_output = input.clone();
        for layer in &self.layers {
            current_output = layer.forward(&current_output)?;
        }
        Ok(current_output)
    }
    fn backward(
        &self,
        input: &Array<F, scirs2_core::ndarray::IxDyn>,
        grad_output: &Array<F, scirs2_core::ndarray::IxDyn>,
    ) -> Result<Array<F, scirs2_core::ndarray::IxDyn>> {
        if self.layer_outputs.is_empty() {
            return Err(NeuralError::InferenceError(
                "No forward pass performed before backward pass".to_string(),
            ));
        }
        let mut grad_input = grad_output.clone();
        // Iterate through layers in reverse
        for (i, layer) in self.layers.iter().enumerate().rev() {
            // Get input for this layer (either from previous layer or the original input)
            let layer_input = if i > 0 {
                &self.layer_outputs[i - 1]
            } else if let Some(saved_input) = &self.input {
                saved_input
            } else {
                // Fallback to the provided input if nothing is saved
                input
            };
            grad_input = layer.backward(layer_input, &grad_input)?;
        }
        Ok(grad_input)
    }
    fn update(&mut self, learningrate: F) -> Result<()> {
        for layer in &mut self.layers {
            layer.update(learningrate)?;
        }
        Ok(())
    }
    fn train_batch(
        &mut self,
        inputs: &Array<F, scirs2_core::ndarray::IxDyn>,
        targets: &Array<F, scirs2_core::ndarray::IxDyn>,
        loss_fn: &dyn Loss<F>,
        optimizer: &mut dyn Optimizer<F>,
    ) -> Result<F> {
        // Forward pass
        let mut layer_outputs = Vec::with_capacity(self.layers.len());
        let mut current_output = inputs.clone();
        for layer in &self.layers {
            current_output = layer.forward(&current_output)?;
            layer_outputs.push(current_output.clone());
        }
        // Save outputs for backward pass
        self.input = Some(inputs.clone());
        self.layer_outputs = layer_outputs;
        // Compute loss
        let predictions = self
            .layer_outputs
            .last()
            .ok_or_else(|| NeuralError::InferenceError("No layers in model".to_string()))?;
        let loss = loss_fn.forward(predictions, targets)?;
        // Backward pass to compute gradients
        let loss_grad = loss_fn.backward(predictions, targets)?;
        let mut grad_input = loss_grad;
        for (i, layer) in self.layers.iter_mut().enumerate().rev() {
            let layer_input = if i > 0 {
                &self.layer_outputs[i - 1]
            } else {
                inputs
            };
            grad_input = layer.backward(layer_input, &grad_input)?;
        }
        // Update parameters using optimizer
        let mut all_params = Vec::new();
        let mut all_grads = Vec::new();
        let mut param_layers = Vec::new();
        // First, collect all parameters and gradients
        for (i, layer) in self.layers.iter().enumerate() {
            // Need to use concrete type instead of dyn trait for downcasting
            // Try to use concrete implementations
            if let Some(param_layer) = layer
                .as_any()
                .downcast_ref::<Box<dyn ParamLayer<F> + Send + Sync>>()
            {
                param_layers.push(i);
                for param in param_layer.get_parameters() {
                    all_params.push(param.clone());
                }
                for grad in param_layer.get_gradients() {
                    all_grads.push(grad.clone());
                }
            }
        }
        optimizer.update(&mut all_params, &all_grads)?;
        // Update the layers with the optimized parameters
        let mut param_idx = 0;
        for i in param_layers {
            if let Some(param_layer) = self.layers[i]
                .as_any_mut()
                .downcast_mut::<Box<dyn ParamLayer<F> + Send + Sync>>()
            {
                let num_params = param_layer.get_parameters().len();
                if param_idx + num_params <= all_params.len() {
                    let layer_params = all_params[param_idx..param_idx + num_params].to_vec();
                    param_layer.set_parameters(layer_params)?;
                    param_idx += num_params;
                }
            }
        }
        Ok(loss)
    }
    fn predict(
        &self,
        inputs: &Array<F, scirs2_core::ndarray::IxDyn>,
    ) -> Result<Array<F, scirs2_core::ndarray::IxDyn>> {
        self.forward(inputs)
    }

    fn evaluate(
        &self,
        inputs: &Array<F, scirs2_core::ndarray::IxDyn>,
        targets: &Array<F, scirs2_core::ndarray::IxDyn>,
        loss_fn: &dyn Loss<F>,
    ) -> Result<F> {
        let predictions = self.forward(inputs)?;
        loss_fn.forward(&predictions, targets)
    }
}
// #[cfg(test)]
// mod tests {
//     use super::*;
//     use crate::layers::Dense;
//     use crate::losses::MeanSquaredError;
//     use crate::models::TrainingConfig;
//     use crate::optimizers::SGD;
//     use scirs2_core::ndarray::Array2;
//     use scirs2_core::random::rngs::StdRng;
//     use scirs2_core::random::SeedableRng;
//
//     // Note: Tests temporarily disabled due to rand version conflicts
//     // TODO: Fix rand version compatibility issues
//     #[allow(dead_code)]
//     fn _test_sequential_training() {
//         let mut rng = StdRng::seed_from_u64(42);
//         let mut model = Sequential::<f64>::new();
//         // Add layers
//         model.add_layer(Dense::new(4, 8, None, &mut rng).expect("Operation failed"));
//         model.add_layer(Dense::new(8, 4, None, &mut rng).expect("Operation failed"));
//         model.add_layer(Dense::new(4, 1, None, &mut rng).expect("Operation failed"));
//         // Create dummy data
//         let train_x = Array2::<f64>::from_elem((100, 4), 0.5).into_dyn();
//         let train_y = Array2::<f64>::from_elem((100, 1), 1.0).into_dyn();
//         // Training configuration
//         let config = TrainingConfig {
//             batch_size: 10,
//             epochs: 5,
//             validation_split: 0.2,
//             verbose: 0,
//             ..Default::default()
//         };
//         let loss_fn = MeanSquaredError::new();
//         let mut optimizer = SGD::new(0.01);
//         // Train the model
//         model.fit(&train_x, &train_y, &config, &loss_fn, &mut optimizer).expect("Operation failed");
//         // Check that training history was recorded
//         assert!(!model.training_history().train_loss.is_empty());
//         assert!(!model.training_history().val_loss.is_empty());
//     }
//     #[test]
//     fn test_sequential_prediction() {
//         model.add_layer(Dense::new(3, 5, None, &mut rng).expect("Operation failed"));
//         model.add_layer(Dense::new(5, 2, None, &mut rng).expect("Operation failed"));
//         let input = Array2::<f64>::from_elem((2, 3), 0.5).into_dyn();
//         let output = model.predict(&input).expect("Operation failed");
//         assert_eq!(output.shape(), &[2, 2]);
//     fn test_batched_prediction() {
//         let input = Array2::<f64>::from_elem((25, 3), 0.5).into_dyn();
//         let output = model.predict_batched(&input, 10).expect("Operation failed");
//         assert_eq!(output.shape(), &[25, 2]);
// }