edgefirst-decoder 0.36.0

ML model output decoding for YOLO and ModelPack object detection and segmentation
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
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

//! Decode kernels for the Au-Zone ModelPack output format.
//!
//! ModelPack emits SSD-style detection (separate box and score tensors) and
//! semantic segmentation, in flat and per-layer split variants. Every kernel
//! here is crate-private and reached through [`crate::Decoder`], which picks
//! the variant from the output shapes at builder time.

use ndarray::{Array2, ArrayView2, ArrayView3};
use num_traits::{AsPrimitive, Float, PrimInt};

use crate::{
    byte::{postprocess_boxes_multilabel_quant, postprocess_boxes_quant, quantize_score_threshold},
    configs::{Detection, Nms},
    dequant_detect_box,
    float::{postprocess_boxes_float, postprocess_boxes_multilabel_float},
    yolo::nms_and_cap,
    BBoxTypeTrait, DecoderError, DecoderResult, DetectBox, Quantization, XYWH, XYXY,
};

/// Configuration for ModelPack split detection decoder. The quantization is
/// ignored when decoding float models.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ModelPackDetectionConfig {
    pub(crate) anchors: Vec<[f32; 2]>,
    pub(crate) quantization: Option<Quantization>,
}

impl TryFrom<&Detection> for ModelPackDetectionConfig {
    type Error = DecoderError;

    fn try_from(value: &Detection) -> Result<Self, DecoderError> {
        Ok(Self {
            anchors: value.anchors.clone().ok_or_else(|| {
                DecoderError::InvalidConfig("ModelPack Split Detection missing anchors".to_string())
            })?,
            quantization: value.quantization.map(Quantization::from),
        })
    }
}

/// Decodes ModelPack detection outputs from quantized tensors.
///
/// The boxes are expected to be in XYXY format.
///
/// Expected shapes of inputs:
/// - boxes: (num_boxes, 4)
/// - scores: (num_boxes, num_classes)
///
/// # Panics
/// Panics if shapes don't match the expected dimensions (argmax path).
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[allow(clippy::too_many_arguments)]
pub(crate) fn decode_modelpack_det<
    BOX: PrimInt + AsPrimitive<f32> + Send + Sync,
    SCORE: PrimInt + AsPrimitive<f32> + Send + Sync,
