tensorlogic_train/optimizers/
lars.rs1use super::common::{compute_gradient_norm, GradClipMode, Optimizer, OptimizerConfig};
9use crate::{TrainError, TrainResult};
10use scirs2_core::ndarray::{Array, Ix2};
11use std::collections::HashMap;
12
13#[derive(Debug)]
20pub struct LarsOptimizer {
21 config: OptimizerConfig,
22 velocity: HashMap<String, Array<f64, Ix2>>,
24 trust_coef: f64,
26 exclude_bias: bool,
28}
29
30impl LarsOptimizer {
31 pub fn new(config: OptimizerConfig, trust_coef: f64, exclude_bias: bool) -> Self {
38 Self {
39 config,
40 velocity: HashMap::new(),
41 trust_coef,
42 exclude_bias,
43 }
44 }
45
46 fn clip_gradients(&self, gradients: &mut HashMap<String, Array<f64, Ix2>>) {
48 if let Some(clip_value) = self.config.grad_clip {
49 match self.config.grad_clip_mode {
50 GradClipMode::Value => {
51 for grad in gradients.values_mut() {
52 grad.mapv_inplace(|g| g.max(-clip_value).min(clip_value));
53 }
54 }
55 GradClipMode::Norm => {
56 let total_norm = compute_gradient_norm(gradients);
57 if total_norm > clip_value {
58 let scale = clip_value / total_norm;
59 for grad in gradients.values_mut() {
60 grad.mapv_inplace(|g| g * scale);
61 }
62 }
63 }
64 }
65 }
66 }
67
68 fn compute_adaptive_lr(
70 &self,
71 param: &Array<f64, Ix2>,
72 grad: &Array<f64, Ix2>,
73 name: &str,
74 ) -> f64 {
75 if self.exclude_bias && (name.contains("bias") || name.contains("b")) {
76 return self.config.learning_rate;
77 }
78 let param_norm: f64 = param.iter().map(|&p| p * p).sum::<f64>().sqrt();
79 let grad_norm: f64 = grad.iter().map(|&g| g * g).sum::<f64>().sqrt();
80 if param_norm == 0.0 || grad_norm == 0.0 {
81 return self.config.learning_rate;
82 }
83 let local_lr = self.trust_coef * param_norm / grad_norm;
84 self.config.learning_rate * local_lr
85 }
86}
87
88impl Optimizer for LarsOptimizer {
89 fn step(
90 &mut self,
91 parameters: &mut HashMap<String, Array<f64, Ix2>>,
92 gradients: &HashMap<String, Array<f64, Ix2>>,
93 ) -> TrainResult<()> {
94 let mut clipped_gradients = gradients.clone();
95 self.clip_gradients(&mut clipped_gradients);
96 for (name, param) in parameters.iter_mut() {
97 let grad = clipped_gradients.get(name).ok_or_else(|| {
98 TrainError::OptimizerError(format!("Missing gradient for parameter: {}", name))
99 })?;
100 let adaptive_lr = self.compute_adaptive_lr(param, grad, name);
101 let mut effective_grad = grad.clone();
102 if self.config.weight_decay > 0.0 {
103 effective_grad += &(&*param * self.config.weight_decay);
104 }
105 if !self.velocity.contains_key(name) {
106 self.velocity
107 .insert(name.clone(), Array::zeros(param.raw_dim()));
108 }
109 let velocity = self
110 .velocity
111 .get_mut(name)
112 .expect("velocity initialized for all parameters");
113 velocity.mapv_inplace(|v| self.config.momentum * v);
114 *velocity = &*velocity + &(effective_grad * adaptive_lr);
115 *param = &*param - &*velocity;
116 }
117 Ok(())
118 }
119
120 fn zero_grad(&mut self) {}
121
122 fn get_lr(&self) -> f64 {
123 self.config.learning_rate
124 }
125
126 fn set_lr(&mut self, lr: f64) {
127 self.config.learning_rate = lr;
128 }
129
130 fn state_dict(&self) -> HashMap<String, Vec<f64>> {
131 let mut state = HashMap::new();
132 state.insert("trust_coef".to_string(), vec![self.trust_coef]);
133 state.insert(
134 "exclude_bias".to_string(),
135 vec![if self.exclude_bias { 1.0 } else { 0.0 }],
136 );
137 for (name, velocity) in &self.velocity {
138 state.insert(
139 format!("velocity_{}", name),
140 velocity.iter().copied().collect(),
141 );
142 }
143 state
144 }
145
146 fn load_state_dict(&mut self, state: HashMap<String, Vec<f64>>) {
147 if let Some(trust) = state.get("trust_coef") {
148 self.trust_coef = trust[0];
149 }
150 if let Some(exclude) = state.get("exclude_bias") {
151 self.exclude_bias = exclude[0] > 0.5;
152 }
153 for (key, values) in state {
154 if let Some(name) = key.strip_prefix("velocity_") {
155 if let Some(velocity) = self.velocity.get(name) {
156 let shape = velocity.raw_dim();
157 if let Ok(arr) = Array::from_shape_vec(shape, values) {
158 self.velocity.insert(name.to_string(), arr);
159 }
160 }
161 }
162 }
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169 use scirs2_core::ndarray::array;
170
171 #[test]
172 fn test_lars_optimizer() {
173 let config = OptimizerConfig {
174 learning_rate: 0.1,
175 momentum: 0.9,
176 weight_decay: 0.0001,
177 ..Default::default()
178 };
179 let mut optimizer = LarsOptimizer::new(config, 0.001, true);
180 let mut params = HashMap::new();
181 params.insert("w".to_string(), array![[1.0, 2.0], [3.0, 4.0]]);
182 let mut grads = HashMap::new();
183 grads.insert("w".to_string(), array![[0.1, 0.1], [0.1, 0.1]]);
184 optimizer.step(&mut params, &grads).expect("unwrap");
185 let w = params.get("w").expect("unwrap");
186 assert!(w[[0, 0]] < 1.0);
187 assert!(w[[1, 1]] < 4.0);
188 let state = optimizer.state_dict();
189 assert!(state.contains_key("trust_coef"));
190 assert!(state.contains_key("exclude_bias"));
191 assert!(state.contains_key("velocity_w"));
192 }
193
194 #[test]
195 fn test_lars_bias_exclusion() {
196 let config = OptimizerConfig {
197 learning_rate: 0.1,
198 momentum: 0.9,
199 ..Default::default()
200 };
201 let mut optimizer = LarsOptimizer::new(config.clone(), 0.001, true);
202 let mut params = HashMap::new();
203 params.insert("weights".to_string(), array![[1.0, 2.0]]);
204 params.insert("bias".to_string(), array![[1.0, 2.0]]);
205 let mut grads = HashMap::new();
206 grads.insert("weights".to_string(), array![[0.1, 0.1]]);
207 grads.insert("bias".to_string(), array![[0.1, 0.1]]);
208 optimizer.step(&mut params, &grads).expect("unwrap");
209 let weights = params.get("weights").expect("unwrap");
210 let bias = params.get("bias").expect("unwrap");
211 assert!(weights[[0, 0]] < 1.0);
212 assert!(bias[[0, 0]] < 1.0);
213 }
214}