entrenar 0.7.10

Training & Optimization library with autograd, LoRA, quantization, and model merging
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
//! Drift Detection Module (ENT-044)
//!
//! Detects training anomalies using statistical methods.
//! Based on renacer's sliding window baseline patterns.

/// Drift detection status
#[derive(Debug, Clone, PartialEq)]
pub enum DriftStatus {
    /// No drift detected
    NoDrift,
    /// Warning: potential drift (p-value)
    Warning(f64),
    /// Drift confirmed (p-value)
    Drift(f64),
}

/// Anomaly severity levels (from renacer)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnomalySeverity {
    /// 3-4 standard deviations
    Low,
    /// 4-5 standard deviations
    Medium,
    /// >5 standard deviations
    High,
}

/// Sliding window baseline for anomaly detection
#[derive(Debug, Clone)]
pub struct SlidingWindowBaseline {
    window_size: usize,
    values: Vec<f64>,
    mean: f64,
    m2: f64, // For Welford's algorithm
    count: usize,
}

impl SlidingWindowBaseline {
    /// Create a new baseline with given window size
    pub fn new(window_size: usize) -> Self {
        Self { window_size, values: Vec::with_capacity(window_size), mean: 0.0, m2: 0.0, count: 0 }
    }

    /// Update baseline with new value
    pub fn update(&mut self, value: f64) {
        if value.is_nan() || value.is_infinite() {
            return;
        }

        // Add to window
        if self.values.len() >= self.window_size {
            self.values.remove(0);
        }
        self.values.push(value);

        // Recalculate stats (simplified - could be optimized)
        self.count = self.values.len();
        if self.count > 0 {
            self.mean = self.values.iter().sum::<f64>() / self.count as f64;
            if self.count > 1 {
                self.m2 = self.values.iter().map(|v| (v - self.mean).powi(2)).sum::<f64>();
            }
        }
    }

    /// Get current standard deviation
    pub fn std(&self) -> f64 {
        if self.count < 2 {
            return 0.0;
        }
        (self.m2 / (self.count - 1) as f64).sqrt()
    }

    /// Calculate z-score for a value
    pub fn z_score(&self, value: f64) -> f64 {
        let std = self.std();
        if std == 0.0 {
            return 0.0;
        }
        (value - self.mean) / std
    }

    /// Detect anomaly with threshold (standard deviations)
    pub fn detect_anomaly(&self, value: f64, threshold: f64) -> Option<Anomaly> {
        if self.count < 10 {
            return None; // Not enough data
        }

        let z = self.z_score(value).abs();
        if z < threshold {
            return None;
        }

        let severity = if z >= 5.0 {
            AnomalySeverity::High
        } else if z >= 4.0 {
            AnomalySeverity::Medium
        } else {
            AnomalySeverity::Low
        };

        Some(Anomaly {
            value,
            z_score: z,
            severity,
            baseline_mean: self.mean,
            baseline_std: self.std(),
        })
    }

    /// Get current mean
    pub fn mean(&self) -> f64 {
        self.mean
    }

    /// Get sample count
    pub fn count(&self) -> usize {
        self.count
    }
}

/// Detected anomaly
#[derive(Debug, Clone)]
pub struct Anomaly {
    /// The anomalous value
    pub value: f64,
    /// Z-score (number of standard deviations from mean)
    pub z_score: f64,
    /// Severity classification
    pub severity: AnomalySeverity,
    /// Baseline mean when anomaly was detected
    pub baseline_mean: f64,
    /// Baseline standard deviation
    pub baseline_std: f64,
}

/// Drift detector using statistical tests
#[derive(Debug)]
pub struct DriftDetector {
    baseline: SlidingWindowBaseline,
    threshold: f64,
    warning_threshold: f64,
}

impl DriftDetector {
    /// Create a new drift detector
    pub fn new(window_size: usize) -> Self {
        Self {
            baseline: SlidingWindowBaseline::new(window_size),
            threshold: 0.05,        // p < 0.05 for drift
            warning_threshold: 0.1, // p < 0.1 for warning
        }
    }

    /// Set detection thresholds
    pub fn with_thresholds(mut self, warning: f64, drift: f64) -> Self {
        self.warning_threshold = warning;
        self.threshold = drift;
        self
    }