>(
    boxes_tensor: (ArrayView2<BOX>, Quantization),
    scores_tensor: (ArrayView2<SCORE>, Quantization),
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()>
where
    f32: AsPrimitive<SCORE>,
{
    impl_modelpack_quant::<XYXY, _, _>(
        boxes_tensor,
        scores_tensor,
        score_threshold,
        iou_threshold,
        nms,
        pre_nms_top_k,
        max_det,
        multi_label,
        output_boxes,
    )
}

/// Decodes ModelPack detection outputs from float tensors. The boxes
/// are expected to be in XYXY format.
///
/// Expected shapes of inputs:
/// - boxes: (num_boxes, 4)
/// - scores: (num_boxes, num_classes)
///
/// # Panics
/// Panics if shapes don't match the expected dimensions (argmax path).
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[allow(clippy::too_many_arguments)]
pub(crate) fn decode_modelpack_float<
    BOX: Float + AsPrimitive<f32> + Send + Sync,
    SCORE: Float + AsPrimitive<f32> + Send + Sync,
>(
    boxes_tensor: ArrayView2<BOX>,
    scores_tensor: ArrayView2<SCORE>,
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()>
where
    f32: AsPrimitive<SCORE>,
{
    impl_modelpack_float::<XYXY, _, _>(
        boxes_tensor,
        scores_tensor,
        score_threshold,
        iou_threshold,
        nms,
        pre_nms_top_k,
        max_det,
        multi_label,
        output_boxes,
    )
}

/// Decodes ModelPack split detection outputs from quantized tensors. The boxes
/// are expected to be in XYWH format.
///
/// The `configs` must correspond to the `outputs` in order.
///
/// Expected shapes of inputs:
/// - outputs: (width, height, num_anchors * (5 + num_classes))
///
/// # Panics
/// Panics if shapes don't match the expected dimensions.
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn decode_modelpack_split_quant<D: AsPrimitive<f32>>(
    outputs: &[ArrayView3<D>],
    configs: &[ModelPackDetectionConfig],
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()> {
    impl_modelpack_split_quant::<XYWH, D>(
        outputs,
        configs,
        score_threshold,
        iou_threshold,
        nms,
        pre_nms_top_k,
        max_det,
        multi_label,
        output_boxes,
    )
}

/// Decodes ModelPack split detection outputs from float tensors. The boxes
/// are expected to be in XYWH format.
///
/// The `configs` must correspond to the `outputs` in order.
///
/// Expected shapes of inputs:
/// - outputs: (width, height, num_anchors * (5 + num_classes))
///
/// # Panics
/// Panics if shapes don't match the expected dimensions.
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[allow(clippy::too_many_arguments)]
pub(crate) fn decode_modelpack_split_float<D: AsPrimitive<f32>>(
    outputs: &[ArrayView3<D>],
    configs: &[ModelPackDetectionConfig],
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()> {
    impl_modelpack_split_float::<XYWH, D>(
        outputs,
        configs,
        score_threshold,
        iou_threshold,
        nms,
        pre_nms_top_k,
        max_det,
        multi_label,
        output_boxes,
    )
}
/// Implementation of ModelPack detection decoding for quantized tensors.
///
/// Expected shapes of inputs:
/// - boxes: (num_boxes, 4)
/// - scores: (num_boxes, num_classes)
///
/// # Panics
/// Panics if shapes don't match the expected dimensions (argmax path).
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[allow(clippy::too_many_arguments)]
pub(crate) fn impl_modelpack_quant<
    B: BBoxTypeTrait,
    BOX: PrimInt + AsPrimitive<f32> + Send + Sync,
    SCORE: PrimInt + AsPrimitive<f32> + Send + Sync,
>(
    boxes: (ArrayView2<BOX>, Quantization),
    scores: (ArrayView2<SCORE>, Quantization),
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()>
where
    f32: AsPrimitive<SCORE>,
{
    let (boxes_tensor, quant_boxes) = boxes;
    let (scores_tensor, quant_scores) = scores;
    let boxes = {
        let score_threshold = quantize_score_threshold(score_threshold, quant_scores);
        if multi_label {
            postprocess_boxes_multilabel_quant::<B, _, _>(
                score_threshold,
                boxes_tensor,
                scores_tensor,
                quant_boxes,
            )?
        } else {
            postprocess_boxes_quant::<B, _, _>(
                score_threshold,
                boxes_tensor,
                scores_tensor,
                quant_boxes,
            )
        }
    };
    let boxes = nms_and_cap(boxes, nms, iou_threshold, pre_nms_top_k, max_det);
    output_boxes.clear();
    output_boxes.extend(boxes.iter().map(|b| dequant_detect_box(b, quant_scores)));
    Ok(())
}

/// Implementation of ModelPack detection decoding for float tensors.
///
/// Expected shapes of inputs:
/// - boxes: (num_boxes, 4)
/// - scores: (num_boxes, num_classes)
///
/// # Panics
/// Panics if shapes don't match the expected dimensions (argmax path).
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[allow(clippy::too_many_arguments)]
pub(crate) fn impl_modelpack_float<
    B: BBoxTypeTrait,
    BOX: Float + AsPrimitive<f32> + Send + Sync,
    SCORE: Float + AsPrimitive<f32> + Send + Sync,
>(
    boxes_tensor: ArrayView2<BOX>,
    scores_tensor: ArrayView2<SCORE>,
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()>
where
    f32: AsPrimitive<SCORE>,
{
    let boxes = if multi_label {
        postprocess_boxes_multilabel_float::<B, _, _>(
            score_threshold.as_(),
            boxes_tensor,
            scores_tensor,
        )?
    } else {
        postprocess_boxes_float::<B, _, _>(score_threshold.as_(), boxes_tensor, scores_tensor)
    };
    output_boxes.clear();
    output_boxes.extend(nms_and_cap(
        boxes,
        nms,
        iou_threshold,
        pre_nms_top_k,
        max_det,
    ));
    Ok(())
}

/// Implementation of ModelPack split detection decoding for quantized tensors.
///
/// Expected shapes of inputs:
/// - boxes: (num_boxes, 4)
/// - scores: (num_boxes, num_classes)
///
/// # Panics
/// Panics if shapes don't match the expected dimensions.
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn impl_modelpack_split_quant<B: BBoxTypeTrait, D: AsPrimitive<f32>>(
    outputs: &[ArrayView3<D>],
    configs: &[ModelPackDetectionConfig],
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()> {
    let (boxes_tensor, scores_tensor) = postprocess_modelpack_split_quant(outputs, configs);
    let boxes = if multi_label {
        postprocess_boxes_multilabel_float::<B, _, _>(
            score_threshold,
            boxes_tensor.view(),
            scores_tensor.view(),
        )?
    } else {
        postprocess_boxes_float::<B, _, _>(
            score_threshold,
            boxes_tensor.view(),
            scores_tensor.view(),
        )
    };
    output_boxes.clear();
    output_boxes.extend(nms_and_cap(
        boxes,
        nms,
        iou_threshold,
        pre_nms_top_k,
        max_det,
    ));
    Ok(())
}

/// Implementation of ModelPack split detection decoding for float tensors.
///
/// The `configs` must correspond to the `outputs` in order.
///
/// Expected shapes of inputs:
/// - outputs: (width, height, num_anchors * (5 + num_classes))
///
/// # Panics
/// Panics if shapes don't match the expected dimensions.
///
/// # Errors
/// Returns [`DecoderError::InvalidShape`]
/// when boxes are not `[N, 4]` or scores do not have one row per box.
#[allow(clippy::too_many_arguments)]
pub(crate) fn impl_modelpack_split_float<B: BBoxTypeTrait, D: AsPrimitive<f32>>(
    outputs: &[ArrayView3<D>],
    configs: &[ModelPackDetectionConfig],
    score_threshold: f32,
    iou_threshold: f32,
    nms: Option<Nms>,
    pre_nms_top_k: usize,
    max_det: usize,
    multi_label: bool,
    output_boxes: &mut Vec<DetectBox>,
) -> DecoderResult<()> {
    let (boxes_tensor, scores_tensor) = postprocess_modelpack_split_float(outputs, configs);
    let boxes = if multi_label {
        postprocess_boxes_multilabel_float::<B, _, _>(
            score_threshold,
            boxes_tensor.view(),
            scores_tensor.view(),
        )?
    } else {
        postprocess_boxes_float::<B, _, _>(
            score_threshold,
            boxes_tensor.view(),
            scores_tensor.view(),
        )
    };
    output_boxes.clear();
    output_boxes.extend(nms_and_cap(
        boxes,
        nms,
        iou_threshold,
        pre_nms_top_k,
        max_det,
    ));
    Ok(())
}

/// Post processes ModelPack split detection into detection boxes,
/// filtering out any boxes below the score threshold. Returns the boxes and
/// scores tensors. Boxes are in XYWH format.
#[cfg(test)]
pub(crate) fn postprocess_modelpack_split_quant<T: AsPrimitive<f32>>(
    outputs: &[ArrayView3<T>],
    config: &[ModelPackDetectionConfig],
) -> (Array2<f32>, Array2<f32>) {
    let mut total_capacity = 0;
    let mut nc = 0;
    for (p, detail) in outputs.iter().zip(config) {
        let shape = p.shape();
        let na = detail.anchors.len();
        nc = *shape
            .last()
            .expect("Shape must have at least one dimension")
            / na
            - 5;
        total_capacity += shape[0] * shape[1] * na;
    }
    let mut bboxes = Vec::with_capacity(total_capacity * 4);
    let mut bscores = Vec::with_capacity(total_capacity * nc);

    for (p, detail) in outputs.iter().zip(config) {
        let anchors = &detail.anchors;
        let na = detail.anchors.len();
        let shape = p.shape();
        assert_eq!(
            shape.iter().product::<usize>(),
            p.len(),
            "Shape product doesn't match tensor length"
        );
        let p_sigmoid = if let Some(quant) = &detail.quantization {
            let scaled_zero = -quant.zero_point as f32 * quant.scale;
            p.mapv(|x| fast_sigmoid_impl(x.as_() * quant.scale + scaled_zero))
        } else {
            p.mapv(|x| fast_sigmoid_impl(x.as_()))
        };
        let p_sigmoid = p_sigmoid.as_standard_layout();

        // Safe to unwrap since we ensured standard layout above
        let p = p_sigmoid
            .as_slice()
            .expect("Sigmoids are not in standard layout");
        let height = shape[0];
        let width = shape[1];

        let div_width = 1.0 / width as f32;
        let div_height = 1.0 / height as f32;

        let mut grid = Vec::with_capacity(height * width * na * 2);
        for y in 0..height {
            for x in 0..width {
                for _ in 0..na {
                    grid.push(x as f32 - 0.5);
                    grid.push(y as f32 - 0.5);
                }
            }
        }
        for ((p, g), anchor) in p
            .chunks_exact(nc + 5)
            .zip(grid.as_chunks::<2>().0)
            .zip(anchors.iter().cycle())
        {
            let (x, y) = (p[0], p[1]);
            let x = (x * 2.0 + g[0]) * div_width;
            let y = (y * 2.0 + g[1]) * div_height;
            let (w, h) = (p[2], p[3]);
            let w = w * w * 4.0 * anchor[0];
            let h = h * h * 4.0 * anchor[1];

            bboxes.push(x);
            bboxes.push(y);
            bboxes.push(w);
            bboxes.push(h);

            if nc == 1 {
                bscores.push(p[4]);
            } else {
                let obj = p[4];
                let probs = p[5..].iter().map(|x| *x * obj);
                bscores.extend(probs);
            }
        }
    }
    // Safe to unwrap since we ensured lengths will match above

    debug_assert_eq!(bboxes.len() % 4, 0);
    debug_assert_eq!(bscores.len() % nc, 0);

    let bboxes = Array2::from_shape_vec((bboxes.len() / 4, 4), bboxes)
        .expect("Failed to create bboxes array");
    let bscores = Array2::from_shape_vec((bscores.len() / nc, nc), bscores)
        .expect("Failed to create bscores array");
    (bboxes, bscores)
}

/// Post processes ModelPack split detection into detection boxes,
/// filtering out any boxes below the score threshold. Returns the boxes and
/// scores tensors. Boxes are in XYWH format.
pub(crate) fn postprocess_modelpack_split_float<T: AsPrimitive<f32>>(
    outputs: &[ArrayView3<T>],
    config: &[ModelPackDetectionConfig],
) -> (Array2<f32>, Array2<f32>) {
    let mut total_capacity = 0;
    let mut nc = 0;
    for (p, detail) in outputs.iter().zip(config) {
        let shape = p.shape();
        let na = detail.anchors.len();
        nc = *shape
            .last()
            .expect("Shape must have at least one dimension")
            / na
            - 5;
        total_capacity += shape[0] * shape[1] * na;
    }
    let mut bboxes = Vec::with_capacity(total_capacity * 4);
    let mut bscores = Vec::with_capacity(total_capacity * nc);

    for (p, detail) in outputs.iter().zip(config) {
        let anchors = &detail.anchors;
        let na = detail.anchors.len();
        let shape = p.shape();
        assert_eq!(
            shape.iter().product::<usize>(),
            p.len(),
            "Shape product doesn't match tensor length"
        );
        let p_sigmoid = p.mapv(|x| fast_sigmoid_impl(x.as_()));
        let p_sigmoid = p_sigmoid.as_standard_layout();

        // Safe to unwrap since we ensured standard layout above
        let p = p_sigmoid
            .as_slice()
            .expect("Sigmoids are not in standard layout");
        let height = shape[0];
        let width = shape[1];

        let div_width = 1.0 / width as f32;
        let div_height = 1.0 / height as f32;

        let mut grid = Vec::with_capacity(height * width * na * 2);
        for y in 0..height {
            for x in 0..width {
                for _ in 0..na {
                    grid.push(x as f32 - 0.5);
                    grid.push(y as f32 - 0.5);
                }
            }
        }
        for ((p, g), anchor) in p
            .chunks_exact(nc + 5)
            .zip(grid.as_chunks::<2>().0)
            .zip(anchors.iter().cycle())
        {
            let (x, y) = (p[0], p[1]);
            let x = (x * 2.0 + g[0]) * div_width;
            let y = (y * 2.0 + g[1]) * div_height;
            let (w, h) = (p[2], p[3]);
            let w = w * w * 4.0 * anchor[0];
            let h = h * h * 4.0 * anchor[1];

            bboxes.push(x);
            bboxes.push(y);
            bboxes.push(w);
            bboxes.push(h);

            if nc == 1 {
                bscores.push(p[4]);
            } else {
                let obj = p[4];
                let probs = p[5..].iter().map(|x| *x * obj);
                bscores.extend(probs);
            }
        }
    }
    // Safe to unwrap since we ensured lengths will match above

    debug_assert_eq!(bboxes.len() % 4, 0);
    debug_assert_eq!(bscores.len() % nc, 0);

    let bboxes = Array2::from_shape_vec((bboxes.len() / 4, 4), bboxes)
        .expect("Failed to create bboxes array");
    let bscores = Array2::from_shape_vec((bscores.len() / nc, nc), bscores)
        .expect("Failed to create bscores array");
    (bboxes, bscores)
}

/// Fast approximation of `eˣ`, vendored bit-for-bit from the (abandoned)
/// `fast-math` crate by Huon Wilson (MIT/Apache-2.0). Inlining the ~10-line
/// Schraudolph float-bit-trick lets us drop the unmaintained dependency while
/// keeping decoder outputs bit-identical to prior releases. Valid for roughly
/// -88 ≤ x ≤ 88 (kept in range by the guard in `fast_sigmoid_impl`); max
/// relative error < ~0.011.
#[inline(always)]
// Constants are reproduced verbatim from `fast-math` to stay bit-identical;
// keep the upstream literals rather than rounding them to f32 precision.
#[allow(clippy::excessive_precision)]
fn exp_raw(x: f32) -> f32 {
    const A: f32 = (1u32 << 23) as f32; // 2^SIGNIF for f32
    const MASK: i32 = 0xff800000u32 as i32;
    const EXP2_23: f32 = 1.1920929e-7;
    const C0: f32 = 0.3371894346 * EXP2_23 * EXP2_23;
    const C1: f32 = 0.657636276 * EXP2_23;
    const C2: f32 = 1.00172476;

    let a = A * core::f32::consts::LOG2_E;
    let mul = (a * x) as i32;
    let floor = mul & MASK;
    let frac = (mul - floor) as f32;
    let approx = (C0 * frac + C1) * frac + C2;
    f32::from_bits(approx.to_bits().wrapping_add(floor as u32))
}

#[inline(always)]
fn fast_sigmoid_impl(f: f32) -> f32 {
    if f.abs() > 80.0 {
        f.signum() * 0.5 + 0.5
    } else {
        // exp_raw is only valid for -88 < x < 88; the guard above keeps us in range
        1.0 / (1.0 + exp_raw(-f))
    }
}

/// Converts ModelPack segmentation into a 2D mask.
/// The input segmentation is expected to have shape (H, W, num_classes).
///
/// The output mask will have shape (H, W), with values `0..num_classes` based
/// on the argmax across the channels.
///
/// # Panics
/// Panics if the input tensor does not have more than one channel.
pub(crate) fn modelpack_segmentation_to_mask(segmentation: ArrayView3<u8>) -> Array2<u8> {
    use argminmax::ArgMinMax;
    assert!(
        segmentation.shape()[2] > 1,
        "Model Instance Segmentation should have shape (H, W, x) where x > 1"
    );
    let height = segmentation.shape()[0];
    let width = segmentation.shape()[1];
    let channels = segmentation.shape()[2];
    let segmentation = segmentation.as_standard_layout();
    // Safe to unwrap since we ensured standard layout above
    let seg = segmentation
        .as_slice()
        .expect("Segmentation is not in standard layout");
    let argmax = seg
        .chunks_exact(channels)
        .map(|x| x.argmax() as u8)
        .collect::<Vec<_>>();

    Array2::from_shape_vec((height, width), argmax).expect("Failed to create mask array")
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod modelpack_tests {
    #![allow(clippy::excessive_precision)]
    use ndarray::Array3;

    use crate::configs::{DecoderType, DimName};

    use super::*;
    #[test]
    fn test_detection_config() {
        let det = Detection {
            anchors: Some(vec![[0.1, 0.13], [0.16, 0.30], [0.33, 0.23]]),
            quantization: Some((0.1, 128).into()),
            decoder: DecoderType::ModelPack,
            shape: vec![1, 9, 17, 18],
            dshape: vec![
                (DimName::Batch, 1),
                (DimName::Height, 9),
                (DimName::Width, 17),
                (DimName::NumAnchorsXFeatures, 18),
            ],
            normalized: Some(true),
        };
        let config = ModelPackDetectionConfig::try_from(&det).unwrap();
        assert_eq!(
            config,
            ModelPackDetectionConfig {
                anchors: vec![[0.1, 0.13], [0.16, 0.30], [0.33, 0.23]],
                quantization: Some(Quantization::new(0.1, 128)),
            }
        );

        let det = Detection {
            anchors: None,
            quantization: Some((0.1, 128).into()),
            decoder: DecoderType::ModelPack,
            shape: vec![1, 9, 17, 18],
            dshape: vec![
                (DimName::Batch, 1),
                (DimName::Height, 9),
                (DimName::Width, 17),
                (DimName::NumAnchorsXFeatures, 18),
            ],
            normalized: Some(true),
        };
        let result = ModelPackDetectionConfig::try_from(&det);
        assert!(
            matches!(result, Err(DecoderError::InvalidConfig(s)) if s == "ModelPack Split Detection missing anchors")
        );
    }

    #[test]
    fn test_fast_sigmoid() {
        fn full_sigmoid(x: f32) -> f32 {
            1.0 / (1.0 + (-x).exp())
        }
        for i in -2550..=2550 {
            let x = i as f32 * 0.1;
            let fast = fast_sigmoid_impl(x);
            let full = full_sigmoid(x);
            let diff = (fast - full).abs();
            assert!(
                diff < 0.0005,
                "Fast sigmoid differs from full sigmoid by {} at input {}",
                diff,
                x
            );
        }
    }

    /// The 80.0 cut-off is exclusive. At exactly -80 the smooth branch still
    /// runs and returns a small positive number; the saturating branch would
    /// return a hard 0.0, which is a different value, not a rounding of it.
    #[test]
    fn fast_sigmoid_saturates_beyond_the_cutoff_not_at_it() {
        assert!(
            fast_sigmoid_impl(-80.0) > 0.0,
            "-80.0 is inside the smooth range, got {}",
            fast_sigmoid_impl(-80.0)
        );
        assert_eq!(fast_sigmoid_impl(-80.5), 0.0);
        assert_eq!(fast_sigmoid_impl(80.5), 1.0);
    }

    /// Exercises the float split decode end to end on one 1x1 cell with two
    /// classes: the class count derived from the last dimension, the box
    /// decode, and the objectness-weighted class scores.
    #[test]
    fn modelpack_split_float_decodes_boxes_and_objectness_weighted_scores() {
        fn full_sigmoid(x: f32) -> f32 {
            1.0 / (1.0 + (-x).exp())
        }

        // (H, W, na * (5 + nc)) with na = 1 and nc = 2.
        let raw = Array3::from_shape_vec((1, 1, 7), vec![0.0, 0.0, 0.0, 0.0, 2.0, 1.0, -1.0])
            .expect("shape matches the data");
        let config = [ModelPackDetectionConfig {
            anchors: vec![[2.0, 3.0]],
            quantization: None,
        }];

        let (boxes, scores) = postprocess_modelpack_split_float(&[raw.view()], &config);

        assert_eq!(boxes.shape(), &[1, 4]);
        assert_eq!(scores.shape(), &[1, 2]);

        // p = sigmoid(raw); grid cell (0,0) contributes -0.5, and 1/width and
        // 1/height are both 1.0 for a 1x1 grid.
        let obj = full_sigmoid(2.0);
        let expected_box = [
            0.5 * 2.0 - 0.5,
            0.5 * 2.0 - 0.5,
            0.5 * 0.5 * 4.0 * 2.0,
            0.5 * 0.5 * 4.0 * 3.0,
        ];
        let expected_scores = [full_sigmoid(1.0) * obj, full_sigmoid(-1.0) * obj];

        // fast_sigmoid_impl is accurate to 5e-4; the width and height terms
        // square it and scale by 4 * anchor, so the box tolerance is looser
        // than the score tolerance by exactly that factor.
        for (i, want) in expected_box.iter().enumerate() {
            assert!(
                (boxes[[0, i]] - want).abs() < 1e-2,
                "box[{i}] = {} want {want}",
                boxes[[0, i]]
            );
        }
        for (i, want) in expected_scores.iter().enumerate() {
            assert!(
                (scores[[0, i]] - want).abs() < 2e-3,
                "score[{i}] = {} want {want}",
                scores[[0, i]]
            );
        }
    }

    /// With one class the objectness is the score outright, and the scores
    /// array stays a single column.
    #[test]
    fn modelpack_split_float_single_class_uses_objectness_as_the_score() {
        let raw = Array3::from_shape_vec((1, 1, 6), vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
            .expect("shape matches the data");
        let config = [ModelPackDetectionConfig {
            anchors: vec![[1.0, 1.0]],
            quantization: None,
        }];

        let (boxes, scores) = postprocess_modelpack_split_float(&[raw.view()], &config);

        assert_eq!(boxes.shape(), &[1, 4]);
        assert_eq!(scores.shape(), &[1, 1]);
        assert!((scores[[0, 0]] - 0.5).abs() < 2e-3, "{}", scores[[0, 0]]);
    }

    #[test]
    fn test_modelpack_segmentation_to_mask() {
        let seg = Array3::from_shape_vec(
            (2, 2, 3),
            vec![
                0u8, 10, 5, // pixel (0,0)
                20, 15, 25, // pixel (0,1)
                30, 5, 10, // pixel (1,0)
                0, 0, 0, // pixel (1,1)
            ],
        )
        .unwrap();
        let mask = modelpack_segmentation_to_mask(seg.view());
        let expected_mask = Array2::from_shape_vec((2, 2), vec![1u8, 2, 0, 0]).unwrap();
        assert_eq!(mask, expected_mask);
    }

    #[test]
    #[should_panic(
        expected = "Model Instance Segmentation should have shape (H, W, x) where x > 1"
    )]
    fn test_modelpack_segmentation_to_mask_invalid() {
        let seg = Array3::from_shape_vec((2, 2, 1), vec![0u8, 10, 20, 30]).unwrap();
        let _ = modelpack_segmentation_to_mask(seg.view());
    }

    #[test]
    fn modelpack_split_float_multi_label_emits_every_class() {
        // 1x1 grid, one anchor, two classes both saturated.
        let p = ndarray::Array3::from_shape_vec(
            (1, 1, 7),
            vec![0.0f32, 0.0, 0.0, 0.0, 10.0, 10.0, 10.0],
        )
        .unwrap();
        let cfg = ModelPackDetectionConfig {
            anchors: vec![[0.5, 0.5]],
            quantization: None,
        };
        let run = |nms: Nms, multi_label: bool| {
            let mut out = Vec::with_capacity(8);
            decode_modelpack_split_float(
                &[p.view()],
                std::slice::from_ref(&cfg),
                0.5,
                0.5,
                Some(nms),
                0,
                8,
                multi_label,
                &mut out,
            )
            .unwrap();
            let mut labels: Vec<usize> = out.iter().map(|b| b.label).collect();
            labels.sort_unstable();
            labels
        };
        assert_eq!(run(Nms::ClassAware, false).len(), 1);
        assert_eq!(run(Nms::ClassAware, true), vec![0, 1]);
        // Class-agnostic NMS runs over the multi-label candidates: the two
        // classes share one bbox, so only one survives.
        assert_eq!(run(Nms::ClassAgnostic, true).len(), 1);
    }
}