axonml-nn 0.6.0

Neural network modules for Axonml ML framework
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
//! Loss Functions - Training Objectives
//!
//! # File
//! `crates/axonml-nn/src/loss.rs`
//!
//! # Author
//! Andrew Jewell Sr - AutomataNexus
//!
//! # Updated
//! March 8, 2026
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

use std::any::Any;

use axonml_autograd::no_grad::is_grad_enabled;
use axonml_autograd::{GradFn, GradientFunction, Variable};
use axonml_tensor::Tensor;

use crate::module::Module;

// =============================================================================
// Reduction Enum
// =============================================================================

/// Specifies how to reduce the loss over elements.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Reduction {
    /// No reduction - return loss per element.
    None,
    /// Mean of all losses.
    #[default]
    Mean,
    /// Sum of all losses.
    Sum,
}

// =============================================================================
// MSELoss
// =============================================================================

/// Mean Squared Error loss.
///
/// loss = mean((input - target)^2)
#[derive(Debug, Clone, Copy)]
pub struct MSELoss {
    reduction: Reduction,
}

impl MSELoss {
    /// Creates a new MSELoss with default reduction (Mean).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
        }
    }

    /// Creates MSELoss with specified reduction.
    pub fn with_reduction(reduction: Reduction) -> Self {
        Self { reduction }
    }

    /// Computes the loss.
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let diff = input.sub_var(target);
        let squared = diff.pow(2.0);

        match self.reduction {
            Reduction::None => squared,
            Reduction::Mean => squared.mean(),
            Reduction::Sum => squared.sum(),
        }
    }
}

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

impl Module for MSELoss {
    fn forward(&self, input: &Variable) -> Variable {
        // For Module interface, we can't easily pass two inputs
        // This is primarily used via compute() method
        input.clone()
    }

    fn name(&self) -> &'static str {
        "MSELoss"
    }
}

// =============================================================================
// L1Loss
// =============================================================================

/// Mean Absolute Error loss.
///
/// loss = mean(|input - target|)
#[derive(Debug, Clone, Copy)]
pub struct L1Loss {
    reduction: Reduction,
}

impl L1Loss {
    /// Creates a new L1Loss with default reduction (Mean).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
        }
    }

    /// Creates L1Loss with specified reduction.
    pub fn with_reduction(reduction: Reduction) -> Self {
        Self { reduction }
    }

    /// Computes the loss.
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let input_data = input.data();
        let target_data = target.data();
        // diff = input - target (Tensor op, auto-dispatches to GPU)
        let diff_tensor = input_data.sub(&target_data).expect("tensor sub failed");
        // |diff| = relu(diff) + relu(-diff), using Tensor ops that auto-dispatch to GPU
        let relu_diff = axonml_tensor::ops::clamp_min(&diff_tensor, 0.0);
        let relu_neg_diff = axonml_tensor::ops::clamp_min(&diff_tensor.neg(), 0.0);
        let abs_tensor = relu_diff.add(&relu_neg_diff).expect("tensor add failed");

        let requires_grad = (input.requires_grad() || target.requires_grad()) && is_grad_enabled();
        let loss_var = if requires_grad {
            let grad_fn = GradFn::new(L1LossBackward {
                next_fns: vec![input.grad_fn().cloned(), target.grad_fn().cloned()],
                diff_tensor,
            });
            Variable::from_operation(abs_tensor, grad_fn, true)
        } else {
            Variable::new(abs_tensor, false)
        };

        match self.reduction {
            Reduction::None => loss_var,
            Reduction::Mean => loss_var.mean(),
            Reduction::Sum => loss_var.sum(),
        }
    }
}

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

// =============================================================================
// L1LossBackward
// =============================================================================

/// Gradient function for L1Loss.
///
/// d/d(input) = sign(input - target)
/// d/d(target) = -sign(input - target)
///
/// Stores diff as Tensor<f32> so it stays on GPU when applicable.
#[derive(Debug)]
struct L1LossBackward {
    next_fns: Vec<Option<GradFn>>,
    diff_tensor: Tensor<f32>,
}

