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
//! NanoDet — Lightweight Anchor-Free Object Detection for Edge
//!
//! # File
//! `crates/axonml-vision/src/models/nanodet.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_nn::{BatchNorm2d, Conv2d, Module, Parameter, ReLU};
use axonml_tensor::Tensor;

use crate::ops::{Detection, InterpolateMode, interpolate_var, nms};

// =============================================================================
// ShuffleNet V2 Backbone
// =============================================================================

/// Channel shuffle operation for ShuffleNet.
fn channel_shuffle(x: &Variable, groups: usize) -> Variable {
    let shape = x.shape();
    let (n, c, h, w) = (shape[0], shape[1], shape[2], shape[3]);
    let channels_per_group = c / groups;

    // Reshape -> transpose -> reshape
    let data = x.data().to_vec();
    let mut shuffled = vec![0.0f32; data.len()];

    for b in 0..n {
        for g in 0..groups {
            for cg in 0..channels_per_group {
                let src_c = g * channels_per_group + cg;
                let dst_c = cg * groups + g;
                for y in 0..h {
                    for x_pos in 0..w {
                        let src_idx = b * c * h * w + src_c * h * w + y * w + x_pos;
                        let dst_idx = b * c * h * w + dst_c * h * w + y * w + x_pos;
                        shuffled[dst_idx] = data[src_idx];
                    }
                }
            }
        }
    }

    let output_tensor = Tensor::from_vec(shuffled, &[n, c, h, w]).unwrap();
    if x.requires_grad() && is_grad_enabled() {
        let grad_fn = GradFn::new(ChannelShuffleBackward {
            next_fns: vec![x.grad_fn().cloned()],
            groups,
            channels_per_group,
            shape: shape.clone(),
        });
        Variable::from_operation(output_tensor, grad_fn, true)
    } else {
        Variable::new(output_tensor, false)
    }
}

/// Gradient function for channel shuffle (inverse permutation).
#[derive(Debug)]
struct ChannelShuffleBackward {
    next_fns: Vec<Option<GradFn>>,
    groups: usize,
    channels_per_group: usize,
    shape: Vec<usize>,
}

impl GradientFunction for ChannelShuffleBackward {
    fn apply(&self, grad_output: &Tensor<f32>) -> Vec<Option<Tensor<f32>>> {
        let (n, c, h, w) = (self.shape[0], self.shape[1], self.shape[2], self.shape[3]);
        let g_vec = grad_output.to_vec();
        let mut grad_input = vec![0.0f32; g_vec.len()];

        // Inverse shuffle: reverse the permutation
        for b in 0..n {
            for g in 0..self.groups {
                for cg in 0..self.channels_per_group {
                    let dst_c = g * self.channels_per_group + cg; // original channel
                    let src_c = cg * self.groups + g; // shuffled channel
                    for y in 0..h {
                        for x_pos in 0..w {
                            let src_idx = b * c * h * w + src_c * h * w + y * w + x_pos;
                            let dst_idx = b * c * h * w + dst_c * h * w + y * w + x_pos;
                            grad_input[dst_idx] = g_vec[src_idx];
                        }
                    }
                }
            }
        }

        let gi = Tensor::from_vec(grad_input, &self.shape).unwrap();
        vec![Some(gi)]
    }

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

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

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

/// ShuffleNet V2 inverted residual block.
struct ShuffleBlock {
    /// Branch 2: 1x1 conv -> depthwise 3x3 -> 1x1 conv
    branch2_pw1: Conv2d,
    branch2_bn1: BatchNorm2d,
    branch2_dw: Conv2d,
    branch2_bn2: BatchNorm2d,
    branch2_pw2: Conv2d,
    branch2_bn3: BatchNorm2d,
    /// Shortcut branch (only for stride=2)
    shortcut: Option<(Conv2d, BatchNorm2d, Conv2d, BatchNorm2d)>,
    relu: ReLU,
    stride: usize,
    _in_channels: usize,
    _out_channels: usize,
}

impl ShuffleBlock {
    fn new(in_channels: usize, out_channels: usize, stride: usize) -> Self {
        let branch_channels = out_channels / 2;
        let inp = if stride == 2 {
            in_channels
        } else {
            in_channels / 2
        };

        let shortcut = if stride == 2 {
            Some((
                Conv2d::with_groups(
                    in_channels,
                    in_channels,
                    (3, 3),
                    (2, 2),
                    (1, 1),
                    true,
                    in_channels,
                ),
                BatchNorm2d::new(in_channels),
                Conv2d::with_options(in_channels, branch_channels, (1, 1), (1, 1), (0, 0), true),
                BatchNorm2d::new(branch_channels),
            ))
        } else {
            None
        };

        Self {
            branch2_pw1: Conv2d::with_options(inp, branch_channels, (1, 1), (1, 1), (0, 0), true),
            branch2_bn1: BatchNorm2d::new(branch_channels),
            branch2_dw: Conv2d::with_groups(
                branch_channels,
                branch_channels,
                (3, 3),
                (stride, stride),
                (1, 1),
                true,
                branch_channels,
            ),
            branch2_bn2: BatchNorm2d::new(branch_channels),
            branch2_pw2: Conv2d::with_options(
                branch_channels,
                branch_channels,
                (1, 1),
                (1, 1),
                (0, 0),
                true,
            ),
            branch2_bn3: BatchNorm2d::new(branch_channels),
            shortcut,
            relu: ReLU,
            stride,
            _in_channels: in_channels,
            _out_channels: out_channels,
        }
    }

