axonml-vision 0.4.2

Computer vision utilities for the 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
//! COCO Evaluation Benchmarks — Full Detection Model Evaluation Suite
//!
//! # File
//! `crates/axonml-vision/src/training/coco_bench.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.

#![allow(dead_code)]

use axonml_autograd::Variable;
use axonml_tensor::Tensor;

use crate::datasets::CocoAnnotation;
use crate::ops::Detection;
use crate::training::metrics::{DetectionResult, GroundTruth, compute_coco_map, compute_map};

// =============================================================================
// Conversion Helpers
// =============================================================================

/// Convert a `Detection` (pixel coords) to `DetectionResult` (normalized [0,1]).
fn detection_to_result(det: &Detection, img_w: f32, img_h: f32) -> DetectionResult {
    DetectionResult {
        bbox: [
            (det.bbox[0] / img_w).clamp(0.0, 1.0),
            (det.bbox[1] / img_h).clamp(0.0, 1.0),
            (det.bbox[2] / img_w).clamp(0.0, 1.0),
            (det.bbox[3] / img_h).clamp(0.0, 1.0),
        ],
        confidence: det.confidence,
        class_id: det.class_id,
    }
}

/// Convert a `CocoAnnotation` (already normalized [0,1]) to `GroundTruth`.
fn annotation_to_gt(anno: &CocoAnnotation) -> GroundTruth {
    GroundTruth {
        bbox: anno.bbox,
        class_id: anno.category_id,
    }
}

// =============================================================================
// Evaluation Runner (public API)
// =============================================================================

/// Evaluate Helios on a COCO dataset, returning (mAP@50, COCO_mAP@[0.5:0.95]).
pub fn evaluate_helios_coco(
    model: &crate::models::helios::Helios,
    dataset: &crate::datasets::CocoDataset,
    input_size: (usize, usize),
    score_threshold: f32,
    nms_threshold: f32,
    max_images: usize,
) -> (f32, f32) {
    let num_classes = dataset.num_classes();
    let n = if max_images > 0 && max_images < dataset.len() {
        max_images
    } else {
        dataset.len()
    };

    let (img_h, img_w) = (input_size.0 as f32, input_size.1 as f32);

    let mut all_detections: Vec<Vec<DetectionResult>> = Vec::with_capacity(n);
    let mut all_ground_truths: Vec<Vec<GroundTruth>> = Vec::with_capacity(n);

    for i in 0..n {
        if let Some((img_tensor, annotations)) = dataset.get(i) {
            let input = Variable::new(img_tensor, false);
            let dets = model.detect(&input, score_threshold, nms_threshold);

            let det_results: Vec<DetectionResult> = dets
                .iter()
                .map(|d| detection_to_result(d, img_w, img_h))
                .collect();

            let gts: Vec<GroundTruth> = annotations.iter().map(annotation_to_gt).collect();

            all_detections.push(det_results);
            all_ground_truths.push(gts);
        }
    }

    if all_detections.is_empty() {
        return (0.0, 0.0);
    }

    let map50 = compute_map(&all_detections, &all_ground_truths, num_classes, 0.5);
    let coco_map = compute_coco_map(&all_detections, &all_ground_truths, num_classes);

    (map50, coco_map)
}

// =============================================================================
// Internal Benchmark Infrastructure
// =============================================================================

/// Comprehensive evaluation result with per-IoU breakdown.
struct FullEvalResult {
    name: String,
    resolution: String,
    params: usize,
    size_mb: f64,
    n_images: usize,
    total_dets: usize,
    total_gts: usize,
    avg_dets_per_image: f64,
    avg_confidence: f64,
    avg_box_area: f64,
    map50: f32,
    map75: f32,
    coco_map: f32,
    warmup_ms: f64,
    latency_ms: f64,
    fps: f64,
    p50_latency_ms: f64,
    p95_latency_ms: f64,
}

impl FullEvalResult {
    fn print(&self) {
        println!("  {:<20} {}", "Model:", self.name);
        println!("  {:<20} {}", "Resolution:", self.resolution);
        println!(
            "  {:<20} {} ({:.2} MB f32)",
            "Parameters:", self.params, self.size_mb
        );
        println!("  {:<20} {}", "Images:", self.n_images);
        println!(
            "  {:<20} {} (avg {:.1}/img)",
            "Detections:", self.total_dets, self.avg_dets_per_image
        );
        println!("  {:<20} {}", "Ground Truths:", self.total_gts);
        println!("  {:<20} {:.4}", "Avg Confidence:", self.avg_confidence);
        println!("  {:<20} {:.4}", "Avg Box Area:", self.avg_box_area);
        println!("  {:<20} {:.4}", "mAP@50:", self.map50);
        println!("  {:<20} {:.4}", "mAP@75:", self.map75);
        println!("  {:<20} {:.4}", "COCO mAP@[.5:.95]:", self.coco_map);
        println!("  {:<20} {:.1}ms", "Warmup latency:", self.warmup_ms);
        println!(
            "  {:<20} {:.1}ms (mean)",
            "Inference latency:", self.latency_ms
        );
        println!("  {:<20} {:.1}ms", "P50 latency:", self.p50_latency_ms);
        println!("  {:<20} {:.1}ms", "P95 latency:", self.p95_latency_ms);
        println!("  {:<20} {:.1}", "Throughput (FPS):", self.fps);
    }
}

