ghostflow-ml 1.0.0

Classical ML algorithms for GhostFlow
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Loss Functions - MSE, CrossEntropy, BCE, Huber, etc.

use ghostflow_core::Tensor;

/// Loss function trait
pub trait Loss: Send + Sync {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32;
    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor;
}

/// Mean Squared Error Loss
pub struct MSELoss {
    pub reduction: Reduction,
}

#[derive(Clone, Copy)]
pub enum Reduction {
    Mean,
    Sum,
    None,
}

impl MSELoss {
    pub fn new() -> Self {
        MSELoss { reduction: Reduction::Mean }
    }

    pub fn reduction(mut self, r: Reduction) -> Self {
        self.reduction = r;
        self
    }
}

impl Default for MSELoss {
    fn default() -> Self { Self::new() }
}

impl Loss for MSELoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        
        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| (p - t).powi(2))
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let g = 2.0 * (p - t);
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// Cross Entropy Loss (for classification)
pub struct CrossEntropyLoss {
    pub reduction: Reduction,
    pub label_smoothing: f32,
}

impl CrossEntropyLoss {
    pub fn new() -> Self {
        CrossEntropyLoss {
            reduction: Reduction::Mean,
            label_smoothing: 0.0,
        }
    }

    pub fn label_smoothing(mut self, ls: f32) -> Self {
        self.label_smoothing = ls.clamp(0.0, 1.0);
        self
    }

    fn softmax(logits: &[f32], n_classes: usize) -> Vec<f32> {
        let max_val = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        let exp_sum: f32 = logits.iter().map(|&x| (x - max_val).exp()).sum();
        logits.iter().map(|&x| (x - max_val).exp() / exp_sum).collect()
    }
}

impl Default for CrossEntropyLoss {
    fn default() -> Self { Self::new() }
}

impl Loss for CrossEntropyLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let batch_size = predictions.dims()[0];
        let n_classes = predictions.dims()[1];
        let eps = 1e-10f32;

        let mut total_loss = 0.0f32;

        for b in 0..batch_size {
            let logits = &pred[b * n_classes..(b + 1) * n_classes];
            let probs = Self::softmax(logits, n_classes);
            let target_class = targ[b] as usize;

            if self.label_smoothing > 0.0 {
                let smooth = self.label_smoothing / n_classes as f32;
                for c in 0..n_classes {
                    let target_prob = if c == target_class {
                        1.0 - self.label_smoothing + smooth
                    } else {
                        smooth
                    };
                    total_loss -= target_prob * (probs[c] + eps).ln();
                }
            } else {
                total_loss -= (probs[target_class] + eps).ln();
            }
        }

        match self.reduction {
            Reduction::Mean => total_loss / batch_size as f32,
            Reduction::Sum => total_loss,
            Reduction::None => total_loss,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let batch_size = predictions.dims()[0];
        let n_classes = predictions.dims()[1];

        let mut grad = vec![0.0f32; batch_size * n_classes];

        for b in 0..batch_size {
            let logits = &pred[b * n_classes..(b + 1) * n_classes];
            let probs = Self::softmax(logits, n_classes);
            let target_class = targ[b] as usize;

            for c in 0..n_classes {
                let target_prob = if c == target_class { 1.0 } else { 0.0 };
                grad[b * n_classes + c] = probs[c] - target_prob;
            }
        }

        if matches!(self.reduction, Reduction::Mean) {
            for g in &mut grad {
                *g /= batch_size as f32;
            }
        }

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// Binary Cross Entropy Loss
pub struct BCELoss {
    pub reduction: Reduction,
}

impl BCELoss {
    pub fn new() -> Self {
        BCELoss { reduction: Reduction::Mean }
    }
}

impl Default for BCELoss {
    fn default() -> Self { Self::new() }
}

impl Loss for BCELoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let eps = 1e-10f32;

        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let p_clipped = p.clamp(eps, 1.0 - eps);
                -t * p_clipped.ln() - (1.0 - t) * (1.0 - p_clipped).ln()
            })
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();
        let eps = 1e-10f32;

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let p_clipped = p.clamp(eps, 1.0 - eps);
                let g = -t / p_clipped + (1.0 - t) / (1.0 - p_clipped);
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// BCE with Logits Loss (numerically stable)
pub struct BCEWithLogitsLoss {
    pub reduction: Reduction,
    pub pos_weight: Option<f32>,
}

