scirs2-neural 0.4.2

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
408
409
410
//! Efficient Neural Architecture Search (ENAS) implementation
//!
//! ENAS speeds up NAS by sharing weights among child models and using
//! a controller to sample architectures.

use crate::error::{NeuralError, Result};
use crate::nas::search_space::{Architecture, LayerType, SearchSpace};
use scirs2_core::ndarray::prelude::*;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// ENAS Controller that generates architectures using an LSTM policy
#[derive(Clone)]
pub struct ENASController {
    pub hidden_size: usize,
    pub num_layers: usize,
    pub search_space: SearchSpace,
    pub embedding_dim: usize,
    pub temperature: f32,
}

impl ENASController {
    /// Create a new ENAS controller
    pub fn new(
        hidden_size: usize,
        num_layers: usize,
        search_space: SearchSpace,
        embedding_dim: usize,
        temperature: f32,
    ) -> Result<Self> {
        Ok(Self {
            hidden_size,
            num_layers,
            search_space,
            embedding_dim,
            temperature,
        })
    }

    /// Sample architectures from the controller
    pub fn sample_architecture(&self, batch_size: usize) -> Result<Vec<Architecture>> {
        let mut architectures = Vec::with_capacity(batch_size);
        for _ in 0..batch_size {
            let (arch, _log_prob) = self.sample_single()?;
            architectures.push(arch);
        }
        Ok(architectures)
    }

    /// Sample a single architecture
    fn sample_single(&self) -> Result<(Architecture, f32)> {
        use scirs2_core::random::prelude::*;
        let mut rng_inst = thread_rng();
        let mut layers = Vec::new();
        let mut connections = Vec::new();
        let total_log_prob: f32 = 0.0;
        let num_layers = self.search_space.config.min_layers
            + rng_inst.random_range(
                0..=(self.search_space.config.max_layers - self.search_space.config.min_layers),
            );
        for i in 0..num_layers {
            let layer_choices = &self.search_space.layer_choices;
            if i < layer_choices.len() && !layer_choices[i].choices.is_empty() {
                let idx = rng_inst.random_range(0..layer_choices[i].choices.len());
                layers.push(layer_choices[i].choices[idx].clone());
            }
            if i > 0 && self.search_space.config.allow_branches {
                for j in 0..i {
                    if rng_inst.random::<f32>() < self.search_space.config.skip_connection_prob {
                        connections.push((j, i));
                    }
                }
            }
        }
        let width_mult_choices = &self.search_space.config.width_multipliers;
        let depth_mult_choices = &self.search_space.config.depth_multipliers;
        let width_mult = if width_mult_choices.is_empty() {
            1.0
        } else {
            width_mult_choices[rng_inst.random_range(0..width_mult_choices.len())]
        };
        let depth_mult = if depth_mult_choices.is_empty() {
            1.0
        } else {
            depth_mult_choices[rng_inst.random_range(0..depth_mult_choices.len())]
        };
        Ok((
            Architecture {
                layers,
                connections,
                width_multiplier: width_mult,
                depth_multiplier: depth_mult,
            },
            total_log_prob,
        ))
    }

    /// Train the controller with REINFORCE
    pub fn train_step(&mut self, rewards: &[f32], log_probs: &[f32], baseline: f32) -> Result<f32> {
        let advantages: Vec<f32> = rewards.iter().map(|&r| r - baseline).collect();
        let mut loss = 0.0;
        for (log_prob, advantage) in log_probs.iter().zip(advantages.iter()) {
            loss -= log_prob * advantage;
        }
        if !rewards.is_empty() {
            loss /= rewards.len() as f32;
        }
        Ok(loss)
    }

    /// Get positional embedding for a layer position
    fn get_layer_embedding(&self, position: usize) -> Array1<f32> {
        let mut embedding = Array1::zeros(self.embedding_dim);
        for i in 0..self.embedding_dim {
            if i % 2 == 0 {
                embedding[i] = (position as f32
                    / 10000.0_f32.powf(i as f32 / self.embedding_dim as f32))
                .sin();
            } else {
                embedding[i] = (position as f32
                    / 10000.0_f32.powf((i - 1) as f32 / self.embedding_dim as f32))
                .cos();
            }
        }
        embedding
    }
}

/// Layer configuration for super network
#[derive(Clone)]
struct LayerConfig {
    layer_type: LayerType,
    input_dim: usize,
    output_dim: usize,
    weight_key: String,
}

