optirs-nas 0.3.2

OptiRS Neural Architecture Search and hyperparameter optimization
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use std::fmt::Debug;
// Neural Architecture Search Engine Module
//
// This module provides a comprehensive Neural Architecture Search (NAS) implementation
// for automatically discovering optimal optimization algorithms. The module is organized
// into focused sub-modules for maintainability and modularity.
//
// ## Module Organization
//
// - **config**: Configuration types, enums, and parameter definitions
// - **results**: Search results, evaluation results, and statistics tracking
// - **resources**: Resource monitoring, constraint enforcement, and optimization
// - **engine**: Main NAS engine implementation and coordination logic
//
// ## Usage
//
// ```rust
// use optirs_core::neural_architecture_search::nas_engine::{
//     NeuralArchitectureSearch, NASConfig, SearchStrategyType,
//     SearchSpaceConfig, EvaluationConfig, MultiObjectiveConfig
// };
// use scirs2_core::numeric::Float;
//
// // Configure the NAS engine
// let config = NASConfig::<f64> {
//     search_strategy: SearchStrategyType::Evolutionary,
//     search_space: SearchSpaceConfig::default(),
//     evaluation_config: EvaluationConfig::default(),
//     multi_objective_config: MultiObjectiveConfig::default(),
//     search_budget: 1000,
//     // ... other configuration
//     ..Default::default()
// };
//
// // Create and run NAS engine
// let mut nas_engine = NeuralArchitectureSearch::new(config)?;
// let results = nas_engine.run_search()?;
//
// // Access best found architectures
// for architecture in &results.best_architectures {
//     println!("Found architecture: {:?}", architecture.architecture_id);
// }
// ```
//
// ## Key Features
//
// ### Search Strategies
// - Random search baseline
// - Evolutionary algorithms (genetic algorithms, differential evolution)
// - Bayesian optimization with Gaussian processes
// - Reinforcement learning-based search
// - Differentiable architecture search (DARTS)
// - Progressive search with increasing complexity
// - Hybrid strategies combining multiple approaches
//
// ### Multi-Objective Optimization
// - NSGA-II: Non-dominated Sorting Genetic Algorithm II
// - NSGA-III: Non-dominated Sorting Genetic Algorithm III
// - MOEA/D: Multi-Objective Evolutionary Algorithm based on Decomposition
// - PAES: Pareto Archived Evolution Strategy
// - SPEA2: Strength Pareto Evolutionary Algorithm 2
//
// ### Resource Management
// - Memory usage monitoring and constraints
// - CPU and GPU time tracking
// - Energy consumption estimation
// - Financial cost tracking
// - Network bandwidth monitoring
// - Automatic resource constraint enforcement
//
// ### Performance Features
// - Performance prediction for faster evaluation
// - Progressive search for complex search spaces
// - Transfer learning between search sessions
// - Parallel evaluation of candidate architectures
// - Caching of evaluation results
// - Early stopping based on convergence criteria

use crate::EvaluationMetric;
use scirs2_core::numeric::Float;

pub mod config;
pub mod engine;
pub mod resources;
pub mod results;
/// Engine-side adapters exposing the real `crate::search_strategies`
/// implementations through the engine's own `SearchStrategy` trait.
///
/// Crate-internal: the adapters are an implementation detail of
/// [`engine::NeuralArchitectureSearch::new`], which picks one per
/// [`config::SearchStrategyType`].
pub(crate) mod strategy_adapters;
pub mod telemetry;

// Re-export core types for convenience
pub use config::*;
pub use engine::*;
pub use resources::*;
pub use results::*;

// Additional convenience re-exports for commonly used combinations
pub use engine::{
    ArchitectureController, DiversityMetrics, MultiObjectiveOptimizer, NeuralArchitectureSearch,
    PerformanceEvaluator, PerformancePredictor, ProgressiveNAS, SearchStrategy,
};

// Re-export ParetoFront from multi_objective module
pub use crate::multi_objective::ParetoFront;

pub use config::{
    EarlyStoppingConfig, EvaluationConfig, MultiObjectiveConfig, NASConfig, ObjectiveConfig,
    SearchSpaceConfig, SearchStrategyType,
};