impl BCEWithLogitsLoss {
    pub fn new() -> Self {
        BCEWithLogitsLoss {
            reduction: Reduction::Mean,
            pos_weight: None,
        }
    }

    pub fn pos_weight(mut self, w: f32) -> Self {
        self.pos_weight = Some(w);
        self
    }

    fn sigmoid(x: f32) -> f32 {
        if x >= 0.0 {
            1.0 / (1.0 + (-x).exp())
        } else {
            let e = x.exp();
            e / (1.0 + e)
        }
    }
}

impl Default for BCEWithLogitsLoss {
    fn default() -> Self { Self::new() }
}

impl Loss for BCEWithLogitsLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();

        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let max_val = p.max(0.0);
                let loss = max_val - p * t + ((-max_val).exp() + (p - max_val).exp()).ln();
                if let Some(w) = self.pos_weight {
                    t * w * loss + (1.0 - t) * loss
                } else {
                    loss
                }
            })
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let sig = Self::sigmoid(p);
                let g = sig - t;
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// Huber Loss (Smooth L1)
pub struct HuberLoss {
    pub delta: f32,
    pub reduction: Reduction,
}

impl HuberLoss {
    pub fn new(delta: f32) -> Self {
        HuberLoss {
            delta,
            reduction: Reduction::Mean,
        }
    }
}

impl Loss for HuberLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();

        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let diff = (p - t).abs();
                if diff <= self.delta {
                    0.5 * diff * diff
                } else {
                    self.delta * (diff - 0.5 * self.delta)
                }
            })
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let diff = p - t;
                let g = if diff.abs() <= self.delta {
                    diff
                } else {
                    self.delta * diff.signum()
                };
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// L1 Loss (Mean Absolute Error)
pub struct L1Loss {
    pub reduction: Reduction,
}

impl L1Loss {
    pub fn new() -> Self {
        L1Loss { reduction: Reduction::Mean }
    }
}

impl Default for L1Loss {
    fn default() -> Self { Self::new() }
}

impl Loss for L1Loss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();

        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| (p - t).abs())
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let g = (p - t).signum();
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// Hinge Loss (for SVM-style classification)
pub struct HingeLoss {
    pub margin: f32,
    pub reduction: Reduction,
}

impl HingeLoss {
    pub fn new() -> Self {
        HingeLoss {
            margin: 1.0,
            reduction: Reduction::Mean,
        }
    }
}

impl Default for HingeLoss {
    fn default() -> Self { Self::new() }
}

impl Loss for HingeLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();

        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                // Convert 0/1 to -1/+1
                let t_signed = if t > 0.5 { 1.0 } else { -1.0 };
                (self.margin - t_signed * p).max(0.0)
            })
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                let t_signed = if t > 0.5 { 1.0 } else { -1.0 };
                let g = if self.margin - t_signed * p > 0.0 {
                    -t_signed
                } else {
                    0.0
                };
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

/// KL Divergence Loss
pub struct KLDivLoss {
    pub reduction: Reduction,
    pub log_target: bool,
}

impl KLDivLoss {
    pub fn new() -> Self {
        KLDivLoss {
            reduction: Reduction::Mean,
            log_target: false,
        }
    }
}

impl Default for KLDivLoss {
    fn default() -> Self { Self::new() }
}

impl Loss for KLDivLoss {
    fn forward(&self, predictions: &Tensor, targets: &Tensor) -> f32 {
        let pred = predictions.data_f32(); // log probabilities
        let targ = targets.data_f32();
        let eps = 1e-10f32;

        let sum: f32 = pred.iter().zip(targ.iter())
            .map(|(&p, &t)| {
                if self.log_target {
                    (t.exp()) * (t - p)
                } else {
                    t * ((t + eps).ln() - p)
                }
            })
            .sum();

        match self.reduction {
            Reduction::Mean => sum / pred.len() as f32,
            Reduction::Sum => sum,
            Reduction::None => sum,
        }
    }