/// Generate diverse synthetic ground truth for benchmark evaluation.
///
/// Produces varied box sizes, positions, and aspect ratios to stress-test
/// detection pipelines beyond trivial 2-box-per-image patterns.
fn diverse_gt(image_idx: usize, num_classes: usize) -> Vec<GroundTruth> {
    // Deterministic pseudo-random from image index
    let seed = image_idx as f32;
    let hash = |v: f32| -> f32 { ((v * 127.1 + 311.7).sin() * 43_758.547).fract().abs() };

    let n_boxes = 2 + (hash(seed) * 4.0) as usize; // 2-5 boxes per image
    let mut gts = Vec::with_capacity(n_boxes);

    for b in 0..n_boxes {
        let h1 = hash(seed + b as f32 * 7.3);
        let h2 = hash(seed + b as f32 * 13.1 + 1.0);
        let h3 = hash(seed + b as f32 * 23.7 + 2.0);
        let h4 = hash(seed + b as f32 * 37.9 + 3.0);

        // Varied box sizes: small (0.05-0.15), medium (0.15-0.35), large (0.35-0.6)
        let size_class = (h1 * 3.0) as usize;
        let (min_s, max_s) = match size_class {
            0 => (0.05, 0.15), // small objects
            1 => (0.15, 0.35), // medium objects
            _ => (0.35, 0.60), // large objects
        };
        let w = min_s + h2 * (max_s - min_s);
        let h = min_s + h3 * (max_s - min_s);

        // Random position (ensure box stays within [0,1])
        let x1 = h4 * (1.0 - w);
        let y1 = hash(seed + b as f32 * 51.3 + 4.0) * (1.0 - h);

        let class_id = ((image_idx + b) * 7 + b * 3) % num_classes;

        gts.push(GroundTruth {
            bbox: [x1, y1, x1 + w, y1 + h],
            class_id,
        });
    }

    gts
}

/// Create a synthetic input tensor with varied pixel patterns.
fn make_input(image_idx: usize, h: usize, w: usize) -> Variable {
    let size = 3 * h * w;
    let mut data = Vec::with_capacity(size);
    let base = 0.2 + ((image_idx as f32 * 0.37).sin().abs() * 0.6);

    for c in 0..3 {
        for y in 0..h {
            for x in 0..w {
                // Gradient + noise pattern per channel
                let gx = x as f32 / w as f32;
                let gy = y as f32 / h as f32;
                let v = base + (c as f32 * 0.1) + (gx * 0.2) - (gy * 0.1);
                data.push(v.clamp(0.0, 1.0));
            }
        }
    }

    Variable::new(Tensor::from_vec(data, &[1, 3, h, w]).unwrap(), false)
}