pub use results::{
    ArchitectureEncoding, ConvergenceData, EvaluationResults, OptimizerArchitecture,
    OptimizerComponent, SearchResult, SearchResults, SearchStatistics,
};

pub use config::{HardwareResources, ResourceConstraints};
pub use resources::{ResourceMonitor, ResourceOptimizer, ResourceSnapshot};
pub use results::ResourceUsage;

/// Example function demonstrating basic NAS usage
pub fn create_example_nas_config<T: Float + Debug + Send + Sync + 'static>() -> NASConfig<T> {
    NASConfig {
        search_strategy: SearchStrategyType::Evolutionary,
        search_space: SearchSpaceConfig {
            components: vec![
                OptimizerComponentConfig {
                    component_type: ComponentType::Adam,
                    hyperparameter_ranges: {
                        let mut ranges = std::collections::HashMap::new();
                        ranges.insert(
                            "learning_rate".to_string(),
                            ParameterRange::Continuous(0.0001, 0.1),
                        );
                        ranges.insert("beta1".to_string(), ParameterRange::Continuous(0.8, 0.99));
                        ranges.insert("beta2".to_string(), ParameterRange::Continuous(0.9, 0.999));
                        ranges
                    },
                    complexity_score: 1.0,
                    memory_requirement: 2048,
                    computational_cost: 1.5,
                    compatibility_constraints: Vec::new(),
                },
                OptimizerComponentConfig {
                    component_type: ComponentType::SGD,
                    hyperparameter_ranges: {
                        let mut ranges = std::collections::HashMap::new();
                        ranges.insert(
                            "learning_rate".to_string(),
                            ParameterRange::Continuous(0.001, 0.1),
                        );
                        ranges.insert(
                            "momentum".to_string(),
                            ParameterRange::Continuous(0.0, 0.99),
                        );
                        ranges
                    },
                    complexity_score: 0.5,
                    memory_requirement: 1024,
                    computational_cost: 1.0,
                    compatibility_constraints: Vec::new(),
                },
                OptimizerComponentConfig {
                    component_type: ComponentType::RMSprop,
                    hyperparameter_ranges: {
                        let mut ranges = std::collections::HashMap::new();
                        ranges.insert(
                            "learning_rate".to_string(),
                            ParameterRange::Continuous(0.0001, 0.1),
                        );
                        ranges.insert("decay".to_string(), ParameterRange::Continuous(0.8, 0.99));
                        ranges
                    },
                    complexity_score: 0.8,
                    memory_requirement: 1536,
                    computational_cost: 1.2,
                    compatibility_constraints: Vec::new(),
                },
            ],
            connection_patterns: vec![ConnectionPatternType::Sequential],
            learning_rate_schedules: LearningRateScheduleSpace::default(),
            regularization_techniques: RegularizationSpace::default(),
            adaptive_mechanisms: AdaptiveMechanismSpace::default(),
            memory_constraints: MemoryConstraints::default(),
            computation_constraints: ComputationConstraints::default(),
            component_types: vec![
                ComponentType::Adam,
                ComponentType::SGD,
                ComponentType::RMSprop,
            ],
            max_components: 10,
            min_components: 2,
            max_connections: 20,
        },
        evaluation_config: EvaluationConfig::default(),
        multi_objective_config: MultiObjectiveConfig::default(),
        search_budget: 500,
        early_stopping: EarlyStoppingConfig {
            enabled: true,
            patience: 25,
            min_improvement: scirs2_core::numeric::NumCast::from(0.001)
                .unwrap_or_else(|| T::zero()),
            metric: EvaluationMetric::FinalPerformance,
            target_performance: None,
            convergence_detection: ConvergenceDetectionStrategy::NoImprovement,
            convergence_strategy: ConvergenceDetectionStrategy::BestScore,
            min_generations: 10,
        },
        progressive_search: false,
        population_size: 25,
        enable_transfer_learning: false,
        encoding_strategy: ArchitectureEncodingStrategy::Direct,
        enable_performance_prediction: true,
        parallelization_factor: 2,
        auto_hyperparameter_tuning: true,
        resource_constraints: ResourceConstraints {
            max_memory_gb: scirs2_core::numeric::NumCast::from(8.0).unwrap_or_else(|| T::zero()),
            max_computation_hours: scirs2_core::numeric::NumCast::from(12.0)
                .unwrap_or_else(|| T::zero()),
            max_energy_kwh: scirs2_core::numeric::NumCast::from(50.0).unwrap_or_else(|| T::zero()),
            max_cost_usd: scirs2_core::numeric::NumCast::from(500.0).unwrap_or_else(|| T::zero()),
            energy_constraints: Some(
                scirs2_core::numeric::NumCast::from(50.0).unwrap_or_else(|| T::zero()),
            ),
            cost_constraints: Some(
                scirs2_core::numeric::NumCast::from(500.0).unwrap_or_else(|| T::zero()),
            ),
            time_constraints: TimeConstraints::default(),
            hardware_resources: HardwareResources {
                cpu_cores: 8,
                ram_gb: 32,
                num_gpus: 2,
                gpu_memory_gb: 16,
                storage_gb: 500,
                network_bandwidth_mbps: 500.0,
                max_memory_gb: 32.0,
                max_cpu_cores: 8,
                max_gpu_devices: 2,
                max_storage_gb: 500.0,
                max_network_bandwidth: 500.0,
                enable_cloud_scaling: false,
                cloud_budget: None,
            },
            enable_monitoring: true,
            violation_handling: ResourceViolationHandling::Penalty,
        },
    }
}