    fn backward(&self, predictions: &Tensor, targets: &Tensor) -> Tensor {
        let pred = predictions.data_f32();
        let targ = targets.data_f32();
        let n = pred.len();

        let grad: Vec<f32> = pred.iter().zip(targ.iter())
            .map(|(&_p, &t)| {
                let g = if self.log_target { -t.exp() } else { -t };
                match self.reduction {
                    Reduction::Mean => g / n as f32,
                    _ => g,
                }
            })
            .collect();

        Tensor::from_slice(&grad, predictions.dims()).unwrap()
    }
}

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

    #[test]
    fn test_mse_loss() {
        let pred = Tensor::from_slice(&[1.0f32, 2.0, 3.0], &[3]).unwrap();
        let targ = Tensor::from_slice(&[1.0f32, 2.0, 3.0], &[3]).unwrap();
        let loss = MSELoss::new();
        assert!((loss.forward(&pred, &targ) - 0.0).abs() < 1e-6);
    }

    #[test]
    fn test_bce_loss() {
        let pred = Tensor::from_slice(&[0.9f32, 0.1], &[2]).unwrap();
        let targ = Tensor::from_slice(&[1.0f32, 0.0], &[2]).unwrap();
        let loss = BCELoss::new();
        let l = loss.forward(&pred, &targ);
        assert!(l > 0.0 && l < 1.0);
    }
}


/// Focal Loss - for addressing class imbalance
/// Focuses training on hard examples
pub struct FocalLoss {
    pub alpha: f32,
    pub gamma: f32,
}

impl FocalLoss {
    pub fn new(alpha: f32, gamma: f32) -> Self {
        FocalLoss { alpha, gamma }
    }

    pub fn forward(&self, predictions: &[f32], targets: &[f32]) -> f32 {
        let eps = 1e-7f32;
        let mut loss = 0.0f32;

        for (&pred, &target) in predictions.iter().zip(targets.iter()) {
            let pred_clipped = pred.clamp(eps, 1.0 - eps);
            let pt = if target > 0.5 { pred_clipped } else { 1.0 - pred_clipped };
            let focal_weight = (1.0 - pt).powf(self.gamma);
            let ce = -target * pred_clipped.ln() - (1.0 - target) * (1.0 - pred_clipped).ln();
            loss += self.alpha * focal_weight * ce;
        }

        loss / predictions.len() as f32
    }

    pub fn backward(&self, predictions: &[f32], targets: &[f32]) -> Vec<f32> {
        let eps = 1e-7f32;
        let mut grads = Vec::with_capacity(predictions.len());

        for (&pred, &target) in predictions.iter().zip(targets.iter()) {
            let pred_clipped = pred.clamp(eps, 1.0 - eps);
            let pt = if target > 0.5 { pred_clipped } else { 1.0 - pred_clipped };
            let focal_weight = (1.0 - pt).powf(self.gamma);
            
            // Gradient computation
            let grad = if target > 0.5 {
                self.alpha * focal_weight * (self.gamma * pt.ln() * (1.0 - pt) - 1.0) / pred_clipped
            } else {
                self.alpha * focal_weight * (self.gamma * (1.0 - pt).ln() * pt + 1.0) / (1.0 - pred_clipped)
            };
            
            grads.push(grad / predictions.len() as f32);
        }

        grads
    }
}

/// Dice Loss - for segmentation tasks
pub struct DiceLoss {
    pub smooth: f32,
}

impl DiceLoss {
    pub fn new() -> Self {
        DiceLoss { smooth: 1.0 }
    }

    pub fn smooth(mut self, s: f32) -> Self {
        self.smooth = s;
        self
    }

    pub fn forward(&self, predictions: &[f32], targets: &[f32]) -> f32 {
        let mut intersection = 0.0f32;
        let mut pred_sum = 0.0f32;
        let mut target_sum = 0.0f32;

        for (&pred, &target) in predictions.iter().zip(targets.iter()) {
            intersection += pred * target;
            pred_sum += pred;
            target_sum += target;
        }

        1.0 - (2.0 * intersection + self.smooth) / (pred_sum + target_sum + self.smooth)
    }

