pub mod attention_optimizer;
pub mod cv_optimizer;
pub mod nlp_optimizer;
pub use attention_optimizer::AttentionOptimizer;
pub use cv_optimizer::CVOptimizer;
pub use nlp_optimizer::NLPOptimizer;
use crate::error::Result;
use scirs2_core::ndarray::Array1;
use scirs2_core::numeric::Float;
use std::fmt::Debug;
#[derive(Debug, Clone)]
pub struct OptimizerStateInfo<T: Float + Debug + Send + Sync + 'static> {
pub step_count: usize,
pub current_lr: T,
pub grad_norm_ema: T,
}
pub trait AdvancedOptimizer<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
fn step(&mut self, params: &Array1<T>, gradients: &Array1<T>) -> Result<Array1<T>>;
fn get_learning_rate(&self) -> T;
fn set_learning_rate(&mut self, lr: T);
fn name(&self) -> &str;
fn get_state(&self) -> OptimizerStateInfo<T>;
}
pub(crate) fn l2_norm<T: Float + Debug + Send + Sync + 'static>(arr: &Array1<T>) -> T {
let sum_sq = arr.iter().fold(T::zero(), |acc, &x| acc + x * x);
sum_sq.sqrt()
}
pub(crate) fn clip_grad_norm<T: Float + Debug + Send + Sync + 'static>(
grad: &Array1<T>,
max_norm: T,
) -> Array1<T> {
let norm = l2_norm(grad);
if norm > max_norm && norm > T::zero() {
let scale = max_norm / norm;
grad.mapv(|g| g * scale)
} else {
grad.clone()
}
}