torsh-optim 0.1.3

Optimization algorithms for ToRSh with PyTorch-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Robustness features for optimizers
//!
//! This module provides tools for making optimizers more robust to various
//! forms of adversarial perturbations, noisy gradients, and training instabilities.
//! It includes implementations of robust optimization techniques and defensive
//! training strategies.

use crate::{OptimizerError, OptimizerResult};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::ops::Add;
use torsh_tensor::Tensor;

/// Configuration for robust optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RobustnessConfig {
    /// Enable gradient clipping for stability
    pub gradient_clipping: bool,
    /// Maximum gradient norm for clipping
    pub max_gradient_norm: f32,
    /// Enable outlier detection and filtering
    pub outlier_detection: bool,
    /// Z-score threshold for outlier detection
    pub outlier_threshold: f32,
    /// Enable smooth gradient aggregation
    pub smooth_aggregation: bool,
    /// Smoothing factor for gradient aggregation
    pub smoothing_factor: f32,
    /// Enable adversarial training support
    pub adversarial_training: bool,
    /// Perturbation budget for adversarial examples
    pub perturbation_budget: f32,
    /// Number of adversarial steps
    pub adversarial_steps: usize,
}

impl Default for RobustnessConfig {
    fn default() -> Self {
        Self {
            gradient_clipping: true,
            max_gradient_norm: 1.0,
            outlier_detection: true,
            outlier_threshold: 3.0,
            smooth_aggregation: true,
            smoothing_factor: 0.1,
            adversarial_training: false,
            perturbation_budget: 0.01,
            adversarial_steps: 1,
        }
    }
}

/// Statistics for robustness monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RobustnessStats {
    /// Number of gradients processed
    pub total_gradients: usize,
    /// Number of gradients clipped
    pub clipped_gradients: usize,
    /// Number of outliers detected
    pub outliers_detected: usize,
    /// Average gradient norm
    pub avg_gradient_norm: f32,
    /// Maximum gradient norm observed
    pub max_gradient_norm: f32,
    /// Gradient variance over time
    pub gradient_variance: f32,
    /// Stability score (0-1, higher is more stable)
    pub stability_score: f32,
}

impl RobustnessStats {
    pub fn new() -> Self {
        Self {
            total_gradients: 0,
            clipped_gradients: 0,
            outliers_detected: 0,
            avg_gradient_norm: 0.0,
            max_gradient_norm: 0.0,
            gradient_variance: 0.0,
            stability_score: 1.0,
        }
    }

    pub fn clipping_rate(&self) -> f32 {
        if self.total_gradients == 0 {
            0.0
        } else {
            self.clipped_gradients as f32 / self.total_gradients as f32
        }
    }

    pub fn outlier_rate(&self) -> f32 {
        if self.total_gradients == 0 {
            0.0
        } else {
            self.outliers_detected as f32 / self.total_gradients as f32
        }
    }
}

/// Gradient history for analysis
#[derive(Debug, Clone)]
struct GradientHistory {
    norms: VecDeque<f32>,
    window_size: usize,
}

impl GradientHistory {
    fn new(window_size: usize) -> Self {
        Self {
            norms: VecDeque::new(),
            window_size,
        }
    }

    fn add(&mut self, norm: f32) {
        self.norms.push_back(norm);
        if self.norms.len() > self.window_size {
            self.norms.pop_front();
        }
    }

    fn mean(&self) -> f32 {
        if self.norms.is_empty() {
            0.0
        } else {
            self.norms.iter().sum::<f32>() / self.norms.len() as f32
        }
    }

    fn variance(&self) -> f32 {
        if self.norms.len() < 2 {
            0.0
        } else {
            let mean = self.mean();
            let sum_sq_diff: f32 = self.norms.iter().map(|x| (x - mean).powi(2)).sum();
            sum_sq_diff / (self.norms.len() - 1) as f32
        }
    }

    fn std_dev(&self) -> f32 {
        self.variance().sqrt()
    }
}