    pub fn backward(&self, predictions: &[f32], targets: &[f32]) -> Vec<f32> {
        let mut intersection = 0.0f32;
        let mut pred_sum = 0.0f32;
        let mut target_sum = 0.0f32;

        for (&pred, &target) in predictions.iter().zip(targets.iter()) {
            intersection += pred * target;
            pred_sum += pred;
            target_sum += target;
        }

        let denominator = pred_sum + target_sum + self.smooth;
        let numerator = 2.0 * intersection + self.smooth;

        predictions.iter().zip(targets.iter())
            .map(|(&pred, &target)| {
                -2.0 * (target * denominator - numerator) / (denominator * denominator)
            })
            .collect()
    }
}

impl Default for DiceLoss {
    fn default() -> Self { Self::new() }
}

/// Tversky Loss - generalization of Dice loss
pub struct TverskyLoss {
    pub alpha: f32,
    pub beta: f32,
    pub smooth: f32,
}

impl TverskyLoss {
    pub fn new(alpha: f32, beta: f32) -> Self {
        TverskyLoss { alpha, beta, smooth: 1.0 }
    }

    pub fn forward(&self, predictions: &[f32], targets: &[f32]) -> f32 {
        let mut tp = 0.0f32;
        let mut fp = 0.0f32;
        let mut fn_count = 0.0f32;

        for (&pred, &target) in predictions.iter().zip(targets.iter()) {
            tp += pred * target;
            fp += pred * (1.0 - target);
            fn_count += (1.0 - pred) * target;
        }

        1.0 - (tp + self.smooth) / (tp + self.alpha * fp + self.beta * fn_count + self.smooth)
    }
}

/// Lovász-Softmax Loss - for segmentation
pub struct LovaszLoss {
    pub per_image: bool,
}

impl LovaszLoss {
    pub fn new() -> Self {
        LovaszLoss { per_image: false }
    }

    pub fn forward(&self, predictions: &[f32], targets: &[f32]) -> f32 {
        // Simplified Lovász hinge loss
        let mut errors: Vec<(f32, bool)> = predictions.iter()
            .zip(targets.iter())
            .map(|(&pred, &target)| {
                let error = if target > 0.5 { 1.0 - pred } else { pred };
                (error, target > 0.5)
            })
            .collect();

        errors.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());

        let mut loss = 0.0f32;
        let mut tp = 0.0f32;
        let mut fp = 0.0f32;

        for (error, is_positive) in errors {
            if is_positive {
                tp += 1.0;
            } else {
                fp += 1.0;
            }
            let jaccard_grad = fp / (tp + fp);
            loss += error * jaccard_grad;
        }

        loss / predictions.len() as f32
    }
}

impl Default for LovaszLoss {
    fn default() -> Self { Self::new() }
}

/// Contrastive Loss - for metric learning
pub struct ContrastiveLoss {
    pub margin: f32,
}

impl ContrastiveLoss {
    pub fn new(margin: f32) -> Self {
        ContrastiveLoss { margin }
    }

    pub fn forward(&self, embeddings1: &[f32], embeddings2: &[f32], labels: &[f32]) -> f32 {
        let n = embeddings1.len();
        let mut loss = 0.0f32;

        for i in 0..n {
            let dist_sq = (embeddings1[i] - embeddings2[i]).powi(2);
            
            if labels[i] > 0.5 {
                // Similar pair
                loss += dist_sq;
            } else {
                // Dissimilar pair
                loss += (self.margin - dist_sq.sqrt()).max(0.0).powi(2);
            }
        }

        loss / n as f32
    }
}

/// Triplet Loss - for metric learning
pub struct TripletLoss {
    pub margin: f32,
}

impl TripletLoss {
    pub fn new(margin: f32) -> Self {
        TripletLoss { margin }
    }

    pub fn forward(&self, anchor: &[f32], positive: &[f32], negative: &[f32]) -> f32 {
        let n = anchor.len();
        
        let mut pos_dist = 0.0f32;
        let mut neg_dist = 0.0f32;

        for i in 0..n {
            pos_dist += (anchor[i] - positive[i]).powi(2);
            neg_dist += (anchor[i] - negative[i]).powi(2);
        }

        (pos_dist - neg_dist + self.margin).max(0.0)
    }
}