    /// Update baseline and check for drift
    pub fn check(&mut self, value: f64) -> DriftStatus {
        // Get z-score before updating
        let z = self.baseline.z_score(value).abs();

        // Update baseline
        self.baseline.update(value);

        if self.baseline.count() < 10 {
            return DriftStatus::NoDrift;
        }

        // Convert z-score to approximate p-value
        let p = z_to_p(z);

        if p < self.threshold {
            DriftStatus::Drift(p)
        } else if p < self.warning_threshold {
            DriftStatus::Warning(p)
        } else {
            DriftStatus::NoDrift
        }
    }
}

/// Approximate z-score to p-value (two-tailed)
fn z_to_p(z: f64) -> f64 {
    // Approximation using error function
    let t = 1.0 / (1.0 + 0.2316419 * z.abs());
    let d = 0.3989423 * (-z * z / 2.0).exp();
    let p =
        d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274))));

    2.0 * p // Two-tailed
}

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

    #[test]
    fn test_sliding_window_new() {
        let baseline = SlidingWindowBaseline::new(100);
        assert_eq!(baseline.count(), 0);
    }

    #[test]
    fn test_sliding_window_update() {
        let mut baseline = SlidingWindowBaseline::new(100);
        for i in 0..10 {
            baseline.update(f64::from(i));
        }
        assert_eq!(baseline.count(), 10);
        assert!((baseline.mean() - 4.5).abs() < 1e-6);
    }

    #[test]
    fn test_sliding_window_rolls() {
        let mut baseline = SlidingWindowBaseline::new(5);
        for i in 0..10 {
            baseline.update(f64::from(i));
        }
        // Window should contain [5, 6, 7, 8, 9]
        assert_eq!(baseline.count(), 5);
        assert!((baseline.mean() - 7.0).abs() < 1e-6);
    }

    #[test]
    fn test_z_score() {
        let mut baseline = SlidingWindowBaseline::new(100);
        // Add 100 values with mean=50, std≈29
        for i in 0..100 {
            baseline.update(f64::from(i));
        }

        // Value at mean should have z≈0
        let z_mean = baseline.z_score(50.0);
        assert!(z_mean.abs() < 0.5);
    }

    #[test]
    fn test_detect_anomaly_none() {
        let mut baseline = SlidingWindowBaseline::new(100);
        for i in 0..100 {
            baseline.update(50.0 + f64::from(i % 5));
        }

        // Normal value
        let anomaly = baseline.detect_anomaly(52.0, 3.0);
        assert!(anomaly.is_none());
    }

    #[test]
    fn test_detect_anomaly_high() {
        let mut baseline = SlidingWindowBaseline::new(100);
        // Add values with some variance so std > 0
        for i in 0..100 {
            baseline.update(50.0 + f64::from(i % 10));
        }

        // Extreme outlier (far from mean ~54.5, std ~2.87)
        let anomaly = baseline.detect_anomaly(100.0, 3.0);
        assert!(anomaly.is_some());
        let a = anomaly.expect("operation should succeed");
        assert!(a.z_score > 5.0); // Should be high severity
    }

    #[test]
    fn test_drift_detector_no_drift() {
        let mut detector = DriftDetector::new(100);

        // Stable values
        for _ in 0..50 {
            let status = detector.check(50.0);
            assert_eq!(status, DriftStatus::NoDrift);
        }
    }

    #[test]
    fn test_drift_detector_detects_drift() {
        let mut detector = DriftDetector::new(100);

        // Establish baseline with some variance
        for i in 0..100 {
            detector.check(50.0 + f64::from(i % 10));
        }

        // Sudden large change (mean ~54.5, value 200 is ~50 std devs away)
        let status = detector.check(200.0);
        // With variance, this should trigger drift or warning
        assert!(
            matches!(status, DriftStatus::Drift(_) | DriftStatus::Warning(_)),
            "Expected drift or warning, got {status:?}"
        );
    }

    #[test]
    fn test_anomaly_severity_low() {
        let mut baseline = SlidingWindowBaseline::new(100);
        for _ in 0..100 {
            baseline.update(50.0);
        }
        // Force a specific std for predictable testing
        // With constant values, std=0, so any deviation is huge
        // Instead test with some variance
    }

    // =========================================================================
    // Additional Coverage Tests
    // =========================================================================

    #[test]
    fn test_update_with_nan() {
        let mut baseline = SlidingWindowBaseline::new(100);
        baseline.update(1.0);
        baseline.update(f64::NAN);
        baseline.update(2.0);
        // NaN should be ignored
        assert_eq!(baseline.count(), 2);
    }

    #[test]
    fn test_update_with_infinity() {
        let mut baseline = SlidingWindowBaseline::new(100);
        baseline.update(1.0);
        baseline.update(f64::INFINITY);
        baseline.update(f64::NEG_INFINITY);
        baseline.update(2.0);
        // Infinities should be ignored
        assert_eq!(baseline.count(), 2);
    }

    #[test]
    fn test_std_with_single_value() {
        let mut baseline = SlidingWindowBaseline::new(100);
        baseline.update(42.0);
        // With single value, std should be 0
        assert_eq!(baseline.std(), 0.0);
    }

    #[test]
    fn test_z_score_zero_std() {
        let mut baseline = SlidingWindowBaseline::new(100);
        baseline.update(5.0);
        baseline.update(5.0);
        // With constant values, std=0, z_score should be 0
        assert_eq!(baseline.z_score(10.0), 0.0);
    }

    #[test]
    fn test_detect_anomaly_not_enough_data() {
        let mut baseline = SlidingWindowBaseline::new(100);
        for i in 0..5 {
            baseline.update(f64::from(i));
        }
        // Less than 10 values, should return None
        let anomaly = baseline.detect_anomaly(100.0, 3.0);
        assert!(anomaly.is_none());
    }

    #[test]
    fn test_anomaly_severity_medium() {
        let mut baseline = SlidingWindowBaseline::new(100);
        // Add values with controlled variance
        for i in 0..100 {
            // Values between 48-52, mean=50, std≈1.41
            baseline.update(50.0 + f64::from(i % 5 - 2));
        }
        // Value 4 std devs away: 50 + 4*1.41 ≈ 55.64
        // But actually need ~4 std devs to get Medium
        // With our distribution mean≈50, std≈1.41, z=4 at ~55.64
        let anomaly = baseline.detect_anomaly(56.0, 3.0);
        if let Some(a) = anomaly {
            // z should be around 4 for Medium severity
            println!("z_score: {}", a.z_score);
        }
    }

    #[test]
    fn test_drift_detector_with_thresholds() {
        let detector = DriftDetector::new(100).with_thresholds(0.15, 0.08);
        // Just verify the builder works
        assert_eq!(detector.threshold, 0.08);
        assert_eq!(detector.warning_threshold, 0.15);
    }

    #[test]
    fn test_drift_status_warning() {
        let mut detector = DriftDetector::new(50).with_thresholds(0.3, 0.05); // More lenient warning

        // Establish baseline
        for i in 0..50 {
            detector.check(50.0 + f64::from(i % 10));
        }

        // Moderate deviation might trigger warning
        // This tests the warning branch
        let _status = detector.check(75.0);
        // Result depends on statistics
    }

    #[test]
    fn test_z_to_p_approximation() {
        // Test the z_to_p function indirectly through DriftDetector
        let mut detector = DriftDetector::new(100);
        for i in 0..100 {
            detector.check(50.0 + f64::from(i % 5));
        }
        // Any check will exercise the z_to_p function
        let _status = detector.check(60.0);
    }

    #[test]
    fn test_drift_status_eq() {
        assert_eq!(DriftStatus::NoDrift, DriftStatus::NoDrift);
        assert_ne!(DriftStatus::NoDrift, DriftStatus::Drift(0.01));
        assert_ne!(DriftStatus::Warning(0.08), DriftStatus::Drift(0.08));
    }

    #[test]
    fn test_anomaly_clone() {
        let anomaly = Anomaly {
            value: 100.0,
            z_score: 5.0,
            severity: AnomalySeverity::High,
            baseline_mean: 50.0,
            baseline_std: 10.0,
        };
        let cloned = anomaly.clone();
        assert_eq!(anomaly.value, cloned.value);
        assert_eq!(anomaly.severity, cloned.severity);
    }

    #[test]
    fn test_sliding_window_baseline_clone() {
        let mut baseline = SlidingWindowBaseline::new(50);
        baseline.update(1.0);
        baseline.update(2.0);
        let cloned = baseline.clone();
        assert_eq!(baseline.count(), cloned.count());
        assert_eq!(baseline.mean(), cloned.mean());
    }
}