    fn forward(&self, x: &Variable) -> Variable {
        if self.stride == 2 {
            // Stride-2: both branches process full input
            let (sc_dw, sc_bn, sc_pw, sc_bn2) = self.shortcut.as_ref().unwrap();
            let branch1 =
                self.relu.forward(&sc_bn2.forward(
                    &sc_pw.forward(&self.relu.forward(&sc_bn.forward(&sc_dw.forward(x)))),
                ));

            let branch2 = self
                .relu
                .forward(&self.branch2_bn1.forward(&self.branch2_pw1.forward(x)));
            let branch2 = self.branch2_bn2.forward(&self.branch2_dw.forward(&branch2));
            let branch2 = self.relu.forward(
                &self
                    .branch2_bn3
                    .forward(&self.branch2_pw2.forward(&branch2)),
            );

            // Concat channels
            concat_channels(&branch1, &branch2)
        } else {
            // Stride-1: split channels using narrow (preserves autograd graph)
            let c = x.shape()[1];
            let mid = c / 2;

            let branch1 = x.narrow(1, 0, mid);
            let inp = x.narrow(1, mid, c - mid);

            let branch2 = self
                .relu
                .forward(&self.branch2_bn1.forward(&self.branch2_pw1.forward(&inp)));
            let branch2 = self.branch2_bn2.forward(&self.branch2_dw.forward(&branch2));
            let branch2 = self.relu.forward(
                &self
                    .branch2_bn3
                    .forward(&self.branch2_pw2.forward(&branch2)),
            );

            let out = concat_channels(&branch1, &branch2);
            channel_shuffle(&out, 2)
        }
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut p = Vec::new();
        p.extend(self.branch2_pw1.parameters());
        p.extend(self.branch2_bn1.parameters());
        p.extend(self.branch2_dw.parameters());
        p.extend(self.branch2_bn2.parameters());
        p.extend(self.branch2_pw2.parameters());
        p.extend(self.branch2_bn3.parameters());
        if let Some((dw, bn, pw, bn2)) = &self.shortcut {
            p.extend(dw.parameters());
            p.extend(bn.parameters());
            p.extend(pw.parameters());
            p.extend(bn2.parameters());
        }
        p
    }
}

/// Concatenate two Variables along channel dimension.
fn concat_channels(a: &Variable, b: &Variable) -> Variable {
    Variable::cat(&[a, b], 1)
}

/// ShuffleNet V2 backbone stages.
pub(crate) struct ShuffleNetBackbone {
    stem: Conv2d,
    stem_bn: BatchNorm2d,
    relu: ReLU,
    stages: Vec<Vec<ShuffleBlock>>,
    stage_out_channels: Vec<usize>,
}

impl ShuffleNetBackbone {
    /// Create a 0.5x ShuffleNet V2 backbone (~350K params).
    fn new() -> Self {
        // 0.5x channel config: [24, 48, 96, 192]
        let stage_channels = [48, 96, 192];
        let stage_repeats = [3, 7, 3];

        let mut stages = Vec::new();
        let mut in_ch = 24;

        for (&out_ch, &repeats) in stage_channels.iter().zip(stage_repeats.iter()) {
            let mut blocks = Vec::new();
            // First block with stride 2
            blocks.push(ShuffleBlock::new(in_ch, out_ch, 2));
            // Remaining blocks with stride 1
            for _ in 1..repeats {
                blocks.push(ShuffleBlock::new(out_ch, out_ch, 1));
            }
            stages.push(blocks);
            in_ch = out_ch;
        }

        Self {
            stem: Conv2d::with_options(3, 24, (3, 3), (2, 2), (1, 1), true),
            stem_bn: BatchNorm2d::new(24),
            relu: ReLU,
            stages,
            stage_out_channels: stage_channels.to_vec(),
        }
    }