/// Center Loss - for face recognition
pub struct CenterLoss {
    pub alpha: f32,
    pub num_classes: usize,
    centers: Vec<Vec<f32>>,
}

impl CenterLoss {
    pub fn new(num_classes: usize, feature_dim: usize, alpha: f32) -> Self {
        CenterLoss {
            alpha,
            num_classes,
            centers: vec![vec![0.0; feature_dim]; num_classes],
        }
    }

    pub fn forward(&self, features: &[f32], labels: &[usize], feature_dim: usize) -> f32 {
        let batch_size = labels.len();
        let mut loss = 0.0f32;

        for (i, &label) in labels.iter().enumerate() {
            if label < self.num_classes {
                let feat_start = i * feature_dim;
                let feat = &features[feat_start..feat_start + feature_dim];
                let center = &self.centers[label];

                for (f, c) in feat.iter().zip(center.iter()) {
                    loss += (f - c).powi(2);
                }
            }
        }

        loss / (2.0 * batch_size as f32)
    }

    pub fn update_centers(&mut self, features: &[f32], labels: &[usize], feature_dim: usize) {
        let batch_size = labels.len();
        let mut counts = vec![0; self.num_classes];
        let mut deltas = vec![vec![0.0f32; feature_dim]; self.num_classes];

        for (i, &label) in labels.iter().enumerate() {
            if label < self.num_classes {
                counts[label] += 1;
                let feat_start = i * feature_dim;
                let feat = &features[feat_start..feat_start + feature_dim];

                for (j, &f) in feat.iter().enumerate() {
                    deltas[label][j] += f - self.centers[label][j];
                }
            }
        }

        for c in 0..self.num_classes {
            if counts[c] > 0 {
                for j in 0..feature_dim {
                    self.centers[c][j] += self.alpha * deltas[c][j] / counts[c] as f32;
                }
            }
        }
    }
}

/// Label Smoothing Cross Entropy
pub struct LabelSmoothingLoss {
    pub smoothing: f32,
    pub num_classes: usize,
}

impl LabelSmoothingLoss {
    pub fn new(num_classes: usize, smoothing: f32) -> Self {
        LabelSmoothingLoss { smoothing, num_classes }
    }

    pub fn forward(&self, predictions: &[f32], targets: &[usize]) -> f32 {
        let batch_size = targets.len();
        let mut loss = 0.0f32;
        let eps = 1e-7f32;
        let confidence = 1.0 - self.smoothing;
        let smooth_value = self.smoothing / self.num_classes as f32;

        for (i, &target) in targets.iter().enumerate() {
            for c in 0..self.num_classes {
                let pred = predictions[i * self.num_classes + c].clamp(eps, 1.0 - eps);
                let target_prob = if c == target { confidence } else { smooth_value };
                loss -= target_prob * pred.ln();
            }
        }

        loss / batch_size as f32
    }
}

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

    #[test]
    fn test_focal_loss() {
        let focal = FocalLoss::new(0.25, 2.0);
        let preds = vec![0.9, 0.1, 0.8, 0.2];
        let targets = vec![1.0, 0.0, 1.0, 0.0];
        let loss = focal.forward(&preds, &targets);
        assert!(loss >= 0.0);
    }

    #[test]
    fn test_dice_loss() {
        let dice = DiceLoss::new();
        let preds = vec![0.9, 0.8, 0.7, 0.6];
        let targets = vec![1.0, 1.0, 0.0, 0.0];
        let loss = dice.forward(&preds, &targets);
        assert!(loss >= 0.0 && loss <= 1.0);
    }

    #[test]
    fn test_triplet_loss() {
        let triplet = TripletLoss::new(1.0);
        let anchor = vec![1.0, 2.0, 3.0];
        let positive = vec![1.1, 2.1, 3.1];
        let negative = vec![5.0, 6.0, 7.0];
        let loss = triplet.forward(&anchor, &positive, &negative);
        assert!(loss >= 0.0);
    }
}