/// Run a full evaluation with warmup, multi-image inference, and statistics.
fn run_full_eval<F>(
    name: &str,
    resolution: &str,
    param_count: usize,
    input_size: (usize, usize),
    num_classes: usize,
    n_images: usize,
    warmup_images: usize,
    detect_fn: &mut F,
) -> FullEvalResult
where
    F: FnMut(Variable, f32, f32) -> Vec<DetectionResult>,
{
    let (ih, iw) = input_size;
    let img_w = iw as f32;
    let img_h = ih as f32;

    // Warmup phase (not timed for throughput, but measured separately)
    let warmup_start = std::time::Instant::now();
    for i in 0..warmup_images {
        let input = make_input(1000 + i, ih, iw);
        let _ = detect_fn(input, img_w, img_h);
    }
    let warmup_ms = warmup_start.elapsed().as_secs_f64() * 1000.0 / warmup_images.max(1) as f64;

    // Timed evaluation phase
    let mut all_detections: Vec<Vec<DetectionResult>> = Vec::with_capacity(n_images);
    let mut all_ground_truths: Vec<Vec<GroundTruth>> = Vec::with_capacity(n_images);
    let mut per_image_times: Vec<f64> = Vec::with_capacity(n_images);
    let mut all_confidences: Vec<f32> = Vec::new();
    let mut all_box_areas: Vec<f32> = Vec::new();

    for i in 0..n_images {
        let input = make_input(i, ih, iw);
        let gts = diverse_gt(i, num_classes);

        let t0 = std::time::Instant::now();
        let det_results = detect_fn(input, img_w, img_h);
        let dt = t0.elapsed().as_secs_f64() * 1000.0;
        per_image_times.push(dt);

        // Collect statistics
        for d in &det_results {
            all_confidences.push(d.confidence);
            let bw = (d.bbox[2] - d.bbox[0]).abs();
            let bh = (d.bbox[3] - d.bbox[1]).abs();
            all_box_areas.push(bw * bh);
        }

        all_detections.push(det_results);
        all_ground_truths.push(gts);
    }

    // Compute metrics
    let map50 = compute_map(&all_detections, &all_ground_truths, num_classes, 0.5);
    let map75 = compute_map(&all_detections, &all_ground_truths, num_classes, 0.75);
    let coco_map = compute_coco_map(&all_detections, &all_ground_truths, num_classes);

    // Latency statistics
    per_image_times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let mean_ms = per_image_times.iter().sum::<f64>() / n_images as f64;
    let p50_ms = per_image_times[n_images / 2];
    let p95_idx = (n_images as f64 * 0.95) as usize;
    let p95_ms = per_image_times[p95_idx.min(n_images - 1)];

    // Detection statistics
    let total_dets: usize = all_detections.iter().map(|d| d.len()).sum();
    let total_gts: usize = all_ground_truths.iter().map(|g| g.len()).sum();
    let avg_conf = if all_confidences.is_empty() {
        0.0
    } else {
        all_confidences.iter().sum::<f32>() as f64 / all_confidences.len() as f64
    };
    let avg_area = if all_box_areas.is_empty() {
        0.0
    } else {
        all_box_areas.iter().sum::<f32>() as f64 / all_box_areas.len() as f64
    };

    FullEvalResult {
        name: name.to_string(),
        resolution: resolution.to_string(),
        params: param_count,
        size_mb: param_count as f64 * 4.0 / 1_048_576.0,
        n_images,
        total_dets,
        total_gts,
        avg_dets_per_image: total_dets as f64 / n_images as f64,
        avg_confidence: avg_conf,
        avg_box_area: avg_area,
        map50,
        map75,
        coco_map,
        warmup_ms,
        latency_ms: mean_ms,
        fps: 1000.0 / mean_ms,
        p50_latency_ms: p50_ms,
        p95_latency_ms: p95_ms,
    }
}

fn print_summary_table(results: &[FullEvalResult]) {
    println!(
        "\n  {:<18} {:>6} {:>7} {:>6} {:>8} {:>8} {:>8} {:>9} {:>9} {:>6}",
        "Model",
        "Res",
        "Params",
        "MB",
        "mAP@50",
        "mAP@75",
        "COCO mAP",
        "Mean(ms)",
        "P95(ms)",
        "FPS"
    );
    println!("  {}", "-".repeat(104));
    for r in results {
        println!(
            "  {:<18} {:>6} {:>7} {:>5.1} {:>8.4} {:>8.4} {:>8.4} {:>8.1}ms {:>8.1}ms {:>6.1}",
            r.name,
            r.resolution,
            format_params(r.params),
            r.size_mb,
            r.map50,
            r.map75,
            r.coco_map,
            r.latency_ms,
            r.p95_latency_ms,
            r.fps
        );
    }
}

fn format_params(p: usize) -> String {
    if p >= 1_000_000 {
        format!("{:.1}M", p as f64 / 1_000_000.0)
    } else if p >= 1_000 {
        format!("{:.0}K", p as f64 / 1_000.0)
    } else {
        format!("{p}")
    }
}