    /// Forward pass returning multi-scale features [P3, P4, P5].
    pub(crate) fn forward(&self, x: &Variable) -> Vec<Variable> {
        let mut out = self
            .relu
            .forward(&self.stem_bn.forward(&self.stem.forward(x)));
        let mut features = Vec::new();

        for stage in &self.stages {
            for block in stage {
                out = block.forward(&out);
            }
            features.push(out.clone());
        }

        features
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut p = Vec::new();
        p.extend(self.stem.parameters());
        p.extend(self.stem_bn.parameters());
        for stage in &self.stages {
            for block in stage {
                p.extend(block.parameters());
            }
        }
        p
    }
}

// =============================================================================
// Ghost PAN Neck
// =============================================================================

/// Depthwise separable convolution block.
struct DepthwiseSeparable {
    dw: Conv2d,
    dw_bn: BatchNorm2d,
    pw: Conv2d,
    pw_bn: BatchNorm2d,
    relu: ReLU,
}

impl DepthwiseSeparable {
    fn new(in_ch: usize, out_ch: usize) -> Self {
        Self {
            dw: Conv2d::with_groups(in_ch, in_ch, (3, 3), (1, 1), (1, 1), true, in_ch),
            dw_bn: BatchNorm2d::new(in_ch),
            pw: Conv2d::with_options(in_ch, out_ch, (1, 1), (1, 1), (0, 0), true),
            pw_bn: BatchNorm2d::new(out_ch),
            relu: ReLU,
        }
    }

    fn forward(&self, x: &Variable) -> Variable {
        let out = self.relu.forward(&self.dw_bn.forward(&self.dw.forward(x)));
        self.relu
            .forward(&self.pw_bn.forward(&self.pw.forward(&out)))
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut p = Vec::new();
        p.extend(self.dw.parameters());
        p.extend(self.dw_bn.parameters());
        p.extend(self.pw.parameters());
        p.extend(self.pw_bn.parameters());
        p
    }
}

/// Ghost PAN (Path Aggregation Network) neck.
///
/// Lightweight feature fusion with depthwise separable convolutions.
pub(crate) struct GhostPAN {
    /// Reduce channels from backbone to neck dimension
    reduce: Vec<(Conv2d, BatchNorm2d)>,
    /// Top-down fusion (depthwise separable)
    top_down: Vec<DepthwiseSeparable>,
    /// Bottom-up fusion (depthwise separable)
    bottom_up: Vec<DepthwiseSeparable>,
    /// Downsampling convs for bottom-up path
    downsample: Vec<(Conv2d, BatchNorm2d)>,
    relu: ReLU,
    _neck_channels: usize,
}

impl GhostPAN {
    fn new(in_channels: &[usize], neck_channels: usize) -> Self {
        let num_levels = in_channels.len();

        let reduce: Vec<_> = in_channels
            .iter()
            .map(|&c| {
                (
                    Conv2d::with_options(c, neck_channels, (1, 1), (1, 1), (0, 0), true),
                    BatchNorm2d::new(neck_channels),
                )
            })
            .collect();

        let top_down: Vec<_> = (0..num_levels - 1)
            .map(|_| DepthwiseSeparable::new(neck_channels, neck_channels))
            .collect();

        let bottom_up: Vec<_> = (0..num_levels - 1)
            .map(|_| DepthwiseSeparable::new(neck_channels, neck_channels))
            .collect();

        let downsample: Vec<_> = (0..num_levels - 1)
            .map(|_| {
                (
                    Conv2d::with_groups(
                        neck_channels,
                        neck_channels,
                        (3, 3),
                        (2, 2),
                        (1, 1),
                        true,
                        neck_channels,
                    ),
                    BatchNorm2d::new(neck_channels),
                )
            })
            .collect();

        Self {
            reduce,
            top_down,
            bottom_up,
            downsample,
            relu: ReLU,
            _neck_channels: neck_channels,
        }
    }

