1use crate::error::{OptimError, Result};
4use scirs2_core::ndarray::{Array1, Array2};
5use scirs2_core::numeric::{Float, ToPrimitive};
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::fmt::Debug;
9
10pub(crate) fn cast_scalar<T: Float, V: ToPrimitive + Copy + Debug>(value: V) -> Result<T> {
18 T::from(value).ok_or_else(|| {
19 OptimError::InvalidConfig(format!(
20 "{value:?} cannot be represented in this optimizer's scalar type"
21 ))
22 })
23}
24
25pub(crate) fn cast_positive<T: Float, V: ToPrimitive + Copy + Debug>(
29 value: V,
30 what: &str,
31) -> Result<T> {
32 let converted: T = cast_scalar(value)?;
33 if converted > T::zero() {
34 Ok(converted)
35 } else {
36 Err(OptimError::InsufficientData(format!(
37 "{what} must be positive, got {value:?}"
38 )))
39 }
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct LearnedOptimizerConfig {
45 pub learning_rate: f64,
47
48 pub meta_learning_rate: f64,
50
51 pub batch_size: usize,
53
54 pub max_steps: usize,
56
57 pub convergence_threshold: f64,
59
60 pub use_momentum: bool,
62
63 pub momentum_decay: f64,
65
66 pub weight_decay: f64,
68
69 pub hidden_size: usize,
71
72 pub attention_heads: usize,
74
75 pub gradient_history_size: usize,
77
78 pub input_features: usize,
80
81 pub output_features: usize,
83
84 pub num_layers: usize,
86
87 pub dropout_rate: f64,
89
90 pub use_attention: bool,
92
93 pub seed: Option<u64>,
95}
96
97impl Default for LearnedOptimizerConfig {
98 fn default() -> Self {
99 Self {
100 learning_rate: 0.001,
101 meta_learning_rate: 0.0001,
102 batch_size: 32,
103 max_steps: 1000,
104 convergence_threshold: 1e-6,
105 use_momentum: true,
106 momentum_decay: 0.9,
107 weight_decay: 1e-4,
108 hidden_size: 256,
109 attention_heads: 8,
110 gradient_history_size: 50,
111 input_features: 256,
112 output_features: 256,
113 num_layers: 3,
114 dropout_rate: 0.1,
115 use_attention: true,
116 seed: None,
117 }
118 }
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, Default)]
123pub enum MetaOptimizationStrategy {
124 #[default]
126 FirstOrder,
127
128 SecondOrder,
130
131 MAML,
133
134 Reptile,
136
137 Custom {
139 inner_steps: usize,
140 outer_learning_rate: f64,
141 },
142}
143
144#[derive(Debug, Clone)]
146pub struct OptimizerState<T: Float + Debug + Send + Sync + 'static> {
147 pub parameters: Array1<T>,
149
150 pub gradients: Array1<T>,
152
153 pub momentum: Option<Array1<T>>,
155
156 pub hidden_states: HashMap<String, Array1<T>>,
158
159 pub memory_buffers: HashMap<String, Array2<T>>,
161
162 pub step: usize,
164
165 pub step_count: usize,
167
168 pub loss: Option<T>,
170
171 pub learning_rate: T,
173
174 pub metadata: StateMetadata,
176}
177
178pub const DEFAULT_LEARNING_RATE: f64 = 0.001;
180
181impl<T: Float + Debug + Send + Sync + 'static> OptimizerState<T> {
182 pub fn new(num_params: usize) -> Result<Self> {
189 Ok(Self {
190 parameters: Array1::zeros(num_params),
191 gradients: Array1::zeros(num_params),
192 momentum: None,
193 hidden_states: HashMap::new(),
194 memory_buffers: HashMap::new(),
195 step: 0,
196 step_count: 0,
197 loss: None,
198 learning_rate: cast_scalar(DEFAULT_LEARNING_RATE)?,
199 metadata: StateMetadata::default(),
200 })
201 }
202}
203
204#[derive(Debug, Clone)]
206pub struct StateMetadata {
207 pub task_id: Option<String>,
209
210 pub optimizer_type: Option<String>,
212
213 pub version: String,
215
216 pub timestamp: std::time::SystemTime,
218
219 pub checksum: u64,
221
222 pub compression_level: u8,
224
225 pub custom_data: HashMap<String, String>,
227}
228
229impl Default for StateMetadata {
230 fn default() -> Self {
231 Self {
232 task_id: None,
233 optimizer_type: None,
234 version: "1.0".to_string(),
235 timestamp: std::time::SystemTime::now(),
236 checksum: 0,
237 compression_level: 0,
238 custom_data: HashMap::new(),
239 }
240 }
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
245pub enum NeuralOptimizerType {
246 Transformer,
248
249 LSTM,
251
252 MLP,
254
255 CNN,
257}
258
259#[derive(Debug, Clone)]
261pub struct TaskContext<T: Float + Debug + Send + Sync + 'static> {
262 pub task_id: String,
264
265 pub initial_parameters: Array1<T>,
267
268 pub task_data: Array2<T>,
270
271 pub targets: Array1<T>,
273
274 pub difficulty: f64,
276}
277
278#[derive(Debug, Clone)]
280pub struct NeuralOptimizerMetrics {
281 pub avg_loss: f64,
283
284 pub convergence_rate: f64,
286
287 pub steps_to_convergence: Option<usize>,
289
290 pub final_performance: f64,
292
293 pub training_time: f64,
295}
296
297#[derive(Debug, Clone)]
299pub struct TaskPerformance {
300 pub task_id: String,
302
303 pub score: f64,
305
306 pub converged: bool,
308
309 pub steps_taken: usize,
311
312 pub final_loss: f64,
314}