impl GradientFunction for L1LossBackward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        // sign(diff): +1 where diff > 0, -1 where diff < 0, 0 where diff == 0
        // Compute as: diff / (|diff| + eps) which gives sign and handles GPU
        let eps_tensor = Tensor::full(self.diff_tensor.shape(), 1e-12);
        let eps_on_device = if self.diff_tensor.device().is_gpu() {
            eps_tensor.to_device(self.diff_tensor.device()).unwrap()
        } else {
            eps_tensor
        };
        // |diff| approximated as sqrt(diff^2 + eps)  — but simpler: diff * diff then sqrt
        let diff_sq = self
            .diff_tensor
            .mul(&self.diff_tensor)
            .expect("tensor mul failed");
        let diff_sq_eps = diff_sq.add(&eps_on_device).expect("tensor add failed");
        // sqrt via exp(0.5 * ln(x))
        let abs_diff = diff_sq_eps.ln().mul_scalar(0.5).exp();
        let sign_diff = self.diff_tensor.div(&abs_diff).unwrap();

        // grad_input = sign(diff) * grad_output
        let gi = sign_diff.mul(grad_output).unwrap();
        // grad_target = -grad_input
        let gt = gi.neg();
        vec![Some(gi), Some(gt)]
    }

    fn name(&self) -> &'static str {
        "L1LossBackward"
    }

    fn next_functions(&self) -> &[Option<GradFn>] {
        &self.next_fns
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// CrossEntropyBackward
// =============================================================================

/// Gradient function for CrossEntropyLoss.
///
/// The gradient of CE w.r.t. logits is: softmax(logits) - one_hot(target).
/// For per-sample losses, each sample's gradient is scaled by the upstream
/// gradient (from reduction).
#[derive(Debug)]
struct CrossEntropyBackward {
    next_fns: Vec<Option<GradFn>>,
    /// Softmax probabilities computed during forward pass, shape (N, C).
    /// Stays on GPU if input was on GPU.
    softmax_probs: Tensor<f32>,
    /// Target class indices as f32, shape (N,). Stays on GPU if input was on GPU.
    targets: Tensor<f32>,
    batch_size: usize,
    num_classes: usize,
}

impl GradientFunction for CrossEntropyBackward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        // Always use the exact CPU path for correctness, then transfer
        // result to GPU if needed. The CUDA cross_entropy_bwd kernel has
        // precision issues with approximate reciprocal/exp that cause
        // training to stall. The CPU backward is fast enough since CE
        // backward is O(N*C) — negligible vs the forward pass matmuls.
        let softmax_vec = self.softmax_probs.to_vec();
        let target_vec = self.targets.to_vec();
        let grad_vec = grad_output.to_vec();
        let mut grad_input = vec![0.0f32; self.batch_size * self.num_classes];

        // Handle both per-sample grad_output [N] and scalar [1] (from mean reduction)
        let is_scalar_grad = grad_vec.len() == 1;

        for b in 0..self.batch_size {
            let grad_scale = if is_scalar_grad {
                grad_vec[0]
            } else if b < grad_vec.len() {
                grad_vec[b]
            } else {
                1.0 / self.batch_size as f32
            };
            let offset = b * self.num_classes;
            let tc = target_vec[b] as usize;
            for c in 0..self.num_classes {
                let mut g = softmax_vec[offset + c];
                if c == tc {
                    g -= 1.0;
                }
                grad_input[offset + c] = g * grad_scale;
            }
        }

        let mut grad_tensor = Tensor::from_vec(grad_input, &[self.batch_size, self.num_classes])
            .expect("tensor creation failed");
        // Transfer to GPU if the forward was on GPU
        if self.softmax_probs.device().is_gpu() {
            grad_tensor = grad_tensor.to_device(self.softmax_probs.device()).unwrap();
        }
        vec![Some(grad_tensor)]
    }

    fn name(&self) -> &'static str {
        "CrossEntropyBackward"
    }

    fn next_functions(&self) -> &[Option<GradFn>] {
        &self.next_fns
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// CrossEntropyLoss
// =============================================================================

/// Cross entropy loss with log softmax.
///
/// This combines LogSoftmax and NLLLoss in a single class.
///
/// # Shape
/// - Input: (N, C) where C = number of classes
/// - Target: (N,) with class indices
#[derive(Debug, Clone, Copy)]
pub struct CrossEntropyLoss {
    reduction: Reduction,
}

impl CrossEntropyLoss {
    /// Creates a new CrossEntropyLoss with default reduction (Mean).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
        }
    }

    /// Creates CrossEntropyLoss with specified reduction.
    pub fn with_reduction(reduction: Reduction) -> Self {
        Self { reduction }
    }

    /// Computes the loss.
    ///
    /// # Arguments
    /// * `input` - Logits of shape (N, C)
    /// * `target` - Class indices of shape (N,) as f32 (will be cast to usize)
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let input_data = input.data();
        let target_data = target.data();
        let shape = input_data.shape().to_vec();
        let batch_size = shape[0];
        let num_classes = shape[1];

        // GPU fast path: fused softmax + NLL loss kernel
        #[cfg(feature = "cuda")]
        if input_data.device().is_gpu() {
            // Ensure targets are on GPU
            let targets_gpu = if target_data.device().is_gpu() {
                target_data.clone()
            } else {
                target_data.to_device(input_data.device()).unwrap()
            };

            let (loss_tensor, softmax_tensor) = input_data.cross_entropy_fwd_cuda(&targets_gpu);

            let loss_var = if input.requires_grad() {
                let grad_fn = GradFn::new(CrossEntropyBackward {
                    next_fns: vec![input.grad_fn().cloned()],
                    softmax_probs: softmax_tensor,
                    targets: targets_gpu,
                    batch_size,
                    num_classes,
                });
                Variable::from_operation(loss_tensor, grad_fn, true)
            } else {
                Variable::new(loss_tensor, false)
            };

            return match self.reduction {
                Reduction::None => loss_var,
                Reduction::Mean => loss_var.mean(),
                Reduction::Sum => loss_var.sum(),
            };
        }

        // CPU path
        let input_vec = input_data.to_vec();
        let target_vec = target_data.to_vec();

        let mut losses = vec![0.0f32; batch_size];
        let mut softmax_probs_vec = vec![0.0f32; batch_size * num_classes];
        let mut target_classes = vec![0usize; batch_size];

        for b in 0..batch_size {
            let offset = b * num_classes;

            // Numerically stable log-softmax
            let max_val = (0..num_classes)
                .map(|c| input_vec[offset + c])
                .fold(f32::NEG_INFINITY, f32::max);

            let mut sum_exp = 0.0f32;
            for c in 0..num_classes {
                let exp_val = (input_vec[offset + c] - max_val).exp();
                softmax_probs_vec[offset + c] = exp_val;
                sum_exp += exp_val;
            }

            for c in 0..num_classes {
                softmax_probs_vec[offset + c] /= sum_exp;
            }

            let log_sum_exp = max_val + sum_exp.ln();

            let tc = target_vec[b] as usize;
            target_classes[b] = tc;
            losses[b] = log_sum_exp - input_vec[offset + tc];
        }

        let loss_tensor = Tensor::from_vec(losses, &[batch_size]).expect("tensor creation failed");
        let softmax_tensor = Tensor::from_vec(softmax_probs_vec, &[batch_size, num_classes])
            .expect("tensor creation failed");
        let targets_f32: Vec<f32> = target_classes.iter().map(|&tc| tc as f32).collect();
        let targets_tensor =
            Tensor::from_vec(targets_f32, &[batch_size]).expect("tensor creation failed");

        let loss_var = if input.requires_grad() {
            let grad_fn = GradFn::new(CrossEntropyBackward {
                next_fns: vec![input.grad_fn().cloned()],
                softmax_probs: softmax_tensor,
                targets: targets_tensor,
                batch_size,
                num_classes,
            });
            Variable::from_operation(loss_tensor, grad_fn, true)
        } else {
            Variable::new(loss_tensor, false)
        };

        match self.reduction {
            Reduction::None => loss_var,
            Reduction::Mean => loss_var.mean(),
            Reduction::Sum => loss_var.sum(),
        }
    }
}

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