/// Robustness manager for optimizers
pub struct RobustnessManager {
    config: RobustnessConfig,
    stats: RobustnessStats,
    gradient_history: HashMap<String, GradientHistory>,
    smoothed_gradients: HashMap<String, Tensor>,
}

impl RobustnessManager {
    pub fn new(config: RobustnessConfig) -> Self {
        Self {
            config,
            stats: RobustnessStats::new(),
            gradient_history: HashMap::new(),
            smoothed_gradients: HashMap::new(),
        }
    }

    /// Apply robustness transformations to gradients
    pub fn process_gradients(
        &mut self,
        gradients: &HashMap<String, Tensor>,
    ) -> OptimizerResult<HashMap<String, Tensor>> {
        let mut processed_gradients = HashMap::new();

        for (param_name, gradient) in gradients {
            let mut processed_grad = gradient.clone();

            // Step 1: Outlier detection and filtering
            if self.config.outlier_detection {
                if self.is_outlier(param_name, &processed_grad)? {
                    self.stats.outliers_detected += 1;
                    processed_grad = self.filter_outlier(param_name, &processed_grad)?;
                }
            }

            // Step 2: Gradient clipping
            if self.config.gradient_clipping {
                processed_grad = self.clip_gradient(&processed_grad)?;
            }

            // Step 3: Smooth aggregation
            if self.config.smooth_aggregation {
                processed_grad = self.smooth_gradient(param_name, &processed_grad)?;
            }

            // Update statistics
            self.update_statistics(param_name, &processed_grad)?;
            processed_gradients.insert(param_name.clone(), processed_grad);
        }

        Ok(processed_gradients)
    }

    /// Check if gradient is an outlier
    fn is_outlier(&mut self, param_name: &str, gradient: &Tensor) -> OptimizerResult<bool> {
        let grad_norm = gradient.norm()?.item()?;

        let history = self
            .gradient_history
            .entry(param_name.to_string())
            .or_insert_with(|| GradientHistory::new(100));

        if history.norms.len() < 10 {
            // Not enough history, assume not an outlier
            history.add(grad_norm);
            return Ok(false);
        }

        let mean = history.mean();
        let std_dev = history.std_dev();

        if std_dev < 1e-8 {
            // Gradients are essentially constant, not an outlier
            history.add(grad_norm);
            return Ok(false);
        }

        let z_score = (grad_norm - mean).abs() / std_dev;
        let is_outlier = z_score > self.config.outlier_threshold;

        if !is_outlier {
            history.add(grad_norm);
        }

        Ok(is_outlier)
    }

    /// Filter outlier gradients
    fn filter_outlier(&self, param_name: &str, gradient: &Tensor) -> OptimizerResult<Tensor> {
        if let Some(history) = self.gradient_history.get(param_name) {
            let mean_norm = history.mean();
            let current_norm = gradient.norm()?.item()?;

            if current_norm > 1e-8 {
                // Scale down to mean norm
                let scale_factor = mean_norm / current_norm;
                return Ok(gradient.mul_scalar(scale_factor)?);
            }
        }

        // Fallback: return zero gradient
        Ok(gradient.zeros_like()?)
    }

    /// Clip gradients to maximum norm
    fn clip_gradient(&mut self, gradient: &Tensor) -> OptimizerResult<Tensor> {
        let grad_norm = gradient.norm()?.item()?;

        if grad_norm > self.config.max_gradient_norm {
            self.stats.clipped_gradients += 1;
            let scale_factor = self.config.max_gradient_norm / grad_norm;
            Ok(gradient.mul_scalar(scale_factor)?)
        } else {
            Ok(gradient.clone())
        }
    }