fn print_detection_stats(results: &[FullEvalResult]) {
    println!(
        "\n  {:<18} {:>6} {:>8} {:>10} {:>10} {:>10}",
        "Model", "Res", "Dets", "Avg/Img", "Avg Conf", "Avg Area"
    );
    println!("  {}", "-".repeat(72));
    for r in results {
        println!(
            "  {:<18} {:>6} {:>8} {:>10.1} {:>10.4} {:>10.4}",
            r.name,
            r.resolution,
            r.total_dets,
            r.avg_dets_per_image,
            r.avg_confidence,
            r.avg_box_area
        );
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use axonml_nn::Module;
    use std::time::Instant;

    fn count_params(params: &[axonml_nn::Parameter]) -> usize {
        params
            .iter()
            .map(|p| p.variable().data().to_vec().len())
            .sum()
    }

    // =========================================================================
    // Helios Multi-Resolution Benchmark
    // =========================================================================

    #[test]
    fn coco_bench_helios_multiresolution() {
        let num_classes = 20;

        println!("\n{}", "=".repeat(80));
        println!("  HELIOS MULTI-RESOLUTION COCO BENCHMARK");
        println!("  Classes: {num_classes} | Images: 50/res | Warmup: 3");
        println!("{}", "=".repeat(80));

        let mut results = Vec::new();

        // Helios-Nano at 128, 320
        {
            use crate::models::helios::Helios;
            let model = Helios::nano(num_classes);
            let pc = count_params(&model.parameters());

            for &(h, w, label) in &[(128, 128, "128"), (320, 320, "320")] {
                println!("\n--- Helios-Nano @ {label}x{label} ---");
                let r = run_full_eval(
                    "Helios-Nano",
                    label,
                    pc,
                    (h, w),
                    num_classes,
                    50,
                    3,
                    &mut |input, iw, ih| {
                        model
                            .detect(&input, 0.001, 0.45)
                            .iter()
                            .map(|d| detection_to_result(d, iw, ih))
                            .collect()
                    },
                );
                r.print();
                results.push(r);
            }
        }

        // Helios-Small at 128, 320
        {
            use crate::models::helios::Helios;
            let model = Helios::small(num_classes);
            let pc = count_params(&model.parameters());

            for &(h, w, label) in &[(128, 128, "128"), (320, 320, "320")] {
                println!("\n--- Helios-Small @ {label}x{label} ---");
                let r = run_full_eval(
                    "Helios-Small",
                    label,
                    pc,
                    (h, w),
                    num_classes,
                    30,
                    2,
                    &mut |input, iw, ih| {
                        model
                            .detect(&input, 0.001, 0.45)
                            .iter()
                            .map(|d| detection_to_result(d, iw, ih))
                            .collect()
                    },
                );
                r.print();
                results.push(r);
            }
        }

        println!("\n{}", "=".repeat(80));
        println!("  HELIOS SUMMARY");
        print_summary_table(&results);
        print_detection_stats(&results);
        println!("{}\n", "=".repeat(80));

        for r in &results {
            assert!(
                r.map50.is_finite(),
                "{} {}: mAP@50 not finite",
                r.name,
                r.resolution
            );
            assert!(
                r.coco_map.is_finite(),
                "{} {}: COCO mAP not finite",
                r.name,
                r.resolution
            );
        }
    }

    // =========================================================================
    // NanoDet Multi-Resolution Benchmark
    // =========================================================================

    #[test]
    fn coco_bench_nanodet_multiresolution() {
        let num_classes = 20;

        println!("\n{}", "=".repeat(80));
        println!("  NANODET MULTI-RESOLUTION COCO BENCHMARK");
        println!("  Classes: {num_classes} | Images: 50/res | Warmup: 3");
        println!("{}", "=".repeat(80));

        let mut results = Vec::new();

        use crate::models::nanodet::NanoDet;
        let model = NanoDet::new(num_classes);
        let pc = count_params(&model.parameters());

        for &(h, w, label) in &[(128, 128, "128"), (320, 320, "320")] {
            println!("\n--- NanoDet @ {label}x{label} ---");
            let r = run_full_eval(
                "NanoDet",
                label,
                pc,
                (h, w),
                num_classes,
                50,
                3,
                &mut |input, iw, ih| {
                    model
                        .detect(&input, 0.001, 0.45)
                        .iter()
                        .map(|d| detection_to_result(d, iw, ih))
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        println!("\n{}", "=".repeat(80));
        println!("  NANODET SUMMARY");
        print_summary_table(&results);
        print_detection_stats(&results);
        println!("{}\n", "=".repeat(80));

        for r in &results {
            assert!(r.map50.is_finite());
        }
    }

    // =========================================================================
    // Nexus Multi-Resolution Benchmark
    // =========================================================================

    #[test]
    fn coco_bench_nexus_multiresolution() {
        let num_classes = 20;

        println!("\n{}", "=".repeat(80));
        println!("  NEXUS MULTI-RESOLUTION COCO BENCHMARK");
        println!("  Classes: {num_classes} | Images: 50/res | Warmup: 3");
        println!("{}", "=".repeat(80));

        let mut results = Vec::new();

        use crate::models::nexus::Nexus;
        let mut model = Nexus::new();
        model.eval();
        let pc = count_params(&model.parameters());

        for &(h, w, label) in &[(64, 64, "64"), (128, 128, "128")] {
            model.reset();
            println!("\n--- Nexus @ {label}x{label} ---");
            let r = run_full_eval(
                "Nexus",
                label,
                pc,
                (h, w),
                num_classes,
                50,
                3,
                &mut |input, iw, ih| {
                    let dets = model.detect(&input);
                    dets.iter()
                        .map(|d| DetectionResult {
                            bbox: [
                                (d.bbox_mean[0] / iw).clamp(0.0, 1.0),
                                (d.bbox_mean[1] / ih).clamp(0.0, 1.0),
                                (d.bbox_mean[2] / iw).clamp(0.0, 1.0),
                                (d.bbox_mean[3] / ih).clamp(0.0, 1.0),
                            ],
                            confidence: d.confidence,
                            class_id: d.class_id,
                        })
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        println!("\n{}", "=".repeat(80));
        println!("  NEXUS SUMMARY");
        print_summary_table(&results);
        print_detection_stats(&results);
        println!("{}\n", "=".repeat(80));

        for r in &results {
            assert!(r.map50.is_finite());
        }
    }

    // =========================================================================
    // Face Detectors Benchmark (Phantom, BlazeFace, RetinaFace)
    // =========================================================================

    #[test]
    fn coco_bench_face_detectors() {
        println!("\n{}", "=".repeat(80));
        println!("  FACE DETECTOR COCO BENCHMARK");
        println!("  Task: Face detection (1 class) | Images: 50/model | Warmup: 3");
        println!("{}", "=".repeat(80));

        let mut results = Vec::new();
        let num_classes = 1;

        let _face_gt = |image_idx: usize, _nc: usize| -> Vec<GroundTruth> {
            // Diverse face-like ground truth
            let h = |v: f32| -> f32 { ((v * 127.1 + 311.7).sin() * 43758.5453).fract().abs() };
            let n = 1 + (h(image_idx as f32) * 3.0) as usize; // 1-3 faces
            (0..n)
                .map(|b| {
                    let s = 0.08 + h(image_idx as f32 + b as f32 * 11.3) * 0.35;
                    let x = h(image_idx as f32 + b as f32 * 23.7) * (1.0 - s);
                    let y = h(image_idx as f32 + b as f32 * 37.1) * (1.0 - s);
                    GroundTruth {
                        bbox: [x, y, x + s, y + s * 1.2],
                        class_id: 0,
                    }
                })
                .collect()
        };

        // Phantom
        {
            use crate::models::phantom::Phantom;
            let mut model = Phantom::new();
            model.eval();
            let pc = count_params(&model.parameters());

            for &(h, w, label) in &[(64, 64, "64"), (128, 128, "128")] {
                model.reset();
                println!("\n--- Phantom @ {label}x{label} ---");
                let r = run_full_eval(
                    "Phantom",
                    label,
                    pc,
                    (h, w),
                    num_classes,
                    50,
                    3,
                    &mut |input, iw, ih| {
                        let dets = model.detect_frame(&input);
                        dets.iter()
                            .map(|d| DetectionResult {
                                bbox: [
                                    (d.bbox[0] / iw).clamp(0.0, 1.0),
                                    (d.bbox[1] / ih).clamp(0.0, 1.0),
                                    (d.bbox[2] / iw).clamp(0.0, 1.0),
                                    (d.bbox[3] / ih).clamp(0.0, 1.0),
                                ],
                                confidence: d.confidence,
                                class_id: 0,
                            })
                            .collect()
                    },
                );
                r.print();
                results.push(r);
            }
        }

        // BlazeFace
        {
            use crate::models::blazeface::BlazeFace;
            let model = BlazeFace::new();
            let pc = count_params(&model.parameters());

            for &(h, w, label) in &[(128, 128, "128"), (256, 256, "256")] {
                println!("\n--- BlazeFace @ {label}x{label} ---");
                let r = run_full_eval(
                    "BlazeFace",
                    label,
                    pc,
                    (h, w),
                    num_classes,
                    50,
                    3,
                    &mut |input, iw, ih| {
                        let dets = model.detect(&input, 0.001, 0.45);
                        dets.iter()
                            .map(|d| DetectionResult {
                                bbox: [
                                    (d.bbox[0] / iw).clamp(0.0, 1.0),
                                    (d.bbox[1] / ih).clamp(0.0, 1.0),
                                    (d.bbox[2] / iw).clamp(0.0, 1.0),
                                    (d.bbox[3] / ih).clamp(0.0, 1.0),
                                ],
                                confidence: d.confidence,
                                class_id: 0,
                            })
                            .collect()
                    },
                );
                r.print();
                results.push(r);
            }
        }

        // RetinaFace
        {
            use crate::models::retinaface::RetinaFace;
            let model = RetinaFace::new();
            let pc = count_params(&model.parameters());

            for &(h, w, label) in &[(128, 128, "128"), (320, 320, "320")] {
                println!("\n--- RetinaFace @ {label}x{label} ---");
                let r = run_full_eval(
                    "RetinaFace",
                    label,
                    pc,
                    (h, w),
                    num_classes,
                    50,
                    3,
                    &mut |input, iw, ih| {
                        let dets = model.detect(&input, 0.001, 0.45);
                        dets.iter()
                            .map(|d| DetectionResult {
                                bbox: [
                                    (d.bbox[0] / iw).clamp(0.0, 1.0),
                                    (d.bbox[1] / ih).clamp(0.0, 1.0),
                                    (d.bbox[2] / iw).clamp(0.0, 1.0),
                                    (d.bbox[3] / ih).clamp(0.0, 1.0),
                                ],
                                confidence: d.confidence,
                                class_id: 0,
                            })
                            .collect()
                    },
                );
                r.print();
                results.push(r);
            }
        }

        println!("\n{}", "=".repeat(80));
        println!("  FACE DETECTOR SUMMARY");
        print_summary_table(&results);
        print_detection_stats(&results);
        println!("{}\n", "=".repeat(80));

        for r in &results {
            assert!(r.map50.is_finite());
        }
    }

    // =========================================================================
    // Cross-Model Comparison (all models, single resolution)
    // =========================================================================

    #[test]
    fn coco_bench_all_models_comparison() {
        let num_classes = 20;
        let n_images = 50;

        println!("\n{}", "=".repeat(80));
        println!("  ALL-MODEL COMPARISON BENCHMARK");
        println!("  Classes: {num_classes} | Images: {n_images} | Conf: 0.001 | NMS: 0.45");
        println!("{}", "=".repeat(80));

        let mut results = Vec::new();

        // Helios-Nano @ 128
        {
            use crate::models::helios::Helios;
            let model = Helios::nano(num_classes);
            let pc = count_params(&model.parameters());
            println!("\n--- Helios-Nano ---");
            let r = run_full_eval(
                "Helios-Nano",
                "128",
                pc,
                (128, 128),
                num_classes,
                n_images,
                3,
                &mut |input, iw, ih| {
                    model
                        .detect(&input, 0.001, 0.45)
                        .iter()
                        .map(|d| detection_to_result(d, iw, ih))
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        // NanoDet @ 128
        {
            use crate::models::nanodet::NanoDet;
            let model = NanoDet::new(num_classes);
            let pc = count_params(&model.parameters());
            println!("\n--- NanoDet ---");
            let r = run_full_eval(
                "NanoDet",
                "128",
                pc,
                (128, 128),
                num_classes,
                n_images,
                3,
                &mut |input, iw, ih| {
                    model
                        .detect(&input, 0.001, 0.45)
                        .iter()
                        .map(|d| detection_to_result(d, iw, ih))
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        // Nexus @ 64
        {
            use crate::models::nexus::Nexus;
            let mut model = Nexus::new();
            model.eval();
            let pc = count_params(&model.parameters());
            println!("\n--- Nexus ---");
            let r = run_full_eval(
                "Nexus",
                "64",
                pc,
                (64, 64),
                num_classes,
                n_images,
                3,
                &mut |input, iw, ih| {
                    let dets = model.detect(&input);
                    dets.iter()
                        .map(|d| DetectionResult {
                            bbox: [
                                (d.bbox_mean[0] / iw).clamp(0.0, 1.0),
                                (d.bbox_mean[1] / ih).clamp(0.0, 1.0),
                                (d.bbox_mean[2] / iw).clamp(0.0, 1.0),
                                (d.bbox_mean[3] / ih).clamp(0.0, 1.0),
                            ],
                            confidence: d.confidence,
                            class_id: d.class_id,
                        })
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        // Phantom @ 64 (1 class)
        {
            use crate::models::phantom::Phantom;
            let mut model = Phantom::new();
            model.eval();
            let pc = count_params(&model.parameters());
            println!("\n--- Phantom ---");
            let r = run_full_eval(
                "Phantom",
                "64",
                pc,
                (64, 64),
                1,
                n_images,
                3,
                &mut |input, iw, ih| {
                    model
                        .detect_frame(&input)
                        .iter()
                        .map(|d| DetectionResult {
                            bbox: [
                                (d.bbox[0] / iw).clamp(0.0, 1.0),
                                (d.bbox[1] / ih).clamp(0.0, 1.0),
                                (d.bbox[2] / iw).clamp(0.0, 1.0),
                                (d.bbox[3] / ih).clamp(0.0, 1.0),
                            ],
                            confidence: d.confidence,
                            class_id: 0,
                        })
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        // BlazeFace @ 128 (1 class)
        {
            use crate::models::blazeface::BlazeFace;
            let model = BlazeFace::new();
            let pc = count_params(&model.parameters());
            println!("\n--- BlazeFace ---");
            let r = run_full_eval(
                "BlazeFace",
                "128",
                pc,
                (128, 128),
                1,
                n_images,
                3,
                &mut |input, iw, ih| {
                    model
                        .detect(&input, 0.001, 0.45)
                        .iter()
                        .map(|d| DetectionResult {
                            bbox: [
                                (d.bbox[0] / iw).clamp(0.0, 1.0),
                                (d.bbox[1] / ih).clamp(0.0, 1.0),
                                (d.bbox[2] / iw).clamp(0.0, 1.0),
                                (d.bbox[3] / ih).clamp(0.0, 1.0),
                            ],
                            confidence: d.confidence,
                            class_id: 0,
                        })
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        // RetinaFace @ 128 (1 class)
        {
            use crate::models::retinaface::RetinaFace;
            let model = RetinaFace::new();
            let pc = count_params(&model.parameters());
            println!("\n--- RetinaFace ---");
            let r = run_full_eval(
                "RetinaFace",
                "128",
                pc,
                (128, 128),
                1,
                n_images,
                3,
                &mut |input, iw, ih| {
                    model
                        .detect(&input, 0.001, 0.45)
                        .iter()
                        .map(|d| DetectionResult {
                            bbox: [
                                (d.bbox[0] / iw).clamp(0.0, 1.0),
                                (d.bbox[1] / ih).clamp(0.0, 1.0),
                                (d.bbox[2] / iw).clamp(0.0, 1.0),
                                (d.bbox[3] / ih).clamp(0.0, 1.0),
                            ],
                            confidence: d.confidence,
                            class_id: 0,
                        })
                        .collect()
                },
            );
            r.print();
            results.push(r);
        }

        println!("\n{}", "=".repeat(80));
        println!("  ALL-MODEL COMPARISON");
        print_summary_table(&results);
        println!();
        print_detection_stats(&results);
        println!("{}\n", "=".repeat(80));

        for r in &results {
            assert!(r.map50.is_finite(), "{}: mAP@50 not finite", r.name);
            assert!(r.coco_map.is_finite(), "{}: COCO mAP not finite", r.name);
            assert!(r.map50 >= 0.0 && r.map50 <= 1.0);
            assert!(r.coco_map >= 0.0 && r.coco_map <= 1.0);
        }
    }

    // =========================================================================
    // mAP Pipeline Validation
    // =========================================================================

    #[test]
    fn coco_bench_map_validation() {
        println!("\n{}", "=".repeat(80));
        println!("  mAP PIPELINE VALIDATION");
        println!("{}", "=".repeat(80));

        // Test 1: Perfect detections
        {
            let num_classes = 3;
            let all_dets = vec![
                vec![
                    DetectionResult {
                        bbox: [0.1, 0.1, 0.4, 0.4],
                        confidence: 0.95,
                        class_id: 0,
                    },
                    DetectionResult {
                        bbox: [0.5, 0.5, 0.9, 0.9],
                        confidence: 0.90,
                        class_id: 1,
                    },
                ],
                vec![DetectionResult {
                    bbox: [0.2, 0.2, 0.6, 0.6],
                    confidence: 0.85,
                    class_id: 2,
                }],
            ];
            let all_gts = vec![
                vec![
                    GroundTruth {
                        bbox: [0.1, 0.1, 0.4, 0.4],
                        class_id: 0,
                    },
                    GroundTruth {
                        bbox: [0.5, 0.5, 0.9, 0.9],
                        class_id: 1,
                    },
                ],
                vec![GroundTruth {
                    bbox: [0.2, 0.2, 0.6, 0.6],
                    class_id: 2,
                }],
            ];

            let map50 = compute_map(&all_dets, &all_gts, num_classes, 0.5);
            let map75 = compute_map(&all_dets, &all_gts, num_classes, 0.75);
            let coco = compute_coco_map(&all_dets, &all_gts, num_classes);
            println!("\n  Perfect detections:");
            println!("    mAP@50:  {map50:.4} (expect 1.0)");
            println!("    mAP@75:  {map75:.4} (expect 1.0)");
            println!("    COCO:    {coco:.4} (expect 1.0)");
            assert!((map50 - 1.0).abs() < 1e-4);
            assert!((map75 - 1.0).abs() < 1e-4);
            assert!((coco - 1.0).abs() < 1e-4);
        }

        // Test 2: Mixed quality
        {
            let num_classes = 3;
            let all_dets = vec![vec![
                DetectionResult {
                    bbox: [0.0, 0.0, 0.5, 0.5],
                    confidence: 0.9,
                    class_id: 0,
                },
                DetectionResult {
                    bbox: [0.5, 0.5, 1.0, 1.0],
                    confidence: 0.8,
                    class_id: 1,
                },
            ]];
            let all_gts = vec![vec![
                GroundTruth {
                    bbox: [0.0, 0.0, 0.5, 0.5],
                    class_id: 0,
                },
                GroundTruth {
                    bbox: [0.5, 0.5, 1.0, 1.0],
                    class_id: 1,
                },
                GroundTruth {
                    bbox: [0.2, 0.2, 0.3, 0.3],
                    class_id: 1,
                },
                GroundTruth {
                    bbox: [0.7, 0.1, 0.9, 0.3],
                    class_id: 2,
                },
            ]];

            let map50 = compute_map(&all_dets, &all_gts, num_classes, 0.5);
            println!("\n  Mixed quality (partial recall):");
            println!("    mAP@50:  {map50:.4} (expect ~0.5)");
            assert!(map50 > 0.3 && map50 < 0.7);
        }

        // Test 3: All false positives
        {
            let all_dets = vec![vec![
                DetectionResult {
                    bbox: [0.0, 0.0, 0.1, 0.1],
                    confidence: 0.9,
                    class_id: 0,
                },
                DetectionResult {
                    bbox: [0.9, 0.9, 1.0, 1.0],
                    confidence: 0.8,
                    class_id: 0,
                },
            ]];
            let all_gts = vec![vec![GroundTruth {
                bbox: [0.4, 0.4, 0.6, 0.6],
                class_id: 0,
            }]];

            let map50 = compute_map(&all_dets, &all_gts, 1, 0.5);
            println!("\n  All false positives:");
            println!("    mAP@50:  {map50:.4} (expect ~0.0)");
            assert!(map50 < 0.15);
        }

        // Test 4: Many classes, sparse detections
        {
            let nc = 80;
            let mut all_dets = Vec::new();
            let mut all_gts = Vec::new();
            for i in 0..20 {
                let cls = i % nc;
                all_dets.push(vec![DetectionResult {
                    bbox: [0.1, 0.1, 0.5, 0.5],
                    confidence: 0.7,
                    class_id: cls,
                }]);
                all_gts.push(vec![GroundTruth {
                    bbox: [0.1, 0.1, 0.5, 0.5],
                    class_id: cls,
                }]);
            }
            let map50 = compute_map(&all_dets, &all_gts, nc, 0.5);
            let coco = compute_coco_map(&all_dets, &all_gts, nc);
            println!("\n  80 classes, 20 images, 1 det/img (perfect per-image):");
            println!("    mAP@50:  {map50:.4} (expect 1.0)");
            println!("    COCO:    {coco:.4} (expect 1.0)");
            assert!((map50 - 1.0).abs() < 1e-4);
        }

        println!("\n  All validation checks PASSED");
        println!("{}\n", "=".repeat(80));
    }

    // =========================================================================
    // Real COCO Evaluation (requires $COCO_ROOT)
    // =========================================================================

    #[test]
    fn coco_bench_real_helios() {
        let coco_root = match std::env::var("COCO_ROOT") {
            Ok(p) => p,
            Err(_) => {
                println!("\n--- Skipping real COCO benchmark (set COCO_ROOT to enable) ---");
                return;
            }
        };

        let image_dir = format!("{coco_root}/val2017");
        let anno_json = format!("{coco_root}/annotations/instances_val2017.json");

        println!("\n{}", "=".repeat(80));
        println!("  REAL COCO val2017 BENCHMARK");
        println!("  COCO_ROOT: {coco_root}");
        println!("{}", "=".repeat(80));

        for &(input_h, input_w, variant, max_default) in &[
            (320, 320, "nano", 200usize),
            (320, 320, "small", 100),
            (640, 640, "nano", 50),
        ] {
            let input_size = (input_h, input_w);
            let dataset =
                match crate::datasets::CocoDataset::new(&image_dir, &anno_json, input_size) {
                    Ok(ds) => ds,
                    Err(e) => {
                        println!("  Failed to load: {e}");
                        return;
                    }
                };

            let num_classes = dataset.num_classes();
            let max_images = std::env::var("COCO_MAX_IMAGES")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(max_default);

            let model = match variant {
                "nano" => crate::models::helios::Helios::nano(num_classes),
                "small" => crate::models::helios::Helios::small(num_classes),
                _ => unreachable!(),
            };

            println!("\n--- Helios-{variant} @ {input_h}x{input_w} ({max_images} images) ---");
            let start = Instant::now();
            let (map50, coco_map) =
                evaluate_helios_coco(&model, &dataset, input_size, 0.001, 0.45, max_images);
            let elapsed = start.elapsed();
            let per_image = elapsed.as_secs_f64() * 1000.0 / max_images as f64;
            let _map75 = {
                // Quick separate mAP@75 computation would need refactoring evaluate_helios_coco
                // For now report the two main metrics
                0.0f32
            };

            println!("  mAP@50:       {map50:.4}");
            println!("  COCO mAP:     {coco_map:.4}");
            println!(
                "  latency:      {per_image:.1}ms/img ({:.1} FPS)",
                1000.0 / per_image
            );
            println!("  total time:   {:.1}s", elapsed.as_secs_f64());

            assert!(map50.is_finite());
            assert!(coco_map.is_finite());
        }

        println!("{}\n", "=".repeat(80));
    }
}