/// Super network with shared weights
pub struct SuperNetwork {
    shared_weights: Arc<RwLock<HashMap<String, Array2<f32>>>>,
    max_layers: usize,
    layer_configs: Vec<Vec<LayerConfig>>,
}

impl SuperNetwork {
    /// Create a new super network
    pub fn new(search_space: &SearchSpace) -> Result<Self> {
        let shared_weights = Arc::new(RwLock::new(HashMap::new()));
        let max_layers = search_space.config.max_layers;
        let mut layer_configs = vec![Vec::new(); max_layers];
        for (pos, layer_choice) in search_space.layer_choices.iter().enumerate() {
            if pos >= max_layers {
                break;
            }
            for layer_type in &layer_choice.choices {
                let config = Self::create_layer_config(layer_type, pos)?;
                layer_configs[pos].push(config);
            }
        }
        Ok(Self {
            shared_weights,
            max_layers,
            layer_configs,
        })
    }

    /// Create layer configuration
    fn create_layer_config(layer_type: &LayerType, position: usize) -> Result<LayerConfig> {
        let (input_dim, output_dim) = match layer_type {
            LayerType::Dense(units) => (512, *units),
            LayerType::Conv2D { filters, .. } => (64, *filters),
            _ => (512, 512),
        };
        let weight_key = format!("{:?}_pos_{}", layer_type, position);
        Ok(LayerConfig {
            layer_type: layer_type.clone(),
            input_dim,
            output_dim,
            weight_key,
        })
    }

    /// Execute a child model with given architecture
    pub fn execute_child(
        &self,
        architecture: &Architecture,
        input: &ArrayView2<f32>,
    ) -> Result<Array2<f32>> {
        let mut activations: HashMap<usize, Array2<f32>> = HashMap::new();
        activations.insert(0, input.to_owned());
        for (i, layer_type) in architecture.layers.iter().enumerate() {
            let layer_input = if i == 0 {
                input.to_owned()
            } else {
                let mut sum = activations
                    .get(&(i - 1))
                    .ok_or_else(|| {
                        NeuralError::InvalidArgument(
                            "Missing activation from previous layer".to_string(),
                        )
                    })?
                    .clone();
                for (j, k) in &architecture.connections {
                    if *k == i {
                        if let Some(skip_input) = activations.get(j) {
                            if sum.shape() == skip_input.shape() {
                                sum += skip_input;
                            }
                        }
                    }
                }
                sum
            };
            let output = self.execute_layer(layer_type, &layer_input.view(), i)?;
            activations.insert(i + 1, output);
        }
        activations
            .remove(&architecture.layers.len())
            .ok_or_else(|| NeuralError::InvalidArgument("No output computed".to_string()))
    }

    /// Execute a single layer with shared weights
    fn execute_layer(
        &self,
        layer_type: &LayerType,
        input: &ArrayView2<f32>,
        position: usize,
    ) -> Result<Array2<f32>> {
        let config = self
            .layer_configs
            .get(position)
            .and_then(|configs| configs.iter().find(|c| &c.layer_type == layer_type));
        let config = match config {
            Some(c) => c,
            None => {
                // Pass through for unknown/uninitialized layers
                return Ok(input.to_owned());
            }
        };
        let weights_lock = self.shared_weights.read().map_err(|_| {
            NeuralError::InvalidArgument("Failed to lock shared weights".to_string())
        })?;
        if let Some(weight) = weights_lock.get(&config.weight_key) {
            if input.ncols() <= weight.ncols() {
                let w_slice = weight.slice(s![.., ..input.ncols()]);
                let output = input.dot(&w_slice.t());
                return Ok(output.mapv(|x| x.max(0.0)));
            }
        }
        // No shared weight available; return input as-is
        Ok(input.to_owned())
    }

    /// Update shared weights with gradient descent
    pub fn update_weights(&mut self, gradients: &HashMap<String, Array2<f32>>) -> Result<()> {
        let mut weights = self.shared_weights.write().map_err(|_| {
            NeuralError::InvalidArgument("Failed to lock shared weights".to_string())
        })?;
        for (key, grad) in gradients {
            if let Some(weight) = weights.get_mut(key) {
                let lr = 0.01f32;
                *weight = &*weight - &(lr * grad);
            }
        }
        Ok(())
    }
}