    pub(crate) fn forward(&self, features: &[Variable]) -> Vec<Variable> {
        let num = features.len();

        // 1. Reduce all feature maps to neck_channels
        let mut reduced: Vec<Variable> = features
            .iter()
            .zip(self.reduce.iter())
            .map(|(f, (conv, bn))| self.relu.forward(&bn.forward(&conv.forward(f))))
            .collect();

        // 2. Top-down pathway (coarse -> fine)
        for i in (0..num - 1).rev() {
            let coarse = &reduced[i + 1];
            let shape = reduced[i].shape();
            let (target_h, target_w) = (shape[2], shape[3]);

            let up_var = interpolate_var(coarse, target_h, target_w, InterpolateMode::Nearest);
            let fused = reduced[i].add_var(&up_var);
            reduced[i] = self.top_down[i].forward(&fused);
        }

        // 3. Bottom-up pathway (fine -> coarse)
        for i in 0..num - 1 {
            let fine = &reduced[i];
            let (conv, bn) = &self.downsample[i];
            let downsampled = self.relu.forward(&bn.forward(&conv.forward(fine)));
            let fused = reduced[i + 1].add_var(&downsampled);
            reduced[i + 1] = self.bottom_up[i].forward(&fused);
        }

        reduced
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut p = Vec::new();
        for (conv, bn) in &self.reduce {
            p.extend(conv.parameters());
            p.extend(bn.parameters());
        }
        for layer in &self.top_down {
            p.extend(layer.parameters());
        }
        for layer in &self.bottom_up {
            p.extend(layer.parameters());
        }
        for (conv, bn) in &self.downsample {
            p.extend(conv.parameters());
            p.extend(bn.parameters());
        }
        p
    }
}

// =============================================================================
// Detection Head
// =============================================================================

/// Anchor-free detection head for NanoDet.
///
/// Predicts class scores and bounding boxes at each spatial location.
pub(crate) struct NanoDetHead {
    /// Shared convolution layers
    shared: Vec<(Conv2d, BatchNorm2d)>,
    /// Classification output (per level)
    cls_out: Conv2d,
    /// Bounding box regression output (per level)
    bbox_out: Conv2d,
    relu: ReLU,
    _num_classes: usize,
}

impl NanoDetHead {
    fn new(in_channels: usize, num_classes: usize) -> Self {
        // 2 shared depthwise-separable-like conv layers
        let shared = vec![
            (
                Conv2d::with_options(in_channels, in_channels, (3, 3), (1, 1), (1, 1), true),
                BatchNorm2d::new(in_channels),
            ),
            (
                Conv2d::with_options(in_channels, in_channels, (3, 3), (1, 1), (1, 1), true),
                BatchNorm2d::new(in_channels),
            ),
        ];

        Self {
            shared,
            cls_out: Conv2d::with_options(in_channels, num_classes, (1, 1), (1, 1), (0, 0), true),
            bbox_out: Conv2d::with_options(in_channels, 4, (1, 1), (1, 1), (0, 0), true),
            relu: ReLU,
            _num_classes: num_classes,
        }
    }