// =============================================================================
// NLLLoss
// =============================================================================

/// Negative Log Likelihood loss.
///
/// Expects input to be log-probabilities.
#[derive(Debug, Clone, Copy)]
pub struct NLLLoss {
    reduction: Reduction,
}

impl NLLLoss {
    /// Creates a new NLLLoss with default reduction (Mean).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
        }
    }

    /// Creates NLLLoss with specified reduction.
    pub fn with_reduction(reduction: Reduction) -> Self {
        Self { reduction }
    }

    /// Computes the loss.
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let input_data = input.data();
        let target_data = target.data();
        let shape = input_data.shape().to_vec();
        let batch_size = shape[0];
        let num_classes = shape[1];

        // NLL forward still needs per-sample gather (index into class dimension).
        // We pull target indices to CPU for the gather but keep input on device.
        let target_vec = target_data.to_vec();
        let input_vec = input_data.to_vec();

        let mut losses = vec![0.0f32; batch_size];
        for b in 0..batch_size {
            let tc = target_vec[b] as usize;
            losses[b] = -input_vec[b * num_classes + tc];
        }

        let mut loss_tensor =
            Tensor::from_vec(losses, &[batch_size]).expect("tensor creation failed");
        if input_data.device().is_gpu() {
            loss_tensor = loss_tensor.to_device(input_data.device()).unwrap();
        }

        let requires_grad = input.requires_grad() && is_grad_enabled();
        let loss_var = if requires_grad {
            let grad_fn = GradFn::new(NLLLossBackward {
                next_fns: vec![input.grad_fn().cloned()],
                target_tensor: target_data.clone(),
                batch_size,
                num_classes,
            });
            Variable::from_operation(loss_tensor, grad_fn, true)
        } else {
            Variable::new(loss_tensor, false)
        };

        match self.reduction {
            Reduction::None => loss_var,
            Reduction::Mean => loss_var.mean(),
            Reduction::Sum => loss_var.sum(),
        }
    }
}

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

// =============================================================================
// NLLLossBackward
// =============================================================================

/// Gradient function for NLLLoss.
///
/// d/d(input)[b, c] = -1 if c == target[b], else 0
///
/// Stores targets as Tensor<f32> (GPU-resident when applicable).
/// The scatter in backward still uses CPU indexing since it's a sparse write,
/// but the result is moved to GPU if needed.
#[derive(Debug)]
struct NLLLossBackward {
    next_fns: Vec<Option<GradFn>>,
    target_tensor: Tensor<f32>,
    batch_size: usize,
    num_classes: usize,
}

impl GradientFunction for NLLLossBackward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        let grad_out_vec = grad_output.to_vec();
        let target_vec = self.target_tensor.to_vec();
        let mut grad_input = vec![0.0f32; self.batch_size * self.num_classes];

        for b in 0..self.batch_size {
            let g = if grad_out_vec.len() == 1 {
                grad_out_vec[0]
            } else {
                grad_out_vec[b]
            };
            let tc = target_vec[b] as usize;
            grad_input[b * self.num_classes + tc] = -g;
        }

        let mut gi = Tensor::from_vec(grad_input, &[self.batch_size, self.num_classes])
            .expect("tensor creation failed");
        if grad_output.device().is_gpu() {
            gi = gi.to_device(grad_output.device()).unwrap();
        }
        vec![Some(gi)]
    }

    fn name(&self) -> &'static str {
        "NLLLossBackward"
    }

    fn next_functions(&self) -> &[Option<GradFn>] {
        &self.next_fns
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// BCELoss
// =============================================================================

/// Binary Cross Entropy loss.
///
/// Expects input to be probabilities in [0, 1].
#[derive(Debug, Clone, Copy)]
pub struct BCELoss {
    reduction: Reduction,
}

impl BCELoss {
    /// Creates a new BCELoss with default reduction (Mean).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
        }
    }

    /// Creates BCELoss with specified reduction.
    pub fn with_reduction(reduction: Reduction) -> Self {
        Self { reduction }
    }

    /// Computes the loss.
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let input_data = input.data();
        let target_data = target.data();

        // Clamp predictions to [eps, 1-eps] using Tensor ops
        let eps = 1e-7f32;
        let p_clamped = axonml_tensor::ops::clamp(&input_data, eps, 1.0 - eps);

        // loss = -(t * ln(p) + (1 - t) * ln(1 - p))
        let ln_p = p_clamped.ln();
        let one_minus_p = p_clamped.neg().add_scalar(1.0);
        let ln_one_minus_p = one_minus_p.ln();
        let one_minus_t = target_data.neg().add_scalar(1.0);

        // t * ln(p)
        let term1 = target_data.mul(&ln_p).expect("tensor mul failed");
        // (1-t) * ln(1-p)
        let term2 = one_minus_t.mul(&ln_one_minus_p).expect("tensor mul failed");
        // -(term1 + term2)
        let loss_tensor = term1.add(&term2).expect("tensor add failed").neg();

        let requires_grad = input.requires_grad() && is_grad_enabled();
        let loss_var = if requires_grad {
            let grad_fn = GradFn::new(BCELossBackward {
                next_fns: vec![input.grad_fn().cloned()],
                input_tensor: input_data,
                target_tensor: target_data,
            });
            Variable::from_operation(loss_tensor, grad_fn, true)
        } else {
            Variable::new(loss_tensor, false)
        };

        match self.reduction {
            Reduction::None => loss_var,
            Reduction::Mean => loss_var.mean(),
            Reduction::Sum => loss_var.sum(),
        }
    }
}

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

