#[allow(dead_code)]
use scirs2_core::ndarray::{Array1, Array2, Array3};
use scirs2_core::numeric::Float;
use std::fmt::Debug;
use std::collections::{HashMap, HashSet, BTreeMap, VecDeque};
use crate::error::{OptimError, Result};
#[derive(Debug, Clone)]
pub struct SearchSpaceConfig<T: Float + Debug + Send + Sync + 'static> {
pub space_type: SearchSpaceType,
pub max_depth: usize,
pub max_operations_per_layer: usize,
pub allowed_operations: Vec<OperationDef<T>>,
pub connection_constraints: ConnectionConstraints,
pub resource_constraints: ResourceConstraints<T>,
pub domain_constraints: DomainConstraints<T>,
pub complexity_limits: ComplexityLimits<T>,
}
#[derive(Debug, Clone, Copy)]
pub enum SearchSpaceType {
Chain,
CellBased,
Hierarchical,
GraphBased,
Differentiable,
Macro,
Custom(String),
}
#[derive(Debug)]
pub struct SearchSpace<T: Float + Debug + Send + Sync + 'static> {
config: SearchSpaceConfig<T>,
operations: HashMap<String, OperationDef<T>>,
layers: HashMap<String, LayerDef<T>>,
connection_patterns: Vec<ConnectionPattern>,
space_graph: SearchSpaceGraph<T>,
constraint_checkers: Vec<Box<dyn ConstraintChecker<T>>>,
statistics: SearchSpaceStatistics<T>,
architecture_cache: HashMap<String, ArchitectureSample<T>>,
}
#[derive(Debug, Clone)]
pub struct OperationDef<T: Float + Debug + Send + Sync + 'static> {
pub id: String,
pub name: String,
pub op_type: OperationType,
pub parameter_space: ParameterSpace<T>,
pub computational_props: ComputationalProperties<T>,
pub compatibility: CompatibilityConstraints,
pub performance_chars: PerformanceCharacteristics<T>,
}
#[derive(Debug, Clone)]
pub enum OperationType {
Conv(ConvType),
Dense(DenseType),
Pool(PoolType),
Norm(NormType),
Activation(ActivationType),
Attention(AttentionType),
Recurrent(RecurrentType),
Skip(SkipType),
Custom(String, HashMap<String, String>),
}
#[derive(Debug, Clone)]
pub enum ConvType {
Standard,
Depthwise,
Separable,
Dilated,
Grouped,
Transposed,
}
#[derive(Debug, Clone)]
pub enum DenseType {
Standard,
Sparse,
LowRank,
Factorized,
}
#[derive(Debug, Clone)]
pub enum PoolType {
Max,
Average,
GlobalMax,
GlobalAverage,
Adaptive,
}
#[derive(Debug, Clone)]
pub enum NormType {
Batch,
Layer,
Instance,
Group,
LocalResponse,
}
#[derive(Debug, Clone)]
pub enum ActivationType {
ReLU, GELU, Swish, Tanh, Sigmoid, LeakyReLU, ELU, Mish,
}
#[derive(Debug, Clone)]
pub enum AttentionType {
SelfAttention,
MultiHead,
ScaledDotProduct,
Additive,
Spatial,
}
#[derive(Debug, Clone)]
pub enum RecurrentType {
LSTM, GRU, RNN, BiLSTM, BiGRU,
}
#[derive(Debug, Clone)]
pub enum SkipType {
Identity,
Zero,
Residual,
Dense,
}
#[derive(Debug, Clone)]
pub struct ParameterSpace<T: Float + Debug + Send + Sync + 'static> {
pub continuous_params: HashMap<String, ContinuousParam<T>>,
pub discrete_params: HashMap<String, DiscreteParam>,
pub categorical_params: HashMap<String, CategoricalParam>,
pub conditional_params: HashMap<String, ConditionalParam<T>>,
}
#[derive(Debug, Clone)]
pub struct ContinuousParam<T: Float + Debug + Send + Sync + 'static> {
pub name: String,
pub min_value: T,
pub max_value: T,
pub default_value: T,
pub distribution: DistributionType<T>,
pub scaling: ScalingType,
}
#[derive(Debug, Clone)]
pub struct DiscreteParam {
pub name: String,
pub values: Vec<i64>,
pub default_value: i64,
pub weights: Option<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct CategoricalParam {
pub name: String,
pub categories: Vec<String>,
pub default_category: String,
pub probabilities: Option<Vec<f64>>,
}
#[derive(Debug, Clone)]
pub struct ConditionalParam<T: Float + Debug + Send + Sync + 'static> {
pub name: String,
pub parent_param: String,
pub conditions: HashMap<String, ParameterSpace<T>>,
}
#[derive(Debug, Clone)]
pub enum DistributionType<T: Float + Debug + Send + Sync + 'static> {
Uniform,
Normal { mean: T, std: T },
LogUniform,
Beta { alpha: T, beta: T },
Gamma { shape: T, scale: T },
}
#[derive(Debug, Clone, Copy)]
pub enum ScalingType {
Linear,
Logarithmic,
Power(f64),
}
#[derive(Debug, Clone)]
pub struct ComputationalProperties<T: Float + Debug + Send + Sync + 'static> {
pub flops_estimator: FLOPSEstimator<T>,
pub memory_estimator: MemoryEstimator<T>,
pub latency_estimator: LatencyEstimator<T>,
pub parallelizability: T,
pub memory_pattern: MemoryAccessPattern,
}
#[derive(Debug, Clone)]
pub struct FLOPSEstimator<T: Float + Debug + Send + Sync + 'static> {
pub base_flops: u64,
pub scaling_factors: HashMap<String, T>,
pub estimator_type: EstimatorType,
}
#[derive(Debug, Clone)]
pub struct MemoryEstimator<T: Float + Debug + Send + Sync + 'static> {
pub base_memory: usize,
pub input_scaling: T,
pub param_overhead: T,
}
#[derive(Debug, Clone)]
pub struct LatencyEstimator<T: Float + Debug + Send + Sync + 'static> {
pub base_latency: T,
pub hardware_multipliers: HashMap<String, T>,
pub batch_scaling: T,
}
#[derive(Debug, Clone, Copy)]
pub enum EstimatorType {
Constant,
Linear,
Polynomial(u32),
Custom,
}
#[derive(Debug, Clone)]
pub enum MemoryAccessPattern {
Sequential,
Random,
Strided { stride: usize },
Blocked { block_size: usize },
}
#[derive(Debug, Clone)]
pub struct CompatibilityConstraints {
pub input_shape_constraints: Vec<ShapeConstraint>,
pub output_shape_constraints: Vec<ShapeConstraint>,
pub predecessor_constraints: Vec<String>,
pub successor_constraints: Vec<String>,
pub exclusion_constraints: Vec<String>,
}
#[derive(Debug, Clone)]
pub enum ShapeConstraint {
Fixed(Vec<usize>),
MinShape(Vec<usize>),
MaxShape(Vec<usize>),
Divisible { dim: usize, factor: usize },
Relationship {
relation: ShapeRelation,
target_dim: usize,
factor: f64,
},
}
#[derive(Debug, Clone, Copy)]
pub enum ShapeRelation {
Equal, GreaterThan, LessThan, Multiple, Divisor,
}
#[derive(Debug, Clone)]
pub struct PerformanceCharacteristics<T: Float + Debug + Send + Sync + 'static> {
pub accuracy_impact: T,
pub stability_impact: T,
pub convergence_impact: T,
pub generalization_impact: T,
pub efficiency_score: T,
}
#[derive(Debug, Clone)]
pub struct LayerDef<T: Float + Debug + Send + Sync + 'static> {
pub id: String,
pub layer_type: LayerType,
pub allowed_operations: Vec<String>,
pub constraints: LayerConstraints<T>,
pub repetition: RepetitionConstraints,
}
#[derive(Debug, Clone)]
pub enum LayerType {
Input,
FeatureExtraction,
Attention,
Normalization,
Activation,
Pooling,
Output,
Custom(String),
}
#[derive(Debug, Clone)]
pub struct LayerConstraints<T: Float + Debug + Send + Sync + 'static> {
pub max_operations: usize,
pub required_operations: Vec<String>,
pub optional_operations: Vec<String>,
pub resource_limits: ResourceConstraints<T>,
}
#[derive(Debug, Clone)]
pub struct RepetitionConstraints {
pub min_repeat: usize,
pub max_repeat: usize,
pub pattern: RepetitionPattern,
}
#[derive(Debug, Clone)]
pub enum RepetitionPattern {
Fixed(usize),
Variable,
Geometric { base: usize, ratio: f64 },
Arithmetic { start: usize, step: usize },
}
#[derive(Debug, Clone)]
pub struct ConnectionPattern {
pub id: String,
pub pattern_type: ConnectionPatternType,
pub source_constraints: Vec<NodeConstraint>,
pub target_constraints: Vec<NodeConstraint>,
pub weight: f64,
}
#[derive(Debug, Clone)]
pub enum ConnectionPatternType {
Sequential,
Skip { max_distance: usize },
Dense,
Random { probability: f64 },
Attention,
Custom(String),
}
#[derive(Debug, Clone)]
pub enum NodeConstraint {
NodeType(String),
LayerIndex(std::ops::Range<usize>),
OperationType(String),
ShapeCompatible,
}
#[derive(Debug, Clone)]
pub struct ConnectionConstraints {
pub max_input_degree: usize,
pub max_output_degree: usize,
pub forbidden_patterns: Vec<String>,
pub required_patterns: Vec<String>,
pub allow_cycles: bool,
}
#[derive(Debug, Clone)]
pub struct ResourceConstraints<T: Float + Debug + Send + Sync + 'static> {
pub max_parameters: Option<usize>,
pub max_flops: Option<u64>,
pub max_memory: Option<usize>,
pub max_latency: Option<T>,
pub max_energy: Option<T>,
pub hardware_constraints: HashMap<String, T>,
}
#[derive(Debug, Clone)]
pub struct DomainConstraints<T: Float + Debug + Send + Sync + 'static> {
pub task_constraints: TaskConstraints,
pub data_constraints: DataConstraints,
pub performance_requirements: PerformanceRequirements<T>,
pub regulatory_constraints: RegulatoryConstraints,
}
#[derive(Debug, Clone)]
pub struct TaskConstraints {
pub task_type: TaskType,
pub required_capabilities: Vec<String>,
pub prohibited_operations: Vec<String>,
pub preferred_patterns: Vec<String>,
}
#[derive(Debug, Clone)]
pub enum TaskType {
Classification, Regression, Detection, Segmentation,
Generation, Translation, Summarization, Custom(String),
}
#[derive(Debug, Clone)]
pub struct DataConstraints {
pub input_types: Vec<DataType>,
pub output_types: Vec<DataType>,
pub size_constraints: SizeConstraints,
pub privacy_requirements: PrivacyRequirements,
}
#[derive(Debug, Clone)]
pub enum DataType {
Image, Video, Audio, Text, Tabular, Graph, TimeSeries, Custom(String),
}
#[derive(Debug, Clone)]
pub struct SizeConstraints {
pub min_size: Vec<usize>,
pub max_size: Vec<usize>,
pub batch_constraints: (usize, usize), }
#[derive(Debug, Clone)]
pub struct PrivacyRequirements {
pub differential_privacy: bool,
pub federated_compatible: bool,
pub data_locality: bool,
pub encryption_required: bool,
}
#[derive(Debug, Clone)]
pub struct PerformanceRequirements<T: Float + Debug + Send + Sync + 'static> {
pub min_accuracy: Option<T>,
pub max_inference_time: Option<T>,
pub min_throughput: Option<T>,
pub real_time: bool,
}
#[derive(Debug, Clone)]
pub struct RegulatoryConstraints {
pub explainability_required: bool,
pub fairness_constraints: Vec<String>,
pub safety_requirements: Vec<String>,
pub compliance_standards: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ComplexityLimits<T: Float + Debug + Send + Sync + 'static> {
pub max_space_size: u64,
pub max_arch_complexity: T,
pub sampling_limits: SamplingLimits,
pub search_constraints: SearchConstraints<T>,
}
#[derive(Debug, Clone)]
pub struct SamplingLimits {
pub max_samples_per_iteration: usize,
pub max_total_samples: usize,
pub sampling_timeout: u32,
}
#[derive(Debug, Clone)]
pub struct SearchConstraints<T: Float + Debug + Send + Sync + 'static> {
pub max_search_depth: usize,
pub convergence_criteria: ConvergenceCriteria<T>,
pub early_stopping: EarlyStoppingConditions<T>,
}
#[derive(Debug, Clone)]
pub struct ConvergenceCriteria<T: Float + Debug + Send + Sync + 'static> {
pub improvement_threshold: T,
pub patience: usize,
pub min_iterations: usize,
pub max_iterations: usize,
}
#[derive(Debug, Clone)]
pub struct EarlyStoppingConditions<T: Float + Debug + Send + Sync + 'static> {
pub performance_threshold: Option<T>,
pub resource_threshold: Option<T>,
pub time_limit: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct SearchSpaceGraph<T: Float + Debug + Send + Sync + 'static> {
pub nodes: HashMap<String, GraphNode<T>>,
pub edges: HashMap<String, GraphEdge<T>>,
pub adjacency: HashMap<String, Vec<String>>,
pub properties: GraphProperties<T>,
}
#[derive(Debug, Clone)]
pub struct GraphNode<T: Float + Debug + Send + Sync + 'static> {
pub id: String,
pub node_type: String,
pub features: HashMap<String, T>,
pub constraints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct GraphEdge<T: Float + Debug + Send + Sync + 'static> {
pub id: String,
pub source: String,
pub target: String,
pub weight: T,
pub edge_type: String,
}
#[derive(Debug, Clone)]
pub struct GraphProperties<T: Float + Debug + Send + Sync + 'static> {
pub num_nodes: usize,
pub num_edges: usize,
pub density: T,
pub clustering_coefficient: T,
pub diameter: usize,
}
pub trait ConstraintChecker<T: Float + Debug + Send + Sync + 'static> {
fn check(&self, architecture: &ArchitectureSample<T>) -> Result<bool>;
fn get_violations(&self, architecture: &ArchitectureSample<T>) -> Result<Vec<ConstraintViolation>>;
fn get_severity(&self) -> ConstraintSeverity;
}
#[derive(Debug, Clone)]
pub struct ConstraintViolation {
pub constraint_type: String,
pub description: String,
pub severity: ConstraintSeverity,
pub suggested_fix: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConstraintSeverity {
Info, Warning, Error, Critical,
}
#[derive(Debug, Clone)]
pub struct SearchSpaceStatistics<T: Float + Debug + Send + Sync + 'static> {
pub total_architectures: u64,
pub sampled_count: usize,
pub valid_count: usize,
pub avg_complexity: T,
pub complexity_distribution: HashMap<String, usize>,
pub operation_usage: HashMap<String, usize>,
}
#[derive(Debug, Clone)]
pub struct ArchitectureSample<T: Float + Debug + Send + Sync + 'static> {
pub id: String,
pub architecture: Vec<String>,
pub parameters: HashMap<String, T>,
pub is_valid: bool,
pub complexity: T,
pub estimated_performance: HashMap<String, T>,
pub metadata: SamplingMetadata,
}
#[derive(Debug, Clone)]
pub struct SamplingMetadata {
pub sampling_method: String,
pub timestamp: u64,
pub parameters: HashMap<String, String>,
pub parents: Vec<String>,
}
impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> SearchSpace<T> {
pub fn new(config: SearchSpaceConfig<T>) -> Result<Self> {
let mut space = Self {
config: config.clone(),
operations: HashMap::new(),
layers: HashMap::new(),
connection_patterns: Vec::new(),
space_graph: SearchSpaceGraph::new(),
constraint_checkers: Vec::new(),
statistics: SearchSpaceStatistics::new(),
architecture_cache: HashMap::new(),
};
space.initialize_operations()?;
space.initialize_layers()?;
space.initialize_connections()?;
space.initialize_constraints()?;
space.compute_statistics()?;
Ok(space)
}
fn initialize_operations(&mut self) -> Result<()> {
for op_def in &self.config.allowed_operations {
self.operations.insert(op_def.id.clone(), op_def.clone());
}
Ok(())
}
fn initialize_layers(&mut self) -> Result<()> {
let layer_types = vec![
("input", LayerType::Input),
("feature", LayerType::FeatureExtraction),
("attention", LayerType::Attention),
("norm", LayerType::Normalization),
("output", LayerType::Output),
];
for (layer_id, layer_type) in layer_types {
let layer_def = LayerDef {
id: layer_id.to_string(),
layer_type,
allowed_operations: self.operations.keys().cloned().collect(),
constraints: LayerConstraints {
max_operations: self.config.max_operations_per_layer,
required_operations: Vec::new(),
optional_operations: self.operations.keys().cloned().collect(),
resource_limits: self.config.resource_constraints.clone(),
},
repetition: RepetitionConstraints {
min_repeat: 1,
max_repeat: 5,
pattern: RepetitionPattern::Variable,
},
};
self.layers.insert(layer_id.to_string(), layer_def);
}
Ok(())
}
fn initialize_connections(&mut self) -> Result<()> {
self.connection_patterns.push(ConnectionPattern {
id: "sequential".to_string(),
pattern_type: ConnectionPatternType::Sequential,
source_constraints: Vec::new(),
target_constraints: Vec::new(),
weight: 1.0,
});
self.connection_patterns.push(ConnectionPattern {
id: "skip".to_string(),
pattern_type: ConnectionPatternType::Skip { max_distance: 3 },
source_constraints: Vec::new(),
target_constraints: Vec::new(),
weight: 0.3,
});
Ok(())
}
fn initialize_constraints(&mut self) -> Result<()> {
self.constraint_checkers.push(Box::new(ResourceConstraintChecker::new(
self.config.resource_constraints.clone()
)));
self.constraint_checkers.push(Box::new(CompatibilityConstraintChecker::new(
self.operations.clone()
)));
Ok(())
}
pub fn sample_architecture(&mut self, method: &str) -> Result<ArchitectureSample<T>> {
match method {
"random" => self.sample_random_architecture(),
"uniform" => self.sample_uniform_architecture(),
"guided" => self.sample_guided_architecture(),
_ => Err(OptimError::InvalidInput(
format!("Unknown sampling method: {}", method)
))
}
}
fn sample_random_architecture(&mut self) -> Result<ArchitectureSample<T>> {
use scirs2_core::random::Rng;
let mut rng = scirs2_core::random::thread_rng();
let num_ops = rng.gen_range(1..=self.config.max_depth);
let mut architecture = Vec::new();
let mut parameters = HashMap::new();
for i in 0..num_ops {
let op_names: Vec<&String> = self.operations.keys().collect();
let op_name = op_names[rng.gen_range(0..op_names.len())];
architecture.push(op_name.clone());
if let Some(op_def) = self.operations.get(op_name) {
for (param_name, continuous_param) in &op_def.parameter_space.continuous_params {
let value = match continuous_param.distribution {
DistributionType::Uniform => {
let range = continuous_param.max_value - continuous_param.min_value;
continuous_param.min_value + T::from(rng.random::<f64>()).expect("unwrap failed") * range
}
_ => continuous_param.default_value,
};
parameters.insert(format!("{}_{}", i, param_name), value);
}
}
}
let sample = ArchitectureSample {
id: format!("sample_{}", scirs2_core::random::random::<u64>()),
architecture,
parameters,
is_valid: true, complexity: scirs2_core::numeric::NumCast::from(num_ops as f64).unwrap_or_else(|| T::zero()),
estimated_performance: HashMap::new(),
metadata: SamplingMetadata {
sampling_method: "random".to_string(),
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
parameters: HashMap::new(),
parents: Vec::new(),
},
};
let is_valid = self.validate_architecture(&sample)?;
let mut validated_sample = sample;
validated_sample.is_valid = is_valid;
self.architecture_cache.insert(validated_sample.id.clone(), validated_sample.clone());
Ok(validated_sample)
}
fn sample_uniform_architecture(&self) -> Result<ArchitectureSample<T>> {
self.sample_random_architecture()
}
fn sample_guided_architecture(&self) -> Result<ArchitectureSample<T>> {
self.sample_random_architecture()
}
pub fn validate_architecture(&self, architecture: &ArchitectureSample<T>) -> Result<bool> {
for checker in &self.constraint_checkers {
if !checker.check(architecture)? {
return Ok(false);
}
}
Ok(true)
}
pub fn get_constraint_violations(&self, architecture: &ArchitectureSample<T>) -> Result<Vec<ConstraintViolation>> {
let mut violations = Vec::new();
for checker in &self.constraint_checkers {
violations.extend(checker.get_violations(architecture)?);
}
Ok(violations)
}
fn compute_statistics(&mut self) -> Result<()> {
self.statistics.total_architectures = 1000000; self.statistics.avg_complexity = scirs2_core::numeric::NumCast::from(5.0).unwrap_or_else(|| T::zero());
Ok(())
}
pub fn get_space_size(&self) -> u64 {
self.statistics.total_architectures
}
pub fn get_operations(&self) -> &HashMap<String, OperationDef<T>> {
&self.operations
}
pub fn get_layers(&self) -> &HashMap<String, LayerDef<T>> {
&self.layers
}
pub fn get_connection_patterns(&self) -> &[ConnectionPattern] {
&self.connection_patterns
}
pub fn get_cached_architectures(&self) -> &HashMap<String, ArchitectureSample<T>> {
&self.architecture_cache
}
}
#[derive(Debug)]
pub struct ResourceConstraintChecker<T: Float + Debug + Send + Sync + 'static> {
constraints: ResourceConstraints<T>,
}
impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> ResourceConstraintChecker<T> {
pub fn new(constraints: ResourceConstraints<T>) -> Self {
Self { constraints }
}
}
impl<T: Float + Debug + Send + Sync + 'static> ConstraintChecker<T> for ResourceConstraintChecker<T> {
fn check(&self, architecture: &ArchitectureSample<T>) -> Result<bool> {
if let Some(max_params) = self.constraints.max_parameters {
let param_count = architecture.parameters.len();
if param_count > max_params {
return Ok(false);
}
}
if let Some(max_flops) = self.constraints.max_flops {
let estimated_flops = architecture.complexity.to_f64().unwrap_or(0.0) * 1000000.0; if estimated_flops > max_flops as f64 {
return Ok(false);
}
}
Ok(true)
}
fn get_violations(&self, architecture: &ArchitectureSample<T>) -> Result<Vec<ConstraintViolation>> {
let mut violations = Vec::new();
if let Some(max_params) = self.constraints.max_parameters {
let param_count = architecture.parameters.len();
if param_count > max_params {
violations.push(ConstraintViolation {
constraint_type: "resource".to_string(),
description: format!("Parameter count {} exceeds maximum {}", param_count, max_params),
severity: ConstraintSeverity::Error,
suggested_fix: Some("Reduce architecture complexity".to_string()),
});
}
}
Ok(violations)
}
fn get_severity(&self) -> ConstraintSeverity {
ConstraintSeverity::Error
}
}
#[derive(Debug)]
pub struct CompatibilityConstraintChecker<T: Float + Debug + Send + Sync + 'static> {
operations: HashMap<String, OperationDef<T>>,
}
impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> CompatibilityConstraintChecker<T> {
pub fn new(operations: HashMap<String, OperationDef<T>>) -> Self {
Self { operations }
}
}
impl<T: Float + Debug + Send + Sync + 'static> ConstraintChecker<T> for CompatibilityConstraintChecker<T> {
fn check(&self, architecture: &ArchitectureSample<T>) -> Result<bool> {
for op_name in &architecture.architecture {
if !self.operations.contains_key(op_name) {
return Ok(false);
}
}
Ok(true)
}
fn get_violations(&self, architecture: &ArchitectureSample<T>) -> Result<Vec<ConstraintViolation>> {
let mut violations = Vec::new();
for op_name in &architecture.architecture {
if !self.operations.contains_key(op_name) {
violations.push(ConstraintViolation {
constraint_type: "compatibility".to_string(),
description: format!("Unknown operation: {}", op_name),
severity: ConstraintSeverity::Critical,
suggested_fix: Some("Replace with valid operation".to_string()),
});
}
}
Ok(violations)
}
fn get_severity(&self) -> ConstraintSeverity {
ConstraintSeverity::Critical
}
}
impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> SearchSpaceGraph<T> {
fn new() -> Self {
Self {
nodes: HashMap::new(),
edges: HashMap::new(),
adjacency: HashMap::new(),
properties: GraphProperties {
num_nodes: 0,
num_edges: 0,
density: T::zero(),
clustering_coefficient: T::zero(),
diameter: 0,
},
}
}
}
impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> SearchSpaceStatistics<T> {
fn new() -> Self {
Self {
total_architectures: 0,
sampled_count: 0,
valid_count: 0,
avg_complexity: T::zero(),
complexity_distribution: HashMap::new(),
operation_usage: HashMap::new(),
}
}
}
impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> Default for SearchSpaceConfig<T> {
fn default() -> Self {
Self {
space_type: SearchSpaceType::Chain,
max_depth: 10,
max_operations_per_layer: 5,
allowed_operations: vec![
OperationDef {
id: "conv2d".to_string(),
name: "2D Convolution".to_string(),
op_type: OperationType::Conv(ConvType::Standard),
parameter_space: ParameterSpace {
continuous_params: HashMap::new(),
discrete_params: HashMap::new(),
categorical_params: HashMap::new(),
conditional_params: HashMap::new(),
},
computational_props: ComputationalProperties {
flops_estimator: FLOPSEstimator {
base_flops: 1000000,
scaling_factors: HashMap::new(),
estimator_type: EstimatorType::Linear,
},
memory_estimator: MemoryEstimator {
base_memory: 1024,
input_scaling: T::one(),
param_overhead: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),
},
latency_estimator: LatencyEstimator {
base_latency: scirs2_core::numeric::NumCast::from(10.0).unwrap_or_else(|| T::zero()),
hardware_multipliers: HashMap::new(),
batch_scaling: scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero()),
},
parallelizability: scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero()),
memory_pattern: MemoryAccessPattern::Sequential,
},
compatibility: CompatibilityConstraints {
input_shape_constraints: Vec::new(),
output_shape_constraints: Vec::new(),
predecessor_constraints: Vec::new(),
successor_constraints: Vec::new(),
exclusion_constraints: Vec::new(),
},
performance_chars: PerformanceCharacteristics {
accuracy_impact: scirs2_core::numeric::NumCast::from(0.7).unwrap_or_else(|| T::zero()),
stability_impact: scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero()),
convergence_impact: scirs2_core::numeric::NumCast::from(0.6).unwrap_or_else(|| T::zero()),
generalization_impact: scirs2_core::numeric::NumCast::from(0.7).unwrap_or_else(|| T::zero()),
efficiency_score: scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero()),
},
},
],
connection_constraints: ConnectionConstraints {
max_input_degree: 5,
max_output_degree: 5,
forbidden_patterns: Vec::new(),
required_patterns: Vec::new(),
allow_cycles: false,
},
resource_constraints: ResourceConstraints {
max_parameters: Some(10_000_000),
max_flops: Some(1_000_000_000),
max_memory: Some(1_000_000_000), max_latency: Some(scirs2_core::numeric::NumCast::from(100.0).unwrap_or_else(|| T::zero())), max_energy: Some(scirs2_core::numeric::NumCast::from(1.0).unwrap_or_else(|| T::zero())), hardware_constraints: HashMap::new(),
},
domain_constraints: DomainConstraints {
task_constraints: TaskConstraints {
task_type: TaskType::Classification,
required_capabilities: Vec::new(),
prohibited_operations: Vec::new(),
preferred_patterns: Vec::new(),
},
data_constraints: DataConstraints {
input_types: vec![DataType::Image],
output_types: vec![DataType::Tabular],
size_constraints: SizeConstraints {
min_size: vec![224, 224, 3],
max_size: vec![1024, 1024, 3],
batch_constraints: (1, 128),
},
privacy_requirements: PrivacyRequirements {
differential_privacy: false,
federated_compatible: false,
data_locality: false,
encryption_required: false,
},
},
performance_requirements: PerformanceRequirements {
min_accuracy: Some(scirs2_core::numeric::NumCast::from(0.9).unwrap_or_else(|| T::zero())),
max_inference_time: Some(scirs2_core::numeric::NumCast::from(100.0).unwrap_or_else(|| T::zero())),
min_throughput: Some(scirs2_core::numeric::NumCast::from(10.0).unwrap_or_else(|| T::zero())),
real_time: false,
},
regulatory_constraints: RegulatoryConstraints {
explainability_required: false,
fairness_constraints: Vec::new(),
safety_requirements: Vec::new(),
compliance_standards: Vec::new(),
},
},
complexity_limits: ComplexityLimits {
max_space_size: 1_000_000_000,
max_arch_complexity: scirs2_core::numeric::NumCast::from(100.0).unwrap_or_else(|| T::zero()),
sampling_limits: SamplingLimits {
max_samples_per_iteration: 100,
max_total_samples: 10000,
sampling_timeout: 3600, },
search_constraints: SearchConstraints {
max_search_depth: 100,
convergence_criteria: ConvergenceCriteria {
improvement_threshold: scirs2_core::numeric::NumCast::from(0.001).unwrap_or_else(|| T::zero()),
patience: 10,
min_iterations: 5,
max_iterations: 1000,
},
early_stopping: EarlyStoppingConditions {
performance_threshold: Some(scirs2_core::numeric::NumCast::from(0.95).unwrap_or_else(|| T::zero())),
resource_threshold: Some(scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero())),
time_limit: Some(7200), },
},
},
}
}
}