    /// Forward on a single feature level.
    pub(crate) fn forward_single(&self, x: &Variable) -> (Variable, Variable) {
        let mut out = x.clone();
        for (conv, bn) in &self.shared {
            out = self.relu.forward(&bn.forward(&conv.forward(&out)));
        }

        let cls = self.cls_out.forward(&out);
        let bbox = self.bbox_out.forward(&out);
        (cls, bbox)
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut p = Vec::new();
        for (conv, bn) in &self.shared {
            p.extend(conv.parameters());
            p.extend(bn.parameters());
        }
        p.extend(self.cls_out.parameters());
        p.extend(self.bbox_out.parameters());
        p
    }
}

// =============================================================================
// NanoDet
// =============================================================================

/// NanoDet — Lightweight anchor-free object detector for edge deployment.
///
/// Architecture: ShuffleNet V2 backbone + Ghost PAN neck + anchor-free head.
/// Designed for <1M parameters and real-time inference on ARM/mobile devices.
pub struct NanoDet {
    pub(crate) backbone: ShuffleNetBackbone,
    pub(crate) neck: GhostPAN,
    pub(crate) head: NanoDetHead,
    num_classes: usize,
    strides: Vec<usize>,
}

impl NanoDet {
    /// Create a NanoDet model.
    ///
    /// # Arguments
    /// - `num_classes`: Number of object classes (e.g., 80 for COCO)
    pub fn new(num_classes: usize) -> Self {
        let backbone = ShuffleNetBackbone::new();
        let neck_channels = 96;

        Self {
            neck: GhostPAN::new(&backbone.stage_out_channels, neck_channels),
            head: NanoDetHead::new(neck_channels, num_classes),
            backbone,
            num_classes,
            strides: vec![8, 16, 32],
        }
    }

    /// Run detection on an input image.
    ///
    /// # Arguments
    /// - `image`: `[N, 3, H, W]` input tensor
    /// - `score_threshold`: Minimum confidence score
    /// - `nms_threshold`: IoU threshold for NMS
    ///
    /// # Returns
    /// Vector of detections with class, bbox, and confidence.
    pub fn detect(
        &self,
        image: &Variable,
        score_threshold: f32,
        nms_threshold: f32,
    ) -> Vec<Detection> {
        let features = self.backbone.forward(image);
        let neck_features = self.neck.forward(&features);

        let input_shape = image.shape();
        let img_h = input_shape[2] as f32;
        let img_w = input_shape[3] as f32;

        let mut all_boxes = Vec::new();
        let mut all_scores = Vec::new();
        let mut all_classes = Vec::new();

        for (level, feat) in neck_features.iter().enumerate() {
            let (cls, bbox) = self.head.forward_single(feat);
            let cls_data = cls.data().to_vec();
            let bbox_data = bbox.data().to_vec();
            let shape = cls.shape();
            let (_n, _c, h, w) = (shape[0], shape[1], shape[2], shape[3]);
            let stride = self.strides[level] as f32;

            for y in 0..h {
                for x in 0..w {
                    // Find best class at this location
                    let mut best_cls = 0;
                    let mut best_score = f32::NEG_INFINITY;

                    for c in 0..self.num_classes {
                        let idx = c * h * w + y * w + x;
                        let score = 1.0 / (1.0 + (-cls_data[idx]).exp()); // sigmoid
                        if score > best_score {
                            best_score = score;
                            best_cls = c;
                        }
                    }

                    if best_score < score_threshold {
                        continue;
                    }

                    // Decode bbox (center offset + size)
                    let dx = bbox_data[0 * h * w + y * w + x];
                    let dy = bbox_data[h * w + y * w + x];
                    let dw = bbox_data[2 * h * w + y * w + x];
                    let dh = bbox_data[3 * h * w + y * w + x];

                    let cx = (x as f32 + 0.5) * stride + dx * stride;
                    let cy = (y as f32 + 0.5) * stride + dy * stride;
                    let bw = (dw.exp() * stride).min(img_w);
                    let bh = (dh.exp() * stride).min(img_h);

                    all_boxes.push([
                        (cx - bw / 2.0).max(0.0),
                        (cy - bh / 2.0).max(0.0),
                        (cx + bw / 2.0).min(img_w),
                        (cy + bh / 2.0).min(img_h),
                    ]);
                    all_scores.push(best_score);
                    all_classes.push(best_cls);
                }
            }
        }

        if all_scores.is_empty() {
            return vec![];
        }

        // Per-class NMS
        let mut results = Vec::new();
        for cls in 0..self.num_classes {
            let indices: Vec<usize> = (0..all_scores.len())
                .filter(|&i| all_classes[i] == cls)
                .collect();

            if indices.is_empty() {
                continue;
            }

            let cls_boxes: Vec<f32> = indices
                .iter()
                .flat_map(|&i| all_boxes[i].iter().copied())
                .collect();
            let cls_scores: Vec<f32> = indices.iter().map(|&i| all_scores[i]).collect();

            let n = indices.len();
            let boxes_t = Tensor::from_vec(cls_boxes, &[n, 4]).unwrap();
            let scores_t = Tensor::from_vec(cls_scores.clone(), &[n]).unwrap();
            let keep = nms(&boxes_t, &scores_t, nms_threshold);

            for &k in &keep {
                let orig_idx = indices[k];
                results.push(Detection {
                    class_id: cls,
                    bbox: all_boxes[orig_idx],
                    confidence: all_scores[orig_idx],
                });
            }
        }

        results
    }
}

impl Module for NanoDet {
    fn forward(&self, x: &Variable) -> Variable {
        let features = self.backbone.forward(x);
        let neck_features = self.neck.forward(&features);
        let (cls, _bbox) = self.head.forward_single(&neck_features[0]);
        cls
    }