    /// Apply smooth aggregation to gradients
    fn smooth_gradient(&mut self, param_name: &str, gradient: &Tensor) -> OptimizerResult<Tensor> {
        let alpha = self.config.smoothing_factor;

        match self.smoothed_gradients.get(param_name) {
            Some(prev_smoothed) => {
                // Exponential moving average: smoothed = alpha * new + (1 - alpha) * prev
                let new_contribution = gradient.mul_scalar(alpha)?;
                let prev_contribution = prev_smoothed.mul_scalar(1.0 - alpha)?;
                let smoothed = new_contribution.add(&prev_contribution)?;

                self.smoothed_gradients
                    .insert(param_name.to_string(), smoothed.clone());
                Ok(smoothed)
            }
            None => {
                // First gradient, use as-is
                self.smoothed_gradients
                    .insert(param_name.to_string(), gradient.clone());
                Ok(gradient.clone())
            }
        }
    }

    /// Update robustness statistics
    fn update_statistics(&mut self, param_name: &str, gradient: &Tensor) -> OptimizerResult<()> {
        let grad_norm = gradient.norm()?.item()?;

        self.stats.total_gradients += 1;
        self.stats.max_gradient_norm = self.stats.max_gradient_norm.max(grad_norm);

        // Update average gradient norm
        let prev_avg = self.stats.avg_gradient_norm;
        let n = self.stats.total_gradients as f32;
        self.stats.avg_gradient_norm = (prev_avg * (n - 1.0) + grad_norm) / n;

        // Update gradient variance
        if let Some(history) = self.gradient_history.get(param_name) {
            self.stats.gradient_variance = history.variance();
        }

        // Update stability score (inverse of coefficient of variation)
        if self.stats.avg_gradient_norm > 1e-8 {
            let cv = self.stats.gradient_variance.sqrt() / self.stats.avg_gradient_norm;
            self.stats.stability_score = 1.0 / (1.0 + cv);
        }

        Ok(())
    }

    /// Generate adversarial perturbations for robust training
    pub fn generate_adversarial_perturbation(
        &self,
        input: &Tensor,
        gradient: &Tensor,
    ) -> OptimizerResult<Tensor> {
        if !self.config.adversarial_training {
            return Ok(input.zeros_like()?);
        }

        let grad_norm = gradient.norm()?.item()?;
        if grad_norm < 1e-8 {
            return Ok(input.zeros_like()?);
        }

        // Generate perturbation in direction of gradient (FGSM-style)
        let perturbation_direction = gradient.div_scalar(grad_norm)?;
        let perturbation = perturbation_direction.mul_scalar(self.config.perturbation_budget)?;

        Ok(perturbation)
    }

    /// Get current robustness statistics
    pub fn get_stats(&self) -> &RobustnessStats {
        &self.stats
    }

    /// Reset statistics
    pub fn reset_stats(&mut self) {
        self.stats = RobustnessStats::new();
        self.gradient_history.clear();
        self.smoothed_gradients.clear();
    }

    /// Check if training appears stable
    pub fn is_training_stable(&self) -> bool {
        self.stats.stability_score > 0.5
            && self.stats.clipping_rate() < 0.3
            && self.stats.outlier_rate() < 0.1
    }

    /// Get recommendations for improving robustness
    pub fn get_recommendations(&self) -> Vec<String> {
        let mut recommendations = Vec::new();

        if self.stats.clipping_rate() > 0.5 {
            recommendations
                .push("Consider reducing learning rate - high gradient clipping rate".to_string());
        }

        if self.stats.outlier_rate() > 0.2 {
            recommendations.push(
                "High outlier rate detected - consider data cleaning or regularization".to_string(),
            );
        }

        if self.stats.stability_score < 0.3 {
            recommendations
                .push("Low stability score - consider increasing smoothing factor".to_string());
        }

        if self.stats.gradient_variance > self.stats.avg_gradient_norm.powi(2) {
            recommendations.push(
                "High gradient variance - consider batch normalization or different architecture"
                    .to_string(),
            );
        }

        if recommendations.is_empty() {
            recommendations.push("Training appears stable and robust".to_string());
        }

        recommendations
    }
}

/// Trait for robust optimizers
pub trait RobustOptimizer {
    /// Enable robustness features
    fn enable_robustness(&mut self, config: RobustnessConfig);