// =============================================================================
// BCELossBackward
// =============================================================================

/// Gradient function for BCELoss.
///
/// d/dp BCE = (p - y) / (p * (1 - p))
///
/// Stores input/target as Tensor<f32> (GPU-resident when applicable).
#[derive(Debug)]
struct BCELossBackward {
    next_fns: Vec<Option<GradFn>>,
    input_tensor: Tensor<f32>,
    target_tensor: Tensor<f32>,
}

impl GradientFunction for BCELossBackward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        let eps = 1e-7f32;
        // p_clamped = clamp(input, eps, 1-eps)
        let p_clamped = axonml_tensor::ops::clamp(&self.input_tensor, eps, 1.0 - eps);
        // (p - y)
        let p_minus_y = p_clamped
            .sub(&self.target_tensor)
            .expect("tensor sub failed");
        // p * (1 - p)
        let one_minus_p = p_clamped.neg().add_scalar(1.0);
        let denom = p_clamped.mul(&one_minus_p).expect("tensor mul failed");
        // grad = grad_output * (p - y) / (p * (1 - p))
        let ratio = p_minus_y.div(&denom).unwrap();
        let grad_tensor = grad_output.mul(&ratio).expect("tensor mul failed");
        vec![Some(grad_tensor)]
    }

    fn name(&self) -> &'static str {
        "BCELossBackward"
    }

    fn next_functions(&self) -> &[Option<GradFn>] {
        &self.next_fns
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// BCEWithLogitsBackward
// =============================================================================

/// Gradient function for BCEWithLogitsLoss.
///
/// The gradient of BCE w.r.t. input logits is: sigmoid(input) - target.
///
/// Stores input/target as Tensor<f32> (GPU-resident when applicable).
#[derive(Debug)]
struct BCEWithLogitsBackward {
    next_fns: Vec<Option<GradFn>>,
    input_tensor: Tensor<f32>,
    target_tensor: Tensor<f32>,
}

impl GradientFunction for BCEWithLogitsBackward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        // sigmoid(input) - target, all via Tensor ops (auto-dispatch to GPU)
        let sig = self.input_tensor.sigmoid();
        let sig_minus_t = sig.sub(&self.target_tensor).expect("tensor sub failed");
        let grad_tensor = grad_output.mul(&sig_minus_t).expect("tensor mul failed");
        vec![Some(grad_tensor)]
    }

    fn name(&self) -> &'static str {
        "BCEWithLogitsBackward"
    }

    fn next_functions(&self) -> &[Option<GradFn>] {
        &self.next_fns
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// BCEWithLogitsLoss
// =============================================================================

/// Binary Cross Entropy with Logits.
///
/// Combines sigmoid and BCE in a numerically stable way.
#[derive(Debug, Clone, Copy)]
pub struct BCEWithLogitsLoss {
    reduction: Reduction,
}

impl BCEWithLogitsLoss {
    /// Creates a new BCEWithLogitsLoss with default reduction (Mean).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
        }
    }

    /// Creates BCEWithLogitsLoss with specified reduction.
    pub fn with_reduction(reduction: Reduction) -> Self {
        Self { reduction }
    }

    /// Computes the loss.
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let input_data = input.data();
        let target_data = target.data();

        // Numerically stable: max(x, 0) - x*t + log(1 + exp(-|x|))
        // max(x, 0) = relu(x) = clamp_min(x, 0)
        let relu_x = axonml_tensor::ops::clamp_min(&input_data, 0.0);
        // x * t
        let x_times_t = input_data.mul(&target_data).expect("tensor mul failed");
        // |x| via clamp trick: max(x, 0) + max(-x, 0) = relu(x) + relu(-x)
        let neg_x = input_data.neg();
        let relu_neg_x = axonml_tensor::ops::clamp_min(&neg_x, 0.0);
        let abs_x = relu_x.add(&relu_neg_x).expect("tensor add failed");
        // exp(-|x|)
        let exp_neg_abs = abs_x.neg().exp();
        // log(1 + exp(-|x|))
        let log_term = exp_neg_abs.add_scalar(1.0).ln();
        // loss = relu(x) - x*t + log(1 + exp(-|x|))
        let loss_tensor = relu_x
            .sub(&x_times_t)
            .expect("tensor sub failed")
            .add(&log_term)
            .expect("tensor add failed");

        let loss_var = if input.requires_grad() {
            let grad_fn = GradFn::new(BCEWithLogitsBackward {
                next_fns: vec![input.grad_fn().cloned()],
                input_tensor: input_data,
                target_tensor: target_data,
            });
            Variable::from_operation(loss_tensor, grad_fn, true)
        } else {
            Variable::new(loss_tensor, false)
        };

        match self.reduction {
            Reduction::None => loss_var,
            Reduction::Mean => loss_var.mean(),
            Reduction::Sum => loss_var.sum(),
        }
    }
}

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