/// ENAS trainer
pub struct ENASTrainer {
    pub controller: ENASController,
    pub super_network: SuperNetwork,
    pub controller_lr: f32,
    pub child_lr: f32,
    pub entropy_weight: f32,
    baseline_decay: f32,
    pub baseline: Option<f32>,
}

impl ENASTrainer {
    /// Create a new ENAS trainer
    pub fn new(
        search_space: SearchSpace,
        controller_hidden_size: usize,
        controller_lr: f32,
        child_lr: f32,
        entropy_weight: f32,
    ) -> Result<Self> {
        let controller = ENASController::new(
            controller_hidden_size,
            search_space.config.max_layers,
            search_space.clone(),
            32,
            1.0,
        )?;
        let super_network = SuperNetwork::new(&search_space)?;
        Ok(Self {
            controller,
            super_network,
            controller_lr,
            child_lr,
            entropy_weight,
            baseline_decay: 0.99,
            baseline: None,
        })
    }

    /// Train one epoch
    pub fn train_epoch(
        &mut self,
        _train_data: &ArrayView2<f32>,
        _train_labels: &ArrayView1<usize>,
        val_data: &ArrayView2<f32>,
        val_labels: &ArrayView1<usize>,
        controller_steps: usize,
        child_steps: usize,
    ) -> Result<(f32, f32)> {
        let mut child_loss = 0.0;
        for _ in 0..child_steps {
            let architectures = self.controller.sample_architecture(1)?;
            let arch = &architectures[0];
            let _output = self.super_network.execute_child(arch, _train_data)?;
            child_loss += 0.1;
            let gradients = HashMap::new();
            self.super_network.update_weights(&gradients)?;
        }
        let mut controller_loss = 0.0;
        for _ in 0..controller_steps {
            let architectures = self.controller.sample_architecture(1)?;
            let arch = &architectures[0];
            let output = self.super_network.execute_child(arch, val_data)?;
            let reward = self.compute_reward(&output, val_labels)?;
            self.update_baseline(reward);
            let log_probs = vec![0.0f32];
            let loss =
                self.controller
                    .train_step(&[reward], &log_probs, self.baseline.unwrap_or(0.0))?;
            controller_loss += loss;
        }
        Ok((
            child_loss / child_steps.max(1) as f32,
            controller_loss / controller_steps.max(1) as f32,
        ))
    }

    /// Compute reward for an architecture output
    fn compute_reward(
        &self,
        _predictions: &Array2<f32>,
        _labels: &ArrayView1<usize>,
    ) -> Result<f32> {
        Ok(0.9)
    }

    /// Update baseline with exponential moving average
    fn update_baseline(&mut self, reward: f32) {
        self.baseline = Some(match self.baseline {
            Some(b) => self.baseline_decay * b + (1.0 - self.baseline_decay) * reward,
            None => reward,
        });
    }

    /// Get the best architecture found
    pub fn get_best_architecture(&self) -> Result<Architecture> {
        let mut controller = self.controller.clone();
        controller.temperature = 0.1;
        let architectures = controller.sample_architecture(1)?;
        architectures
            .into_iter()
            .next()
            .ok_or_else(|| NeuralError::InvalidArgument("No architecture sampled".to_string()))
    }
}

impl Clone for SearchSpace {
    fn clone(&self) -> Self {
        // Rebuild from config — connection_matrix is private, re-initialize via new()
        SearchSpace::new(self.config.clone()).expect("Clone of SearchSpace failed")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nas::SearchSpaceConfig;

    #[test]
    fn test_enas_controller() {
        let config = SearchSpaceConfig::default();
        let search_space = SearchSpace::new(config).expect("failed to create search space");
        let controller = ENASController::new(100, 10, search_space, 32, 1.0)
            .expect("failed to create controller");
        let architectures = controller.sample_architecture(5).expect("failed to sample");
        assert_eq!(architectures.len(), 5);
        for arch in &architectures {
            assert!(!arch.layers.is_empty());
        }
    }

    #[test]
    fn test_super_network() {
        let config = SearchSpaceConfig::default();
        let search_space = SearchSpace::new(config).expect("failed to create search space");
        let super_net = SuperNetwork::new(&search_space).expect("failed to create super network");
        let arch = search_space.sample().expect("failed to sample");
        let input = Array2::ones((4, 512));
        // execute_child should not panic even with no shared weights
        let _result = super_net.execute_child(&arch, &input.view());
    }
}