    /// Get robustness statistics
    fn robustness_stats(&self) -> Option<&RobustnessStats>;

    /// Check if training is stable
    fn is_stable(&self) -> bool;
}

#[cfg(test)]
mod tests {
    use super::*;
    use torsh_tensor::creation::randn;

    #[test]
    fn test_robustness_config_default() {
        let config = RobustnessConfig::default();
        assert!(config.gradient_clipping);
        assert_eq!(config.max_gradient_norm, 1.0);
    }

    #[test]
    fn test_robustness_manager_creation() {
        let config = RobustnessConfig::default();
        let manager = RobustnessManager::new(config);
        assert_eq!(manager.stats.total_gradients, 0);
    }

    #[test]
    fn test_gradient_clipping() -> OptimizerResult<()> {
        let config = RobustnessConfig {
            max_gradient_norm: 1.0,
            gradient_clipping: true,
            ..Default::default()
        };
        let mut manager = RobustnessManager::new(config);

        let large_gradient = randn::<f32>(&[2, 2]).unwrap().mul_scalar(10.0).unwrap();
        let clipped = manager.clip_gradient(&large_gradient).unwrap();

        let clipped_norm = clipped.norm().unwrap().to_vec()?[0];
        assert!(clipped_norm <= 1.0 + 1e-6);

        Ok(())
    }

    #[test]
    fn test_gradient_smoothing() -> OptimizerResult<()> {
        let config = RobustnessConfig {
            smooth_aggregation: true,
            smoothing_factor: 0.5,
            ..Default::default()
        };
        let mut manager = RobustnessManager::new(config);

        let grad1 = randn::<f32>(&[2, 2]).unwrap();
        let grad2 = randn::<f32>(&[2, 2]).unwrap();

        let smoothed1 = manager.smooth_gradient("param1", &grad1).unwrap();
        let smoothed2 = manager.smooth_gradient("param1", &grad2).unwrap();

        // First gradient should be unchanged
        assert_eq!(smoothed1.data()?, grad1.data()?);

        // Second should be blend
        let expected = grad2
            .mul_scalar(0.5)
            .unwrap()
            .add(&grad1.mul_scalar(0.5).unwrap())
            .unwrap();
        let diff = smoothed2.sub(&expected).unwrap().norm().unwrap().item()?;
        assert!(diff < 1e-6);
        Ok(())
    }

    #[test]
    fn test_statistics_tracking() {
        let config = RobustnessConfig::default();
        let mut manager = RobustnessManager::new(config);

        let gradient = randn::<f32>(&[2, 2]).unwrap();
        manager.update_statistics("param1", &gradient).unwrap();

        assert_eq!(manager.stats.total_gradients, 1);
        assert!(manager.stats.avg_gradient_norm > 0.0);
    }

    #[test]
    fn test_adversarial_perturbation() -> OptimizerResult<()> {
        let config = RobustnessConfig {
            adversarial_training: true,
            perturbation_budget: 0.1,
            ..Default::default()
        };
        let manager = RobustnessManager::new(config);

        let input = randn::<f32>(&[2, 2]).unwrap();
        let gradient = randn::<f32>(&[2, 2]).unwrap();

        let perturbation = manager
            .generate_adversarial_perturbation(&input, &gradient)
            .unwrap();
        let pert_norm = perturbation.norm().unwrap().to_vec()?[0];

        assert!(pert_norm <= 0.1 + 1e-6);

        Ok(())
    }

    #[test]
    fn test_stability_assessment() {
        let mut stats = RobustnessStats::new();
        stats.stability_score = 0.8;
        stats.total_gradients = 100;
        stats.clipped_gradients = 10;
        stats.outliers_detected = 5;

        let manager = RobustnessManager {
            config: RobustnessConfig::default(),
            stats,
            gradient_history: HashMap::new(),
            smoothed_gradients: HashMap::new(),
        };

        assert!(manager.is_training_stable());
    }
}