quantum_nas/
quantum_nas.rs

1#![allow(clippy::pedantic, clippy::unnecessary_wraps)]
2//! Quantum Neural Architecture Search Example
3//!
4//! This example demonstrates various quantum neural architecture search algorithms
5//! including evolutionary search, reinforcement learning, random search,
6//! Bayesian optimization, and DARTS.
7
8use quantrs2_ml::prelude::*;
9use quantrs2_ml::qnn::QNNLayerType;
10use scirs2_core::ndarray::{Array1, Array2};
11use scirs2_core::random::prelude::*;
12
13fn main() -> Result<()> {
14    println!("=== Quantum Neural Architecture Search Demo ===\n");
15
16    // Step 1: Evolutionary algorithm search
17    println!("1. Evolutionary Algorithm Search...");
18    evolutionary_search_demo()?;
19
20    // Step 2: Random search baseline
21    println!("\n2. Random Search Baseline...");
22    random_search_demo()?;
23
24    // Step 3: Reinforcement learning search
25    println!("\n3. Reinforcement Learning Search...");
26    rl_search_demo()?;
27
28    // Step 4: Bayesian optimization
29    println!("\n4. Bayesian Optimization Search...");
30    bayesian_search_demo()?;
31
32    // Step 5: DARTS (Differentiable Architecture Search)
33    println!("\n5. DARTS (Differentiable Architecture Search)...");
34    darts_demo()?;
35
36    // Step 6: Multi-objective optimization
37    println!("\n6. Multi-Objective Optimization...");
38    multi_objective_demo()?;
39
40    // Step 7: Architecture analysis
41    println!("\n7. Architecture Analysis...");
42    architecture_analysis_demo()?;
43
44    println!("\n=== Quantum NAS Demo Complete ===");
45
46    Ok(())
47}
48
49/// Evolutionary algorithm search demonstration
50fn evolutionary_search_demo() -> Result<()> {
51    // Create search space
52    let search_space = create_default_search_space();
53
54    // Configure evolutionary strategy
55    let strategy = SearchStrategy::Evolutionary {
56        population_size: 20,
57        mutation_rate: 0.2,
58        crossover_rate: 0.7,
59        elitism_ratio: 0.1,
60    };
61
62    let mut nas = QuantumNAS::new(strategy, search_space);
63
64    println!("   Created evolutionary NAS:");
65    println!("   - Population size: 20");
66    println!("   - Mutation rate: 0.2");
67    println!("   - Crossover rate: 0.7");
68    println!("   - Elitism ratio: 0.1");
69
70    // Set evaluation data (synthetic for demo)
71    let eval_data = Array2::from_shape_fn((100, 4), |(i, j)| (i as f64 + j as f64) / 50.0);
72    let eval_labels = Array1::from_shape_fn(100, |i| i % 2);
73    nas.set_evaluation_data(eval_data, eval_labels);
74
75    // Run search
76    println!("\n   Running evolutionary search for 10 generations...");
77    let best_architectures = nas.search(10)?;
78
79    println!("   Search complete!");
80    println!(
81        "   - Best architectures found: {}",
82        best_architectures.len()
83    );
84
85    if let Some(best) = best_architectures.first() {
86        println!("   - Best architecture: {best}");
87        println!("   - Circuit depth: {}", best.metrics.circuit_depth);
88        println!("   - Parameter count: {}", best.metrics.parameter_count);
89
90        if let Some(expressivity) = best.properties.expressivity {
91            println!("   - Expressivity: {expressivity:.3}");
92        }
93    }
94
95    // Show search summary
96    let summary = nas.get_search_summary();
97    println!(
98        "   - Total architectures evaluated: {}",
99        summary.total_architectures_evaluated
100    );
101    println!("   - Pareto front size: {}", summary.pareto_front_size);
102
103    Ok(())
104}
105
106/// Random search baseline demonstration
107fn random_search_demo() -> Result<()> {
108    let search_space = create_default_search_space();
109    let strategy = SearchStrategy::Random { num_samples: 50 };
110
111    let mut nas = QuantumNAS::new(strategy, search_space);
112
113    println!("   Created random search NAS:");
114    println!("   - Number of samples: 50");
115
116    // Generate synthetic evaluation data
117    let eval_data = Array2::from_shape_fn((80, 4), |(i, j)| {
118        0.5f64.mul_add((i as f64).sin(), 0.3 * (j as f64).cos())
119    });
120    let eval_labels = Array1::from_shape_fn(80, |i| usize::from(i % 3 != 0));
121    nas.set_evaluation_data(eval_data, eval_labels);
122
123    println!("\n   Running random search...");
124    let best_architectures = nas.search(50)?;
125
126    println!("   Random search complete!");
127    if let Some(best) = best_architectures.first() {
128        println!("   - Best random architecture: {best}");
129        if let Some(accuracy) = best.metrics.accuracy {
130            println!("   - Accuracy: {accuracy:.3}");
131        }
132    }
133
134    Ok(())
135}
136
137/// Reinforcement learning search demonstration
138fn rl_search_demo() -> Result<()> {
139    let search_space = create_custom_search_space();
140
141    let strategy = SearchStrategy::ReinforcementLearning {
142        agent_type: RLAgentType::PolicyGradient,
143        exploration_rate: 0.3,
144        learning_rate: 0.01,
145    };
146
147    let mut nas = QuantumNAS::new(strategy, search_space);
148
149    println!("   Created RL-based NAS:");
150    println!("   - Agent type: Policy Gradient");
151    println!("   - Exploration rate: 0.3");
152    println!("   - Learning rate: 0.01");
153
154    println!("\n   Running RL search for 100 episodes...");
155    let best_architectures = nas.search(100)?;
156
157    println!("   RL search complete!");
158    println!("   - Architectures found: {}", best_architectures.len());
159
160    if let Some(best) = best_architectures.first() {
161        println!("   - Best RL architecture: {best}");
162        if let Some(entanglement) = best.properties.entanglement_capability {
163            println!("   - Entanglement capability: {entanglement:.3}");
164        }
165    }
166
167    Ok(())
168}
169
170/// Bayesian optimization search demonstration
171fn bayesian_search_demo() -> Result<()> {
172    let search_space = create_default_search_space();
173
174    let strategy = SearchStrategy::BayesianOptimization {
175        acquisition_function: AcquisitionFunction::ExpectedImprovement,
176        num_initial_points: 10,
177    };
178
179    let mut nas = QuantumNAS::new(strategy, search_space);
180
181    println!("   Created Bayesian optimization NAS:");
182    println!("   - Acquisition function: Expected Improvement");
183    println!("   - Initial random points: 10");
184
185    // Set up evaluation data
186    let eval_data = generate_quantum_data(60, 4);
187    let eval_labels = Array1::from_shape_fn(60, |i| i % 3);
188    nas.set_evaluation_data(eval_data, eval_labels);
189
190    println!("\n   Running Bayesian optimization for 30 iterations...");
191    let best_architectures = nas.search(30)?;
192
193    println!("   Bayesian optimization complete!");
194    if let Some(best) = best_architectures.first() {
195        println!("   - Best Bayesian architecture: {best}");
196        if let Some(hardware_eff) = best.metrics.hardware_efficiency {
197            println!("   - Hardware efficiency: {hardware_eff:.3}");
198        }
199    }
200
201    Ok(())
202}
203
204/// DARTS demonstration
205fn darts_demo() -> Result<()> {
206    let search_space = create_darts_search_space();
207
208    let strategy = SearchStrategy::DARTS {
209        learning_rate: 0.01,
210        weight_decay: 1e-4,
211    };
212
213    let mut nas = QuantumNAS::new(strategy, search_space);
214
215    println!("   Created DARTS NAS:");
216    println!("   - Learning rate: 0.01");
217    println!("   - Weight decay: 1e-4");
218    println!("   - Differentiable architecture search");
219
220    println!("\n   Running DARTS for 200 epochs...");
221    let best_architectures = nas.search(200)?;
222
223    println!("   DARTS search complete!");
224    if let Some(best) = best_architectures.first() {
225        println!("   - DARTS architecture: {best}");
226        println!("   - Learned through gradient-based optimization");
227
228        if let Some(gradient_var) = best.properties.gradient_variance {
229            println!("   - Gradient variance: {gradient_var:.3}");
230        }
231    }
232
233    Ok(())
234}
235
236/// Multi-objective optimization demonstration
237fn multi_objective_demo() -> Result<()> {
238    let search_space = create_default_search_space();
239
240    let strategy = SearchStrategy::Evolutionary {
241        population_size: 30,
242        mutation_rate: 0.15,
243        crossover_rate: 0.8,
244        elitism_ratio: 0.2,
245    };
246
247    let mut nas = QuantumNAS::new(strategy, search_space);
248
249    println!("   Multi-objective optimization:");
250    println!("   - Optimizing accuracy vs. complexity");
251    println!("   - Finding Pareto-optimal architectures");
252
253    // Run search
254    nas.search(15)?;
255
256    // Analyze Pareto front
257    let pareto_front = nas.get_pareto_front();
258    println!("   Pareto front analysis:");
259    println!("   - Pareto-optimal architectures: {}", pareto_front.len());
260
261    for (i, arch) in pareto_front.iter().take(3).enumerate() {
262        println!(
263            "   Architecture {}: {} params, {:.3} accuracy",
264            i + 1,
265            arch.metrics.parameter_count,
266            arch.metrics.accuracy.unwrap_or(0.0)
267        );
268    }
269
270    Ok(())
271}
272
273/// Architecture analysis demonstration
274fn architecture_analysis_demo() -> Result<()> {
275    println!("   Analyzing quantum circuit architectures...");
276
277    // Create sample architectures with different properties
278    let architectures = create_sample_architectures();
279
280    println!("\n   Architecture comparison:");
281    for (i, arch) in architectures.iter().enumerate() {
282        println!("   Architecture {}:", i + 1);
283        println!("     - Layers: {}", arch.layers.len());
284        println!("     - Qubits: {}", arch.num_qubits);
285        println!("     - Circuit depth: {}", arch.metrics.circuit_depth);
286
287        if let Some(expressivity) = arch.properties.expressivity {
288            println!("     - Expressivity: {expressivity:.3}");
289        }
290
291        if let Some(entanglement) = arch.properties.entanglement_capability {
292            println!("     - Entanglement: {entanglement:.3}");
293        }
294
295        if let Some(barren_plateau) = arch.properties.barren_plateau_score {
296            println!("     - Barren plateau risk: {barren_plateau:.3}");
297        }
298
299        println!();
300    }
301
302    // Performance trade-offs analysis
303    println!("   Performance trade-offs:");
304    println!("   - Deeper circuits: higher expressivity, more barren plateaus");
305    println!("   - More entanglement: better feature mixing, higher noise sensitivity");
306    println!("   - More parameters: greater capacity, overfitting risk");
307
308    Ok(())
309}
310
311/// Generate quantum-inspired synthetic data
312fn generate_quantum_data(samples: usize, features: usize) -> Array2<f64> {
313    Array2::from_shape_fn((samples, features), |(i, j)| {
314        let phase = (i as f64).mul_add(0.1, j as f64 * 0.2).sin();
315        let amplitude = (i as f64 / samples as f64).exp() * 0.5;
316        amplitude * phase + 0.1 * fastrand::f64()
317    })
318}
319
320/// Create custom search space for RL demo
321fn create_custom_search_space() -> SearchSpace {
322    SearchSpace {
323        layer_types: vec![
324            QNNLayerType::VariationalLayer { num_params: 4 },
325            QNNLayerType::VariationalLayer { num_params: 8 },
326            QNNLayerType::EntanglementLayer {
327                connectivity: "circular".to_string(),
328            },
329            QNNLayerType::EntanglementLayer {
330                connectivity: "linear".to_string(),
331            },
332        ],
333        depth_range: (1, 5),
334        qubit_constraints: QubitConstraints {
335            min_qubits: 3,
336            max_qubits: 6,
337            topology: Some(QuantumTopology::Ring),
338        },
339        param_ranges: vec![("variational_params".to_string(), (3, 12))]
340            .into_iter()
341            .collect(),
342        connectivity_patterns: vec!["linear".to_string(), "circular".to_string()],
343        measurement_bases: vec!["computational".to_string(), "Pauli-Z".to_string()],
344    }
345}
346
347/// Create search space optimized for DARTS
348fn create_darts_search_space() -> SearchSpace {
349    SearchSpace {
350        layer_types: vec![
351            QNNLayerType::VariationalLayer { num_params: 6 },
352            QNNLayerType::VariationalLayer { num_params: 9 },
353            QNNLayerType::EntanglementLayer {
354                connectivity: "full".to_string(),
355            },
356        ],
357        depth_range: (3, 6),
358        qubit_constraints: QubitConstraints {
359            min_qubits: 4,
360            max_qubits: 4, // Fixed for DARTS
361            topology: Some(QuantumTopology::Complete),
362        },
363        param_ranges: vec![("variational_params".to_string(), (6, 9))]
364            .into_iter()
365            .collect(),
366        connectivity_patterns: vec!["full".to_string()],
367        measurement_bases: vec!["computational".to_string()],
368    }
369}
370
371/// Create sample architectures for analysis
372fn create_sample_architectures() -> Vec<ArchitectureCandidate> {
373    vec![
374        // Simple architecture
375        ArchitectureCandidate {
376            id: "simple".to_string(),
377            layers: vec![
378                QNNLayerType::EncodingLayer { num_features: 4 },
379                QNNLayerType::VariationalLayer { num_params: 6 },
380                QNNLayerType::MeasurementLayer {
381                    measurement_basis: "computational".to_string(),
382                },
383            ],
384            num_qubits: 3,
385            metrics: ArchitectureMetrics {
386                accuracy: Some(0.65),
387                loss: Some(0.4),
388                circuit_depth: 3,
389                parameter_count: 6,
390                training_time: Some(10.0),
391                memory_usage: Some(512),
392                hardware_efficiency: Some(0.8),
393            },
394            properties: ArchitectureProperties {
395                expressivity: Some(0.3),
396                entanglement_capability: Some(0.2),
397                gradient_variance: Some(0.1),
398                barren_plateau_score: Some(0.2),
399                noise_resilience: Some(0.7),
400            },
401        },
402        // Complex architecture
403        ArchitectureCandidate {
404            id: "complex".to_string(),
405            layers: vec![
406                QNNLayerType::EncodingLayer { num_features: 6 },
407                QNNLayerType::VariationalLayer { num_params: 12 },
408                QNNLayerType::EntanglementLayer {
409                    connectivity: "full".to_string(),
410                },
411                QNNLayerType::VariationalLayer { num_params: 12 },
412                QNNLayerType::EntanglementLayer {
413                    connectivity: "circular".to_string(),
414                },
415                QNNLayerType::MeasurementLayer {
416                    measurement_basis: "Pauli-Z".to_string(),
417                },
418            ],
419            num_qubits: 6,
420            metrics: ArchitectureMetrics {
421                accuracy: Some(0.85),
422                loss: Some(0.2),
423                circuit_depth: 8,
424                parameter_count: 24,
425                training_time: Some(45.0),
426                memory_usage: Some(2048),
427                hardware_efficiency: Some(0.4),
428            },
429            properties: ArchitectureProperties {
430                expressivity: Some(0.8),
431                entanglement_capability: Some(0.9),
432                gradient_variance: Some(0.3),
433                barren_plateau_score: Some(0.7),
434                noise_resilience: Some(0.3),
435            },
436        },
437        // Balanced architecture
438        ArchitectureCandidate {
439            id: "balanced".to_string(),
440            layers: vec![
441                QNNLayerType::EncodingLayer { num_features: 4 },
442                QNNLayerType::VariationalLayer { num_params: 8 },
443                QNNLayerType::EntanglementLayer {
444                    connectivity: "circular".to_string(),
445                },
446                QNNLayerType::VariationalLayer { num_params: 8 },
447                QNNLayerType::MeasurementLayer {
448                    measurement_basis: "computational".to_string(),
449                },
450            ],
451            num_qubits: 4,
452            metrics: ArchitectureMetrics {
453                accuracy: Some(0.78),
454                loss: Some(0.28),
455                circuit_depth: 5,
456                parameter_count: 16,
457                training_time: Some(25.0),
458                memory_usage: Some(1024),
459                hardware_efficiency: Some(0.65),
460            },
461            properties: ArchitectureProperties {
462                expressivity: Some(0.6),
463                entanglement_capability: Some(0.5),
464                gradient_variance: Some(0.15),
465                barren_plateau_score: Some(0.4),
466                noise_resilience: Some(0.6),
467            },
468        },
469    ]
470}