    fn parameters(&self) -> Vec<Parameter> {
        let mut p = Vec::new();
        p.extend(self.backbone.parameters());
        p.extend(self.neck.parameters());
        p.extend(self.head.parameters());
        p
    }

    fn train(&mut self) {}
    fn eval(&mut self) {}
}

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

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

    #[test]
    fn test_shuffle_block_stride1() {
        let block = ShuffleBlock::new(48, 48, 1);
        let input = Variable::new(
            Tensor::from_vec(vec![0.1; 1 * 48 * 8 * 8], &[1, 48, 8, 8]).unwrap(),
            false,
        );
        let output = block.forward(&input);
        assert_eq!(output.shape(), vec![1, 48, 8, 8]);
    }

    #[test]
    fn test_shuffle_block_stride2() {
        let block = ShuffleBlock::new(24, 48, 2);
        let input = Variable::new(
            Tensor::from_vec(vec![0.1; 1 * 24 * 16 * 16], &[1, 24, 16, 16]).unwrap(),
            false,
        );
        let output = block.forward(&input);
        assert_eq!(output.shape(), vec![1, 48, 8, 8]);
    }

    #[test]
    fn test_nanodet_creation() {
        let model = NanoDet::new(80);
        let params = model.parameters();
        assert!(!params.is_empty());

        // Should be lightweight (<1M params)
        let total: usize = params
            .iter()
            .map(|p| p.variable().data().to_vec().len())
            .sum();
        assert!(
            total < 1_000_000,
            "NanoDet has {} params, expected < 1M",
            total
        );
    }

    #[test]
    fn test_nanodet_forward() {
        let model = NanoDet::new(20);
        let input = Variable::new(
            Tensor::from_vec(vec![0.1; 1 * 3 * 128 * 128], &[1, 3, 128, 128]).unwrap(),
            false,
        );
        let output = model.forward(&input);
        assert_eq!(output.shape()[0], 1);
        // Output should have num_classes channels
        assert_eq!(output.shape()[1], 20);
    }

    #[test]
    fn test_channel_shuffle() {
        let input = Variable::new(
            Tensor::from_vec(vec![0.1; 1 * 4 * 2 * 2], &[1, 4, 2, 2]).unwrap(),
            false,
        );
        let output = channel_shuffle(&input, 2);
        assert_eq!(output.shape(), vec![1, 4, 2, 2]);
    }
}