// =============================================================================
// SmoothL1Backward
// =============================================================================

/// Gradient function for SmoothL1Loss.
///
/// The gradient is: diff/beta if |diff| < beta, else sign(diff).
/// Returns gradients for both input and target (negated for target).
///
/// Stores diff as Tensor<f32> (GPU-resident when applicable).
#[derive(Debug)]
struct SmoothL1Backward {
    next_fns: Vec<Option<GradFn>>,
    diff_tensor: Tensor<f32>,
    beta: f32,
    shape: Vec<usize>,
}

impl GradientFunction for SmoothL1Backward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        // Compute |diff| = sqrt(diff^2 + eps) to stay differentiable and device-agnostic
        let eps = 1e-12f32;
        let diff_sq = self
            .diff_tensor
            .mul(&self.diff_tensor)
            .expect("tensor mul failed");
        let diff_sq_eps = diff_sq.add_scalar(eps);
        let abs_diff = diff_sq_eps.ln().mul_scalar(0.5).exp();

        // sign(diff) = diff / |diff|
        let sign_diff = self.diff_tensor.div(&abs_diff).unwrap();

        // For the L2 region (|diff| < beta): grad = diff / beta
        // For the L1 region (|diff| >= beta): grad = sign(diff)
        // Blend: mask = clamp(|diff| / beta, 0, 1), but we need a hard cutoff.
        // Use a smooth approximation via where: if |diff| < beta -> diff/beta, else sign
        // Since we need element-wise branching and don't have a GPU where_cond,
        // we use: grad = (1 - mask) * (diff / beta) + mask * sign(diff)
        // where mask = clamp((|diff| - beta) * large_value, 0, 1) approximates step function.
        // Actually simpler: mask_l2 = clamp(1 - |diff|/beta, 0, 1) gives 1 in L2 region, 0 in L1
        // BUT this gives a soft transition. For exact correctness, use CPU branching on the mask.
        //
        // Practical approach: compute both branches with Tensor ops, build mask on CPU, blend.
        let grad_l2 = self.diff_tensor.mul_scalar(1.0 / self.beta); // diff / beta
        let grad_l1 = sign_diff; // sign(diff)

        // Build mask tensor: 1.0 where |d| < beta, 0.0 otherwise
        let abs_vec = abs_diff.to_vec();
        let beta = self.beta;
        let mask_vec: Vec<f32> = abs_vec
            .iter()
            .map(|&a| if a < beta { 1.0 } else { 0.0 })
            .collect();
        let mut mask = Tensor::from_vec(mask_vec, &self.shape).expect("tensor creation failed");
        if self.diff_tensor.device().is_gpu() {
            mask = mask.to_device(self.diff_tensor.device()).unwrap();
        }
        let inv_mask = mask.neg().add_scalar(1.0);

        // grad_per_elem = mask * grad_l2 + (1 - mask) * grad_l1
        let blended = mask
            .mul(&grad_l2)
            .unwrap()
            .add(&inv_mask.mul(&grad_l1).expect("tensor add failed"))
            .unwrap();

        // gi = blended * grad_output
        let gi = blended.mul(grad_output).unwrap();
        let gt = gi.neg();
        vec![Some(gi), Some(gt)]
    }

    fn name(&self) -> &'static str {
        "SmoothL1Backward"
    }

    fn next_functions(&self) -> &[Option<GradFn>] {
        &self.next_fns
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// =============================================================================
// SmoothL1Loss
// =============================================================================

/// Smooth L1 loss (Huber loss).
///
/// Uses L2 loss when |x| < beta, L1 loss otherwise.
#[derive(Debug, Clone, Copy)]
pub struct SmoothL1Loss {
    reduction: Reduction,
    beta: f32,
}

impl SmoothL1Loss {
    /// Creates a new SmoothL1Loss with default beta (1.0).
    pub fn new() -> Self {
        Self {
            reduction: Reduction::Mean,
            beta: 1.0,
        }
    }

    /// Creates SmoothL1Loss with specified beta.
    pub fn with_beta(beta: f32) -> Self {
        Self {
            reduction: Reduction::Mean,
            beta,
        }
    }

    /// Computes the loss.
    pub fn compute(&self, input: &Variable, target: &Variable) -> Variable {
        let input_data = input.data();
        let target_data = target.data();
        let diff_tensor = input_data.sub(&target_data).expect("tensor sub failed");
        let shape = diff_tensor.shape().to_vec();

        // Compute |diff| via relu(diff) + relu(-diff)
        let relu_diff = axonml_tensor::ops::clamp_min(&diff_tensor, 0.0);
        let relu_neg_diff = axonml_tensor::ops::clamp_min(&diff_tensor.neg(), 0.0);
        let abs_diff = relu_diff.add(&relu_neg_diff).expect("tensor add failed");

        // L2 branch: 0.5 * diff^2 / beta
        let diff_sq = diff_tensor.mul(&diff_tensor).expect("tensor mul failed");
        let l2_loss = diff_sq.mul_scalar(0.5 / self.beta);

        // L1 branch: |diff| - 0.5 * beta
        let l1_loss = abs_diff.add_scalar(-0.5 * self.beta);

        // Build mask: 1.0 where |diff| < beta, 0.0 otherwise
        let abs_vec = abs_diff.to_vec();
        let beta = self.beta;
        let mask_vec: Vec<f32> = abs_vec
            .iter()
            .map(|&a| if a < beta { 1.0 } else { 0.0 })
            .collect();
        let mut mask = Tensor::from_vec(mask_vec, &shape).expect("tensor creation failed");
        if diff_tensor.device().is_gpu() {
            mask = mask.to_device(diff_tensor.device()).unwrap();
        }
        let inv_mask = mask.neg().add_scalar(1.0);

        // loss = mask * l2_loss + (1-mask) * l1_loss
        let loss_tensor = mask
            .mul(&l2_loss)
            .unwrap()
            .add(&inv_mask.mul(&l1_loss).expect("tensor add failed"))
            .unwrap();

        let loss_var = if input.requires_grad() || target.requires_grad() {
            let grad_fn = GradFn::new(SmoothL1Backward {
                next_fns: vec![input.grad_fn().cloned(), target.grad_fn().cloned()],
                diff_tensor,
                beta: self.beta,
                shape,
            });
            Variable::from_operation(loss_tensor, grad_fn, true)
        } else {
            Variable::new(loss_tensor, false)
        };

        match self.reduction {
            Reduction::None => loss_var,
            Reduction::Mean => loss_var.mean(),
            Reduction::Sum => loss_var.sum(),
        }
    }
}

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

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_mse_loss() {
        let loss_fn = MSELoss::new();
        let input = Variable::new(
            Tensor::from_vec(vec![1.0, 2.0, 3.0], &[3]).expect("tensor creation failed"),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![1.0, 2.0, 3.0], &[3]).expect("tensor creation failed"),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        assert!((loss.data().to_vec()[0] - 0.0).abs() < 1e-6);
    }

    #[test]
    fn test_mse_loss_nonzero() {
        let loss_fn = MSELoss::new();
        let input = Variable::new(
            Tensor::from_vec(vec![1.0, 2.0, 3.0], &[3]).expect("tensor creation failed"),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![2.0, 3.0, 4.0], &[3]).expect("tensor creation failed"),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        // Each diff is 1.0, squared is 1.0, mean is 1.0
        assert!((loss.data().to_vec()[0] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_cross_entropy_loss() {
        let loss_fn = CrossEntropyLoss::new();
        let input = Variable::new(
            Tensor::from_vec(vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0], &[2, 3])
                .expect("tensor creation failed"),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![2.0, 0.0], &[2]).expect("tensor creation failed"),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        assert!(loss.data().to_vec()[0] > 0.0);
    }

    #[test]
    fn test_bce_loss() {
        let loss_fn = BCELoss::new();
        let input = Variable::new(
            Tensor::from_vec(vec![0.5, 0.5], &[2]).expect("tensor creation failed"),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![1.0, 0.0], &[2]).expect("tensor creation failed"),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        // -[1*ln(0.5) + 0*ln(0.5)] - [0*ln(0.5) + 1*ln(0.5)] = -2*ln(0.5) / 2 = -ln(0.5) = 0.693
        assert!((loss.data().to_vec()[0] - 0.693).abs() < 0.01);
    }

    #[test]
    fn test_cross_entropy_gradient_flow() {
        use axonml_autograd::backward;

        // Create input logits with requires_grad=true
        let input = Variable::new(
            Tensor::from_vec(vec![2.0, 1.0, 0.1, 0.5, 2.5, 0.3], &[2, 3])
                .expect("tensor creation failed"),
            true,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![0.0, 1.0], &[2]).expect("tensor creation failed"),
            false,
        );

        let loss_fn = CrossEntropyLoss::new();
        let loss = loss_fn.compute(&input, &target);

        // Loss should be positive
        let loss_val = loss.data().to_vec()[0];
        assert!(loss_val > 0.0, "Loss should be positive, got {}", loss_val);

        // Backward pass
        let ones = Tensor::from_vec(vec![1.0], &loss.shape()).unwrap();
        backward(&loss, &ones);

        // Input should have gradient
        let grad = input
            .grad()
            .expect("Input should have gradient after backward");
        let grad_vec = grad.to_vec();

        // Gradient should be non-zero
        let grad_norm: f32 = grad_vec.iter().map(|g| g * g).sum();
        assert!(
            grad_norm > 1e-10,
            "Gradient should be non-zero, got norm {}",
            grad_norm
        );

        // Gradient shape should match input shape
        assert_eq!(grad.shape(), &[2, 3]);

        // For the correct class, gradient should be negative (softmax - 1 < 0)
        // Sample 0, class 0 (target): grad should be (softmax[0,0] - 1) / 2
        assert!(
            grad_vec[0] < 0.0,
            "Gradient for correct class should be negative"
        );
        // Sample 1, class 1 (target): grad should be (softmax[1,1] - 1) / 2
        assert!(
            grad_vec[4] < 0.0,
            "Gradient for correct class should be negative"
        );

        // For wrong classes, gradient should be positive (softmax > 0)
        assert!(
            grad_vec[1] > 0.0,
            "Gradient for wrong class should be positive"
        );
        assert!(
            grad_vec[2] > 0.0,
            "Gradient for wrong class should be positive"
        );
    }

    #[test]
    fn test_cross_entropy_perfect_prediction() {
        // When logits strongly favor the correct class, loss should be near zero
        let loss_fn = CrossEntropyLoss::new();
        let input = Variable::new(
            Tensor::from_vec(vec![10.0, -10.0, -10.0], &[1, 3]).expect("tensor creation failed"),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![0.0], &[1]).expect("tensor creation failed"),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        assert!(
            loss.data().to_vec()[0] < 0.001,
            "Perfect prediction should have near-zero loss"
        );
    }

    #[test]
    fn test_cross_entropy_uniform_prediction() {
        // When logits are all equal, loss should be ln(num_classes)
        let loss_fn = CrossEntropyLoss::new();
        let num_classes = 16;
        let input = Variable::new(
            Tensor::from_vec(vec![0.0; num_classes], &[1, num_classes])
                .expect("tensor creation failed"),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![0.0], &[1]).expect("tensor creation failed"),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        let expected = (num_classes as f32).ln(); // ln(16) ≈ 2.77
        let actual = loss.data().to_vec()[0];
        assert!(
            (actual - expected).abs() < 0.01,
            "Uniform logits should give ln(C)={}, got {}",
            expected,
            actual,
        );
    }

    #[test]
    fn test_bce_with_logits_gradient_flow() {
        use axonml_autograd::backward;

        let input = Variable::new(
            Tensor::from_vec(vec![0.5, -0.5, 1.0, -1.0], &[4]).expect("tensor creation failed"),
            true,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![1.0, 0.0, 1.0, 0.0], &[4]).expect("tensor creation failed"),
            false,
        );

        let loss_fn = BCEWithLogitsLoss::new();
        let loss = loss_fn.compute(&input, &target);
        assert!(loss.data().to_vec()[0] > 0.0);

        let ones = Tensor::from_vec(vec![1.0], &loss.shape()).unwrap();
        backward(&loss, &ones);

        let grad = input.grad().expect("Input should have gradient");
        let grad_vec = grad.to_vec();
        assert_eq!(grad_vec.len(), 4);

        // For target=1, grad = sigmoid(x) - 1 < 0
        assert!(grad_vec[0] < 0.0);
        // For target=0, grad = sigmoid(x) > 0
        assert!(grad_vec[1] > 0.0);
    }

    #[test]
    fn test_smooth_l1_gradient_flow() {
        use axonml_autograd::backward;

        let input = Variable::new(
            Tensor::from_vec(vec![1.0, 2.0, 5.0], &[3]).expect("tensor creation failed"),
            true,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![1.5, 1.5, 1.5], &[3]).expect("tensor creation failed"),
            false,
        );

        let loss_fn = SmoothL1Loss::new();
        let loss = loss_fn.compute(&input, &target);
        assert!(loss.data().to_vec()[0] > 0.0);

        let ones = Tensor::from_vec(vec![1.0], &loss.shape()).unwrap();
        backward(&loss, &ones);

        let grad = input.grad().expect("Input should have gradient");
        let grad_vec = grad.to_vec();
        assert_eq!(grad_vec.len(), 3);
        // Gradients should be non-zero
        let grad_norm: f32 = grad_vec.iter().map(|g| g * g).sum();
        assert!(grad_norm > 1e-10);
    }

    // =========================================================================
    // MSE Loss Comprehensive
    // =========================================================================

    #[test]
    fn test_mse_loss_gradient_correctness() {
        use axonml_autograd::backward;

        // MSE gradient = 2*(input - target) / N
        let input = Variable::new(Tensor::from_vec(vec![3.0, 1.0], &[2]).unwrap(), true);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 1.0], &[2]).unwrap(), false);

        let loss = MSELoss::new().compute(&input, &target);
        // loss = ((3-1)^2 + (1-1)^2) / 2 = 4/2 = 2.0
        assert!(
            (loss.data().to_vec()[0] - 2.0).abs() < 1e-5,
            "MSE should be 2.0"
        );

        let ones = Tensor::from_vec(vec![1.0], &loss.shape()).unwrap();
        backward(&loss, &ones);

        let grad = input.grad().expect("Should have gradient");
        let gv = grad.to_vec();
        // dL/dx = 2*(x-t)/N = 2*(3-1)/2 = 2.0 for first, 0.0 for second
        assert!(
            (gv[0] - 2.0).abs() < 0.1,
            "Grad[0] should be ~2.0, got {}",
            gv[0]
        );
        assert!(gv[1].abs() < 0.1, "Grad[1] should be ~0.0, got {}", gv[1]);
    }

    #[test]
    fn test_mse_loss_reduction_sum() {
        let input = Variable::new(Tensor::from_vec(vec![2.0, 4.0], &[2]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 1.0], &[2]).unwrap(), false);
        let loss = MSELoss::with_reduction(Reduction::Sum).compute(&input, &target);
        // sum = (2-1)^2 + (4-1)^2 = 1 + 9 = 10
        assert!((loss.data().to_vec()[0] - 10.0).abs() < 1e-5);
    }

    // =========================================================================
    // L1 Loss
    // =========================================================================

    #[test]
    fn test_l1_loss_basic() {
        let input = Variable::new(Tensor::from_vec(vec![1.0, 5.0, 3.0], &[3]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 2.0, 4.0], &[3]).unwrap(), false);
        let loss = L1Loss::new().compute(&input, &target);
        // mean(|0| + |3| + |-1|) = 4/3 ≈ 1.333
        assert!((loss.data().to_vec()[0] - 4.0 / 3.0).abs() < 1e-4);
    }

    #[test]
    fn test_l1_loss_zero() {
        let input = Variable::new(Tensor::from_vec(vec![1.0, 2.0], &[2]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 2.0], &[2]).unwrap(), false);
        let loss = L1Loss::new().compute(&input, &target);
        assert!(
            loss.data().to_vec()[0].abs() < 1e-6,
            "Identical inputs should give 0 loss"
        );
    }

    // =========================================================================
    // BCE Loss Edge Cases
    // =========================================================================

    #[test]
    fn test_bce_loss_perfect_prediction() {
        let loss_fn = BCELoss::new();
        // Near-perfect predictions
        let input = Variable::new(Tensor::from_vec(vec![0.999, 0.001], &[2]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 0.0], &[2]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        assert!(
            loss.data().to_vec()[0] < 0.01,
            "Perfect prediction should have near-zero loss"
        );
    }

    #[test]
    fn test_bce_loss_worst_prediction() {
        let loss_fn = BCELoss::new();
        // Worst predictions (inverted)
        let input = Variable::new(Tensor::from_vec(vec![0.001, 0.999], &[2]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 0.0], &[2]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        // Should be high
        assert!(
            loss.data().to_vec()[0] > 3.0,
            "Worst prediction should have high loss"
        );
    }

    // =========================================================================
    // BCEWithLogitsLoss Comprehensive
    // =========================================================================

    #[test]
    fn test_bce_with_logits_numerical_stability() {
        let loss_fn = BCEWithLogitsLoss::new();
        // Very large logits should not produce NaN/Inf
        let input = Variable::new(
            Tensor::from_vec(vec![100.0, -100.0, 50.0, -50.0], &[4]).unwrap(),
            false,
        );
        let target = Variable::new(
            Tensor::from_vec(vec![1.0, 0.0, 1.0, 0.0], &[4]).unwrap(),
            false,
        );
        let loss = loss_fn.compute(&input, &target);
        let val = loss.data().to_vec()[0];
        assert!(
            val.is_finite(),
            "Loss should be finite for large logits, got {}",
            val
        );
        assert!(val >= 0.0, "BCE loss should be non-negative");
    }

    #[test]
    fn test_bce_with_logits_zero_logits() {
        let loss_fn = BCEWithLogitsLoss::new();
        // Zero logits → sigmoid(0) = 0.5 → random prediction
        let input = Variable::new(Tensor::from_vec(vec![0.0, 0.0], &[2]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 0.0], &[2]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        // Should be ln(2) ≈ 0.693
        assert!((loss.data().to_vec()[0] - 0.693).abs() < 0.01);
    }

    #[test]
    fn test_bce_with_logits_reduction_none() {
        let loss_fn = BCEWithLogitsLoss::with_reduction(Reduction::None);
        let input = Variable::new(Tensor::from_vec(vec![0.0, 0.0, 0.0], &[3]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.0, 0.0, 1.0], &[3]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        // Should return per-element losses, not reduced
        assert_eq!(loss.shape().len(), 1);
        assert_eq!(loss.shape()[0], 3);
    }

    // =========================================================================
    // SmoothL1 Loss
    // =========================================================================

    #[test]
    fn test_smooth_l1_small_error() {
        // For |diff| < beta=1.0: loss = 0.5 * diff^2 / beta
        let loss_fn = SmoothL1Loss::new();
        let input = Variable::new(Tensor::from_vec(vec![1.0], &[1]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![1.3], &[1]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        // diff=0.3, |0.3| < 1.0, loss = 0.5 * 0.09 / 1.0 = 0.045
        assert!((loss.data().to_vec()[0] - 0.045).abs() < 0.01);
    }

    #[test]
    fn test_smooth_l1_large_error() {
        // For |diff| >= beta=1.0: loss = |diff| - 0.5*beta
        let loss_fn = SmoothL1Loss::new();
        let input = Variable::new(Tensor::from_vec(vec![0.0], &[1]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![5.0], &[1]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        // diff=5.0, |5| >= 1.0, loss = 5.0 - 0.5 = 4.5
        assert!((loss.data().to_vec()[0] - 4.5).abs() < 0.1);
    }

    // =========================================================================
    // Cross-Entropy Batch Consistency
    // =========================================================================

    #[test]
    fn test_cross_entropy_batch_independence() {
        let loss_fn = CrossEntropyLoss::new();

        // Single sample
        let input1 = Variable::new(
            Tensor::from_vec(vec![2.0, 1.0, 0.1], &[1, 3]).unwrap(),
            false,
        );
        let target1 = Variable::new(Tensor::from_vec(vec![0.0], &[1]).unwrap(), false);
        let loss1 = loss_fn.compute(&input1, &target1).data().to_vec()[0];

        // Same sample duplicated in batch
        let input2 = Variable::new(
            Tensor::from_vec(vec![2.0, 1.0, 0.1, 2.0, 1.0, 0.1], &[2, 3]).unwrap(),
            false,
        );
        let target2 = Variable::new(Tensor::from_vec(vec![0.0, 0.0], &[2]).unwrap(), false);
        let loss2 = loss_fn.compute(&input2, &target2).data().to_vec()[0];

        // Mean reduction should give same result for duplicated batch
        assert!(
            (loss1 - loss2).abs() < 1e-5,
            "Duplicated batch should give same loss: {} vs {}",
            loss1,
            loss2
        );
    }

    #[test]
    fn test_cross_entropy_high_class_count() {
        // Test with many classes (like BirdCLEF 234 species)
        let n_classes = 100;
        let mut logits = vec![0.0f32; n_classes];
        logits[42] = 5.0; // Correct class has high logit

        let loss_fn = CrossEntropyLoss::new();
        let input = Variable::new(Tensor::from_vec(logits, &[1, n_classes]).unwrap(), false);
        let target = Variable::new(Tensor::from_vec(vec![42.0], &[1]).unwrap(), false);
        let loss = loss_fn.compute(&input, &target);
        let val = loss.data().to_vec()[0];
        assert!(val.is_finite(), "Should handle 100 classes");
        assert!(val < 1.0, "Correct class should have low loss, got {}", val);
    }
}