/// Create a minimal NAS configuration for quick testing
pub fn create_minimal_nas_config<T: Float + Debug + Send + Sync + 'static>() -> NASConfig<T> {
    NASConfig {
        search_strategy: SearchStrategyType::Random,
        search_space: SearchSpaceConfig {
            components: vec![
                OptimizerComponentConfig {
                    component_type: ComponentType::Adam,
                    hyperparameter_ranges: std::collections::HashMap::new(),
                    complexity_score: 1.0,
                    memory_requirement: 1024,
                    computational_cost: 1.0,
                    compatibility_constraints: Vec::new(),
                },
                OptimizerComponentConfig {
                    component_type: ComponentType::SGD,
                    hyperparameter_ranges: std::collections::HashMap::new(),
                    complexity_score: 0.5,
                    memory_requirement: 512,
                    computational_cost: 0.5,
                    compatibility_constraints: Vec::new(),
                },
            ],
            connection_patterns: vec![ConnectionPatternType::Sequential],
            learning_rate_schedules: LearningRateScheduleSpace::default(),
            regularization_techniques: RegularizationSpace::default(),
            adaptive_mechanisms: AdaptiveMechanismSpace::default(),
            memory_constraints: MemoryConstraints::default(),
            computation_constraints: ComputationConstraints::default(),
            component_types: vec![ComponentType::Adam, ComponentType::SGD],
            max_components: 5,
            min_components: 1,
            max_connections: 10,
        },
        evaluation_config: EvaluationConfig::default(),
        multi_objective_config: MultiObjectiveConfig::default(),
        search_budget: 100,
        early_stopping: EarlyStoppingConfig {
            enabled: true,
            patience: 10,
            min_improvement: scirs2_core::numeric::NumCast::from(0.01).unwrap_or_else(|| T::zero()),
            metric: EvaluationMetric::FinalPerformance,
            target_performance: None,
            convergence_detection: ConvergenceDetectionStrategy::NoImprovement,
            convergence_strategy: ConvergenceDetectionStrategy::BestScore,
            min_generations: 5,
        },
        progressive_search: false,
        population_size: 10,
        enable_transfer_learning: false,
        encoding_strategy: ArchitectureEncodingStrategy::Direct,
        enable_performance_prediction: false,
        parallelization_factor: 1,
        auto_hyperparameter_tuning: false,
        resource_constraints: ResourceConstraints {
            max_memory_gb: scirs2_core::numeric::NumCast::from(4.0).unwrap_or_else(|| T::zero()),
            max_computation_hours: scirs2_core::numeric::NumCast::from(1.0)
                .unwrap_or_else(|| T::zero()),
            max_energy_kwh: scirs2_core::numeric::NumCast::from(5.0).unwrap_or_else(|| T::zero()),
            max_cost_usd: scirs2_core::numeric::NumCast::from(50.0).unwrap_or_else(|| T::zero()),
            hardware_resources: HardwareResources {
                max_cpu_cores: 4,
                max_memory_gb: 16.0,
                max_gpu_devices: 1,
                max_storage_gb: 100.0,
                max_network_bandwidth: 100.0,
                enable_cloud_scaling: false,
                cloud_budget: None,
                cpu_cores: 4,
                ram_gb: 16,
                num_gpus: 1,
                gpu_memory_gb: 8,
                storage_gb: 100,
                network_bandwidth_mbps: 100.0,
            },
            time_constraints: TimeConstraints::default(),
            energy_constraints: Some(
                scirs2_core::numeric::NumCast::from(5.0).unwrap_or_else(|| T::zero()),
            ),
            cost_constraints: Some(
                scirs2_core::numeric::NumCast::from(50.0).unwrap_or_else(|| T::zero()),
            ),
            violation_handling: ResourceViolationHandling::Penalty,
            enable_monitoring: false,
        },
    }
}

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

    #[test]
    fn test_nas_config_creation() {
        let config = NASConfig::<f64>::default();
        assert_eq!(config.search_budget, 100);
        assert_eq!(config.population_size, 20);
        assert!(config.early_stopping.enabled);
    }

    #[test]
    fn test_resource_constraints_validation() {
        let constraints = ResourceConstraints::<f64> {
            max_memory_gb: 16.0,
            max_computation_hours: 24.0,
            max_energy_kwh: 100.0,
            max_cost_usd: 1000.0,
            hardware_resources: HardwareResources::default(),
            enable_monitoring: true,
            violation_handling: ResourceViolationHandling::Penalty,
            time_constraints: TimeConstraints::default(),
            energy_constraints: Some(100.0),
            cost_constraints: Some(1000.0),
        };

        // The monitor used to be built and dropped without a single assertion, so
        // the test proved nothing about it. Check the constraints actually reach
        // the monitor and that an idle monitor reports idle state rather than
        // fabricated activity.
        let mut monitor = ResourceMonitor::new(constraints.clone());
        assert_eq!(monitor.get_monitoring_state(), MonitoringState::Stopped);
        assert!(monitor.get_usage_history().is_empty());
        assert!(
            monitor
                .check_violations()
                .expect("checking violations on an idle monitor must succeed")
                .is_empty(),
            "generous constraints cannot be violated before anything is measured"
        );

        let report = monitor.generate_report();
        assert_eq!(report.total_samples, 0);
        assert_eq!(report.monitoring_duration, std::time::Duration::ZERO);

        // Re-configuring the monitor is what `update_constraints` exists for.
        let mut tightened = constraints.clone();
        tightened.max_memory_gb = 0.0;
        monitor.update_constraints(tightened);
        assert!(
            monitor
                .check_violations()
                .expect("checking violations must succeed after reconfiguration")
                .is_empty(),
            "no sample has been taken, so even a zero budget cannot be exceeded yet"
        );

        assert!(constraints.max_memory_gb > 0.0);
    }

    #[test]
    fn test_search_strategy_types() {
        let strategies = [
            SearchStrategyType::Random,
            SearchStrategyType::Evolutionary,
            SearchStrategyType::BayesianOptimization,
            SearchStrategyType::ReinforcementLearning,
            SearchStrategyType::Differentiable,
            SearchStrategyType::Progressive,
            SearchStrategyType::MultiObjectiveEvolutionary,
            SearchStrategyType::NeuralPredictorBased,
        ];

        assert_eq!(strategies.len(), 8);
    }

    #[test]
    fn test_multi_objective_algorithms() {
        let algorithms = [
            MultiObjectiveAlgorithm::NSGA2,
            MultiObjectiveAlgorithm::NSGA3,
            MultiObjectiveAlgorithm::MOEAD,
            MultiObjectiveAlgorithm::PAES,
            MultiObjectiveAlgorithm::SPEA2,
        ];

        assert_eq!(algorithms.len(), 5);
    }

    #[test]
    fn test_evaluation_metrics() {
        let metrics = [
            EvaluationMetric::FinalPerformance,
            EvaluationMetric::ConvergenceSpeed,
            EvaluationMetric::Stability,
            EvaluationMetric::Robustness,
            EvaluationMetric::Efficiency,
            EvaluationMetric::Generalization,
            EvaluationMetric::MemoryUsage,
            EvaluationMetric::ComputationTime,
        ];

        assert_eq!(metrics.len(), 8);
    }

    #[test]
    fn test_component_types() {
        let components = vec![
            ComponentType::SGD,
            ComponentType::Adam,
            ComponentType::AdamW,
            ComponentType::RMSprop,
            ComponentType::AdaGrad,
            ComponentType::AdaDelta,
            ComponentType::LBFGS,
            ComponentType::Momentum,
            ComponentType::Nesterov,
            ComponentType::Custom("custom".to_string()),
        ];

        assert_eq!(components.len(), 10);
    }

    #[test]
    fn test_resource_usage_calculation() {
        let usage = ResourceUsage::<f64> {
            memory_gb: 8.0,
            cpu_time_seconds: 3600.0,
            gpu_time_seconds: 1800.0,
            energy_kwh: 5.4,
            cost_usd: 0.648,
            network_gb: 0.1,
            network_io_gb: 0.1,
            disk_io_gb: 0.5,
            peak_memory_gb: 10.0,
            efficiency_score: 0.75,
        };

        assert!(usage.memory_gb > 0.0);
        assert!(usage.cpu_time_seconds > 0.0);
        assert!(usage.energy_kwh > 0.0);
    }

    #[test]
    fn test_architecture_encoding() {
        let encoding = ArchitectureEncoding {
            encoding_type: EncodingType::Binary,
            binary_encoding: Some(vec![1, 2, 3, 4]),
            string_encoding: None,
            graph_encoding: None,
            hash: 12345,
            metadata: EncodingMetadata::default(),
        };

        assert_eq!(
            encoding
                .binary_encoding
                .as_ref()
                .expect("unwrap failed")
                .len(),
            4
        );
        assert_eq!(encoding.hash, 12345);
    }

    #[test]
    fn test_search_statistics_initialization() {
        let stats = SearchStatistics::<f64>::default();
        assert_eq!(stats.total_evaluations, 0);
        assert_eq!(stats.current_generation, 0);
        assert!(stats.population_diversity >= 0.0);
    }

    #[test]
    fn test_pareto_front_creation() {
        use crate::multi_objective::{CoverageMetrics, FrontMetrics, ObjectiveBounds};

        let pareto_front = ParetoFront::<f64> {
            solutions: Vec::new(),
            objective_bounds: ObjectiveBounds {
                min_values: Vec::new(),
                max_values: Vec::new(),
                ideal_point: Vec::new(),
                nadir_point: Vec::new(),
            },
            metrics: FrontMetrics {
                hypervolume: 0.0,
                spread: 0.0,
                spacing: 0.0,
                convergence: 0.0,
                num_solutions: 0,
                coverage: CoverageMetrics {
                    objective_space_coverage: 0.0,
                    reference_distance: 0.0,
                    epsilon_dominance: 0.0,
                },
            },
            generation: 0,
            last_updated: std::time::SystemTime::now(),
        };

        assert_eq!(pareto_front.solutions.len(), 0);
        assert_eq!(pareto_front.generation, 0);
    }

    #[test]
    fn test_hardware_resources() {
        let hardware = HardwareResources {
            max_memory_gb: 128.0,
            max_cpu_cores: 32,
            max_gpu_devices: 8,
            max_storage_gb: 2000.0,
            max_network_bandwidth: 10000.0,
            enable_cloud_scaling: false,
            cloud_budget: None,
            cpu_cores: 16,
            ram_gb: 64,
            num_gpus: 4,
            gpu_memory_gb: 32,
            storage_gb: 1000,
            network_bandwidth_mbps: 1000.0,
        };

        assert!(hardware.cpu_cores > 0);
        assert!(hardware.ram_gb > 0);
        assert!(hardware.num_gpus > 0);
    }
}