1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0
use std::collections::HashSet;
use super::config::ConfigOutputRef;
use super::configs::{self, DecoderType, DecoderVersion, DimName, ModelType};
use super::merge::DecodeProgram;
use super::{ConfigOutput, ConfigOutputs, Decoder};
use crate::per_scale::{DecodeDtype, PerScalePlan};
use crate::schema::SchemaV2;
use crate::DecoderError;
/// Extract `(width, height)` from a schema [`crate::schema::InputSpec`].
///
/// Prefers named dims (`DimName::Width` / `DimName::Height`) when the
/// `dshape` is populated, falling back to the NHWC convention
/// (`shape[1] = H, shape[2] = W`) for 4-element shapes whenever either
/// named dim is missing. Returns `None` for any other shape arity — the
/// decoder treats that as "input dims unknown" and skips the EDGEAI-1303
/// normalization path.
///
/// The fallback fires when **either** `Height` or `Width` is missing from
/// the dshape (not only when both are absent), so a partially-named
/// dshape (e.g. only `Width`) still resolves both dims via positional
/// inference instead of silently disabling normalization.
fn input_dims_from_spec(input: &crate::schema::InputSpec) -> Option<(usize, usize)> {
use crate::configs::DimName;
let mut h = None;
let mut w = None;
// `SchemaV2::validate()` doesn't currently enforce
// `dshape.len() <= shape.len()`, so a malformed schema can trip an
// out-of-bounds index here. Use `shape.get(i)` to silently skip
// dshape entries that overflow the shape — the caller treats
// missing dims as "unknown" and disables EDGEAI-1303 normalization.
for (i, (name, _)) in input.dshape.iter().enumerate() {
match name {
DimName::Height => h = input.shape.get(i).copied(),
DimName::Width => w = input.shape.get(i).copied(),
_ => {}
}
}
if (h.is_none() || w.is_none()) && input.shape.len() == 4 {
// NHWC default: [N, H, W, C]. Mirrors the per-scale `extract_hw`
// fallback (`crates/decoder/src/per_scale/plan.rs::extract_hw`).
// Only fill the missing axis so a partial named dshape still
// resolves both dims.
h = h.or(Some(input.shape[1]));
w = w.or(Some(input.shape[2]));
}
match (w, h) {
(Some(w), Some(h)) => Some((w, h)),
_ => None,
}
}
#[cfg(test)]
mod input_dims_from_spec_tests {
use super::input_dims_from_spec;
use crate::configs::DimName;
use crate::schema::InputSpec;
#[test]
fn named_dshape_resolves_dims() {
let spec = InputSpec {
shape: vec![1, 480, 640, 3],
dshape: vec![
(DimName::Batch, 1),
(DimName::Height, 480),
(DimName::Width, 640),
(DimName::NumFeatures, 3),
],
cameraadaptor: None,
};
assert_eq!(input_dims_from_spec(&spec), Some((640, 480)));
}
#[test]
fn empty_dshape_falls_back_to_nhwc_for_4d() {
let spec = InputSpec {
shape: vec![1, 480, 640, 3],
dshape: vec![],
cameraadaptor: None,
};
assert_eq!(input_dims_from_spec(&spec), Some((640, 480)));
}
#[test]
fn malformed_dshape_longer_than_shape_does_not_panic() {
// Regression for Copilot review on PR #63: indexing
// `input.shape[i]` while iterating dshape can OOB-panic when
// `dshape.len() > shape.len()`. The fix uses `shape.get(i)`
// and silently treats overflow as "dim missing".
let spec = InputSpec {
shape: vec![640, 480], // 2-D shape
dshape: vec![
(DimName::Width, 640),
(DimName::Height, 480),
(DimName::NumFeatures, 3), // overflow — index 2 ≥ shape.len()
],
cameraadaptor: None,
};
// First two dshape entries resolve via `shape.get()`; the third
// is a no-op. Width/Height both resolved, so we expect Some.
assert_eq!(input_dims_from_spec(&spec), Some((640, 480)));
}
#[test]
fn malformed_dshape_only_overflow_returns_none() {
// All dshape entries are past the shape boundary — width and
// height stay None and the 4-D NHWC fallback doesn't fire
// (shape.len() == 1), so we get None instead of a panic.
let spec = InputSpec {
shape: vec![1],
dshape: vec![
(DimName::NumFeatures, 3),
(DimName::Height, 480),
(DimName::Width, 640),
],
cameraadaptor: None,
};
assert_eq!(input_dims_from_spec(&spec), None);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DecoderBuilder {
config_src: Option<ConfigSource>,
iou_threshold: f32,
score_threshold: f32,
/// NMS mode.
///
/// - `Some(Nms::Auto)` — resolve from config or fallback to
/// `ClassAgnostic` (builder default)
/// - `Some(Nms::ClassAgnostic)` — explicit class-agnostic override
/// - `Some(Nms::ClassAware)` — explicit class-aware override
/// - `None` — bypass NMS entirely
nms: Option<configs::Nms>,
/// Output dtype for the per-scale fast path. Has no effect on
/// schemas without per-scale children (which use the legacy decode
/// path).
decode_dtype: DecodeDtype,
pre_nms_top_k: usize,
max_det: usize,
/// Explicit override for the model input dimensions `(width, height)`,
/// consumed by EDGEAI-1303 normalization. When set, takes precedence
/// over schema-derived dims; when `None`, the value is read from the
/// schema's `input.shape` / `input.dshape` at build time.
input_dims: Option<(usize, usize)>,
}
#[derive(Debug, Clone, PartialEq)]
enum ConfigSource {
Yaml(String),
Json(String),
Config(ConfigOutputs),
/// Schema v2 metadata. During build the schema is either converted
/// to a legacy [`ConfigOutputs`] (flat case) or used to construct a
/// [`DecodeProgram`] that performs per-child dequant + merge at
/// decode time.
Schema(SchemaV2),
}
impl Default for DecoderBuilder {
/// Creates a default DecoderBuilder with no configuration and 0.5 score
/// threshold and 0.5 IoU threshold.
///
/// A valid configuration must be provided before building the Decoder.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_yaml = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.yaml")).to_string();
/// let decoder = DecoderBuilder::default()
/// .with_config_yaml_str(config_yaml)
/// .build()?;
/// assert_eq!(decoder.score_threshold, 0.5);
/// assert_eq!(decoder.iou_threshold, 0.5);
///
/// # Ok(())
/// # }
/// ```
fn default() -> Self {
Self {
config_src: None,
iou_threshold: 0.5,
score_threshold: 0.5,
nms: Some(configs::Nms::Auto),
decode_dtype: DecodeDtype::F32,
pre_nms_top_k: 300,
max_det: 300,
input_dims: None,
}
}
}
impl DecoderBuilder {
/// Creates a default DecoderBuilder with no configuration and 0.5 score
/// threshold and 0.5 IoU threshold.
///
/// A valid configuration must be provided before building the Decoder.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_yaml = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.yaml")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_yaml_str(config_yaml)
/// .build()?;
/// assert_eq!(decoder.score_threshold, 0.5);
/// assert_eq!(decoder.iou_threshold, 0.5);
///
/// # Ok(())
/// # }
/// ```
pub fn new() -> Self {
Self::default()
}
/// Loads a model configuration in YAML format. Does not check if the string
/// is a correct configuration file. Use `DecoderBuilder.build()` to
/// deserialize the YAML and parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// let config_yaml = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.yaml")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_yaml_str(config_yaml)
/// .build()?;
///
/// # Ok(())
/// # }
/// ```
pub fn with_config_yaml_str(mut self, yaml_str: String) -> Self {
self.config_src.replace(ConfigSource::Yaml(yaml_str));
self
}
/// Loads a model configuration in JSON format. Does not check if the string
/// is a correct configuration file. Use `DecoderBuilder.build()` to
/// deserialize the JSON and parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .build()?;
///
/// # Ok(())
/// # }
/// ```
pub fn with_config_json_str(mut self, json_str: String) -> Self {
self.config_src.replace(ConfigSource::Json(json_str));
self
}
/// Loads a model configuration. Does not check if the configuration is
/// correct. Intended to be used when the user needs control over the
/// deserialize of the configuration information. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json"));
/// let config = serde_json::from_str(config_json)?;
/// let decoder = DecoderBuilder::new().with_config(config).build()?;
///
/// # Ok(())
/// # }
/// ```
pub fn with_config(mut self, config: ConfigOutputs) -> Self {
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Configure the decoder from a schema v2 metadata document.
///
/// Accepts a [`SchemaV2`] as produced by [`SchemaV2::parse_json`],
/// [`SchemaV2::parse_yaml`], [`SchemaV2::parse_file`], or
/// constructed programmatically. The builder validates the schema,
/// compiles a [`DecodeProgram`] for any split logical outputs
/// (per-scale or channel sub-splits), and downconverts the
/// logical-level semantics to the legacy [`ConfigOutputs`]
/// representation consumed by the existing decoder dispatch.
///
/// # Examples
///
/// ```rust,no_run
/// use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// use edgefirst_decoder::schema::SchemaV2;
///
/// # fn main() -> DecoderResult<()> {
/// let schema = SchemaV2::parse_file("model/edgefirst.json")?;
/// let decoder = DecoderBuilder::new()
/// .with_schema(schema)
/// .with_score_threshold(0.25)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_schema(mut self, schema: SchemaV2) -> Self {
self.config_src.replace(ConfigSource::Schema(schema));
self
}
/// Choose the output dtype for the per-scale decoder pipeline.
///
/// Defaults to [`DecodeDtype::F32`]. Has no effect on schemas
/// without per-scale children (which use the legacy decode path).
/// `F16` saves ~2× memory bandwidth at the cost of 10-bit mantissa
/// precision; empirically safe for YOLO-family models.
///
/// # Examples
///
/// ```rust,no_run
/// use edgefirst_decoder::{DecodeDtype, DecoderBuilder, DecoderResult};
/// use edgefirst_decoder::schema::SchemaV2;
///
/// # fn main() -> DecoderResult<()> {
/// let schema = SchemaV2::parse_file("model/edgefirst.json")?;
/// let decoder = DecoderBuilder::new()
/// .with_schema(schema)
/// .with_decode_dtype(DecodeDtype::F32)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_decode_dtype(mut self, dtype: DecodeDtype) -> Self {
self.decode_dtype = dtype;
self
}
/// Loads a YOLO detection model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let decoder = DecoderBuilder::new()
/// .with_config_yolo_det(
/// configs::Detection {
/// anchors: None,
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 84, 8400],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// },
/// None,
/// )
/// .build()?;
///
/// # Ok(())
/// # }
/// ```
pub fn with_config_yolo_det(
mut self,
boxes: configs::Detection,
version: Option<DecoderVersion>,
) -> Self {
let config = ConfigOutputs {
outputs: vec![ConfigOutput::Detection(boxes)],
decoder_version: version,
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a YOLO split detection model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let boxes_config = configs::Boxes {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 4, 8400],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let scores_config = configs::Scores {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 80, 8400],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_yolo_split_det(boxes_config, scores_config)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_yolo_split_det(
mut self,
boxes: configs::Boxes,
scores: configs::Scores,
) -> Self {
let config = ConfigOutputs {
outputs: vec![ConfigOutput::Boxes(boxes), ConfigOutput::Scores(scores)],
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a YOLO segmentation model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let seg_config = configs::Detection {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 116, 8400],
/// anchors: None,
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let protos_config = configs::Protos {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 160, 160, 32],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_yolo_segdet(
/// seg_config,
/// protos_config,
/// Some(configs::DecoderVersion::Yolov8),
/// )
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_yolo_segdet(
mut self,
boxes: configs::Detection,
protos: configs::Protos,
version: Option<DecoderVersion>,
) -> Self {
let config = ConfigOutputs {
outputs: vec![ConfigOutput::Detection(boxes), ConfigOutput::Protos(protos)],
decoder_version: version,
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a YOLO split segmentation model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let boxes_config = configs::Boxes {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 4, 8400],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let scores_config = configs::Scores {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.012345, 14)),
/// shape: vec![1, 80, 8400],
/// dshape: Vec::new(),
/// };
/// let mask_config = configs::MaskCoefficients {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.0064123, 125)),
/// shape: vec![1, 32, 8400],
/// dshape: Vec::new(),
/// };
/// let protos_config = configs::Protos {
/// decoder: configs::DecoderType::Ultralytics,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 160, 160, 32],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_yolo_split_segdet(boxes_config, scores_config, mask_config, protos_config)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_yolo_split_segdet(
mut self,
boxes: configs::Boxes,
scores: configs::Scores,
mask_coefficients: configs::MaskCoefficients,
protos: configs::Protos,
) -> Self {
let config = ConfigOutputs {
outputs: vec![
ConfigOutput::Boxes(boxes),
ConfigOutput::Scores(scores),
ConfigOutput::MaskCoefficients(mask_coefficients),
ConfigOutput::Protos(protos),
],
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a ModelPack detection model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let boxes_config = configs::Boxes {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 8400, 1, 4],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let scores_config = configs::Scores {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 8400, 3],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_modelpack_det(boxes_config, scores_config)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_modelpack_det(
mut self,
boxes: configs::Boxes,
scores: configs::Scores,
) -> Self {
let config = ConfigOutputs {
outputs: vec![ConfigOutput::Boxes(boxes), ConfigOutput::Scores(scores)],
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a ModelPack split detection model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let config0 = configs::Detection {
/// anchors: Some(vec![
/// [0.13750000298023224, 0.2074074000120163],
/// [0.2541666626930237, 0.21481481194496155],
/// [0.23125000298023224, 0.35185185074806213],
/// ]),
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 17, 30, 18],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let config1 = configs::Detection {
/// anchors: Some(vec![
/// [0.36666667461395264, 0.31481480598449707],
/// [0.38749998807907104, 0.4740740656852722],
/// [0.5333333611488342, 0.644444465637207],
/// ]),
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 9, 15, 18],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
///
/// let decoder = DecoderBuilder::new()
/// .with_config_modelpack_det_split(vec![config0, config1])
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_modelpack_det_split(mut self, boxes: Vec<configs::Detection>) -> Self {
let outputs = boxes.into_iter().map(ConfigOutput::Detection).collect();
let config = ConfigOutputs {
outputs,
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a ModelPack segmentation detection model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let boxes_config = configs::Boxes {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.012345, 26)),
/// shape: vec![1, 8400, 1, 4],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let scores_config = configs::Scores {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 8400, 2],
/// dshape: Vec::new(),
/// };
/// let seg_config = configs::Segmentation {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 640, 640, 3],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_modelpack_segdet(boxes_config, scores_config, seg_config)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_modelpack_segdet(
mut self,
boxes: configs::Boxes,
scores: configs::Scores,
segmentation: configs::Segmentation,
) -> Self {
let config = ConfigOutputs {
outputs: vec![
ConfigOutput::Boxes(boxes),
ConfigOutput::Scores(scores),
ConfigOutput::Segmentation(segmentation),
],
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a ModelPack segmentation split detection model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let config0 = configs::Detection {
/// anchors: Some(vec![
/// [0.36666667461395264, 0.31481480598449707],
/// [0.38749998807907104, 0.4740740656852722],
/// [0.5333333611488342, 0.644444465637207],
/// ]),
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.08547406643629074, 174)),
/// shape: vec![1, 9, 15, 18],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let config1 = configs::Detection {
/// anchors: Some(vec![
/// [0.13750000298023224, 0.2074074000120163],
/// [0.2541666626930237, 0.21481481194496155],
/// [0.23125000298023224, 0.35185185074806213],
/// ]),
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.09929127991199493, 183)),
/// shape: vec![1, 17, 30, 18],
/// dshape: Vec::new(),
/// normalized: Some(true),
/// };
/// let seg_config = configs::Segmentation {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 640, 640, 2],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_modelpack_segdet_split(vec![config0, config1], seg_config)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_modelpack_segdet_split(
mut self,
boxes: Vec<configs::Detection>,
segmentation: configs::Segmentation,
) -> Self {
let mut outputs = boxes
.into_iter()
.map(ConfigOutput::Detection)
.collect::<Vec<_>>();
outputs.push(ConfigOutput::Segmentation(segmentation));
let config = ConfigOutputs {
outputs,
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Loads a ModelPack segmentation model configuration. Use
/// `DecoderBuilder.build()` to parse the model configuration.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{ DecoderBuilder, DecoderResult, configs };
/// # fn main() -> DecoderResult<()> {
/// let seg_config = configs::Segmentation {
/// decoder: configs::DecoderType::ModelPack,
/// quantization: Some(configs::QuantTuple(0.0064123, -31)),
/// shape: vec![1, 640, 640, 3],
/// dshape: Vec::new(),
/// };
/// let decoder = DecoderBuilder::new()
/// .with_config_modelpack_seg(seg_config)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_config_modelpack_seg(mut self, segmentation: configs::Segmentation) -> Self {
let config = ConfigOutputs {
outputs: vec![ConfigOutput::Segmentation(segmentation)],
..Default::default()
};
self.config_src.replace(ConfigSource::Config(config));
self
}
/// Add an output to the decoder configuration.
///
/// Incrementally builds the model configuration by adding outputs one at
/// a time. The decoder resolves the model type from the combination of
/// outputs during `build()`.
///
/// If `dshape` is non-empty on the output, `shape` is automatically
/// derived from it (the size component of each named dimension). This
/// prevents conflicts between `shape` and `dshape`.
///
/// This uses the programmatic config path. Calling this after
/// `with_config_json_str()` or `with_config_yaml_str()` replaces the
/// string-based config source.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult, ConfigOutput, configs};
/// # fn main() -> DecoderResult<()> {
/// let decoder = DecoderBuilder::new()
/// .add_output(ConfigOutput::Scores(configs::Scores {
/// decoder: configs::DecoderType::Ultralytics,
/// dshape: vec![
/// (configs::DimName::Batch, 1),
/// (configs::DimName::NumClasses, 80),
/// (configs::DimName::NumBoxes, 8400),
/// ],
/// ..Default::default()
/// }))
/// .add_output(ConfigOutput::Boxes(configs::Boxes {
/// decoder: configs::DecoderType::Ultralytics,
/// dshape: vec![
/// (configs::DimName::Batch, 1),
/// (configs::DimName::BoxCoords, 4),
/// (configs::DimName::NumBoxes, 8400),
/// ],
/// ..Default::default()
/// }))
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn add_output(mut self, output: ConfigOutput) -> Self {
if !matches!(self.config_src, Some(ConfigSource::Config(_))) {
self.config_src = Some(ConfigSource::Config(ConfigOutputs::default()));
}
if let Some(ConfigSource::Config(ref mut config)) = self.config_src {
config.outputs.push(Self::normalize_output(output));
}
self
}
/// Sets the decoder version for Ultralytics models.
///
/// This is used with `add_output()` to specify the YOLO architecture
/// version when it cannot be inferred from the output shapes alone.
///
/// - `Yolov5`, `Yolov8`, `Yolo11`: Traditional models requiring external
/// NMS
/// - `Yolo26`: End-to-end models with NMS embedded in the model graph
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult, ConfigOutput, configs};
/// # fn main() -> DecoderResult<()> {
/// let decoder = DecoderBuilder::new()
/// .add_output(ConfigOutput::Detection(configs::Detection {
/// decoder: configs::DecoderType::Ultralytics,
/// dshape: vec![
/// (configs::DimName::Batch, 1),
/// (configs::DimName::NumBoxes, 100),
/// (configs::DimName::NumFeatures, 6),
/// ],
/// ..Default::default()
/// }))
/// .with_decoder_version(configs::DecoderVersion::Yolo26)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_decoder_version(mut self, version: configs::DecoderVersion) -> Self {
if !matches!(self.config_src, Some(ConfigSource::Config(_))) {
self.config_src = Some(ConfigSource::Config(ConfigOutputs::default()));
}
if let Some(ConfigSource::Config(ref mut config)) = self.config_src {
config.decoder_version = Some(version);
}
self
}
/// Normalize an output: if dshape is non-empty, derive shape from it.
fn normalize_output(mut output: ConfigOutput) -> ConfigOutput {
fn normalize_shape(shape: &mut Vec<usize>, dshape: &[(configs::DimName, usize)]) {
if !dshape.is_empty() {
*shape = dshape.iter().map(|(_, size)| *size).collect();
}
}
match &mut output {
ConfigOutput::Detection(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::Boxes(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::Scores(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::Protos(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::Segmentation(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::MaskCoefficients(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::Mask(c) => normalize_shape(&mut c.shape, &c.dshape),
ConfigOutput::Classes(c) => normalize_shape(&mut c.shape, &c.dshape),
}
output
}
/// Sets the scores threshold of the decoder
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_score_threshold(0.654)
/// .build()?;
/// assert_eq!(decoder.score_threshold, 0.654);
/// # Ok(())
/// # }
/// ```
pub fn with_score_threshold(mut self, score_threshold: f32) -> Self {
self.score_threshold = score_threshold;
self
}
/// Sets the IOU threshold of the decoder. Has no effect when NMS is set to
/// `None`
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_iou_threshold(0.654)
/// .build()?;
/// assert_eq!(decoder.iou_threshold, 0.654);
/// # Ok(())
/// # }
/// ```
pub fn with_iou_threshold(mut self, iou_threshold: f32) -> Self {
self.iou_threshold = iou_threshold;
self
}
/// Sets the NMS mode for the decoder.
///
/// - `Some(Nms::Auto)` — resolve from model config (e.g. `edgefirst.json`)
/// or fall back to `ClassAgnostic` (this is the builder default)
/// - `Some(Nms::ClassAgnostic)` — class-agnostic NMS: suppress overlapping
/// boxes regardless of class label
/// - `Some(Nms::ClassAware)` — class-aware NMS: only suppress boxes that
/// share the same class label AND overlap above the IoU threshold
/// - `None` — bypass NMS entirely (for end-to-end models with embedded NMS)
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult, configs::Nms};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_nms(Some(Nms::ClassAware))
/// .build()?;
/// assert_eq!(decoder.nms, Some(Nms::ClassAware));
/// # Ok(())
/// # }
/// ```
pub fn with_nms(mut self, nms: Option<configs::Nms>) -> Self {
self.nms = nms;
self
}
/// Sets the maximum number of candidate boxes fed into NMS after score
/// filtering. Uses partial sort (O(N)) to select the top-K candidates,
/// dramatically reducing the O(N²) NMS cost when many low-confidence
/// proposals pass the threshold (common with mAP eval at 0.001).
///
/// Default: 300.
///
/// # ⚠️ Validation vs Deployment
///
/// The default is appropriate for **deployment** where
/// `score_threshold ≥ 0.25` means few anchors survive filtering and
/// top-K is effectively a no-op.
///
/// For **COCO mAP evaluation** (`score_threshold ≈ 0.001`), set this to
/// the total anchor count (8 400 for standard 640 × 640 YOLO models) or
/// to `0` (no limit) so that all score-passing candidates reach NMS.
/// Failing to do so causes **~9 pp box mAP loss** — the decoder math is
/// correct but the evaluation protocol requires full recall across the
/// confidence range.
///
/// Post-processing latency scales with candidate count. At deployment
/// thresholds the cost difference is negligible; at validation thresholds
/// it is measurable but necessary for correct results.
///
/// # Examples
///
/// Deployment (default top-K, high score threshold):
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_score_threshold(0.25)
/// // pre_nms_top_k defaults to 300 — appropriate here
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// COCO mAP evaluation (pass all anchors to NMS):
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_score_threshold(0.001)
/// .with_pre_nms_top_k(8400) // all YOLO anchors
/// .with_max_det(300)
/// .build()?;
/// assert_eq!(decoder.pre_nms_top_k, 8400);
/// # Ok(())
/// # }
/// ```
pub fn with_pre_nms_top_k(mut self, pre_nms_top_k: usize) -> Self {
self.pre_nms_top_k = pre_nms_top_k;
self
}
/// Sets the maximum number of detections returned after NMS.
/// Matches the Ultralytics `max_det` parameter.
///
/// Default: 300.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_max_det(100)
/// .build()?;
/// assert_eq!(decoder.max_det, 100);
/// # Ok(())
/// # }
/// ```
pub fn with_max_det(mut self, max_det: usize) -> Self {
self.max_det = max_det;
self
}
/// Sets the model input dimensions `(width, height)` consumed by the
/// EDGEAI-1303 normalization path. Use this when building via
/// [`with_config`](Self::with_config) / [`add_output`](Self::add_output)
/// (no schema) and the model emits pixel-space boxes that need to be
/// divided by `(W, H)` before NMS.
///
/// When the builder is also configured with [`with_schema`](Self::with_schema)
/// (or `with_config_json_str` / `with_config_yaml_str`) and the schema's
/// `input` block carries usable dims, this explicit override **takes
/// precedence** so callers can correct schemas with missing or wrong
/// input specs without rewriting the schema.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_yaml = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.yaml")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_yaml_str(config_yaml)
/// .with_input_dims(640, 640)
/// .build()?;
/// assert_eq!(decoder.input_dims(), Some((640, 640)));
/// # Ok(())
/// # }
/// ```
pub fn with_input_dims(mut self, width: usize, height: usize) -> Self {
self.input_dims = Some((width, height));
self
}
/// Builds the decoder with the given settings. If the config is a JSON or
/// YAML string, this will deserialize the JSON or YAML and then parse the
/// configuration information.
///
/// # Examples
/// ```rust
/// # use edgefirst_decoder::{DecoderBuilder, DecoderResult};
/// # fn main() -> DecoderResult<()> {
/// # let config_json = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/modelpack_split.json")).to_string();
/// let decoder = DecoderBuilder::new()
/// .with_config_json_str(config_json)
/// .with_score_threshold(0.654)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn build(self) -> Result<Decoder, DecoderError> {
let decode_dtype = self.decode_dtype;
let explicit_input_dims = self.input_dims;
let (config, decode_program, per_scale_plan, schema_input_dims) = match self.config_src {
Some(ConfigSource::Json(s)) => {
Self::build_from_schema(SchemaV2::parse_json(&s)?, decode_dtype)?
}
Some(ConfigSource::Yaml(s)) => {
Self::build_from_schema(SchemaV2::parse_yaml(&s)?, decode_dtype)?
}
Some(ConfigSource::Config(c)) => (c, None, None, None),
Some(ConfigSource::Schema(schema)) => Self::build_from_schema(schema, decode_dtype)?,
None => return Err(DecoderError::NoConfig),
};
// Explicit `with_input_dims(W, H)` overrides any schema-derived
// value so callers can fix schemas with missing or wrong input
// specs without rewriting the schema (EDGEAI-1303).
let input_dims = explicit_input_dims.or(schema_input_dims);
// Enforce the physical-order contract: when dshape is present
// it must describe the same axes as shape in the same order,
// listed from outermost to innermost. Ambiguous-layout roles
// (Protos, Boxes, Scores, MaskCoefficients, Classes, Detection)
// may still omit dshape when shape is already in the decoder's
// canonical order.
for output in &config.outputs {
Decoder::validate_output_layout(output.into())?;
}
// Extract normalized flag from config outputs.
//
// The per-scale subsystem (DFL/LTRB → dist2bbox → sigmoid) emits
// boxes in pixel coordinates by design — `(grid + dist) * stride`
// — independently of any `normalized: true` annotation in the
// schema. The schema's `normalized` flag describes the model's
// training-time convention, not the runtime output coord space
// for this code path. Override to `Some(false)` when the
// per-scale path is active so `Decoder::normalized_boxes()`
// matches what `decode_proto`/`decode` actually produce; the
// legacy / non-per-scale paths still honor the schema flag.
let normalized = if per_scale_plan.is_some() {
Some(false)
} else {
Self::get_normalized(&config.outputs)
};
// NMS precedence:
// Some(ClassAgnostic|ClassAware) → explicit user override
// Some(Auto) → resolve from config, fallback to ClassAgnostic
// None → NMS disabled (explicit)
//
// `Auto` is always resolved to a concrete mode here — it never
// persists into the built `Decoder`, even if the config itself
// contains `Auto`.
let resolve_auto = |nms: Option<configs::Nms>| match nms {
Some(configs::Nms::Auto) | None => Some(configs::Nms::ClassAgnostic),
concrete => concrete,
};
let nms = match self.nms {
Some(configs::Nms::Auto) => resolve_auto(config.nms),
other => other,
};
// When the per-scale path is active, the per_scale subsystem owns
// model decoding entirely — `decode` / `decode_proto` short-circuit
// on `per_scale.is_some()` before reading `model_type`. Skip the
// legacy ModelType validation, which otherwise rejects per-scale
// schemas that carry `decoder_version: yolo26` (an
// "end-to-end" hint) but use the per-scale split outputs rather
// than the end-to-end split-output shape the legacy validator
// expects. We keep a placeholder `ModelType` so the field remains
// valid; it is dead state for per-scale Decoders.
let model_type = if per_scale_plan.is_some() {
// Drop the un-needed config; the per-scale subsystem owns it.
drop(config);
ModelType::PerScale
} else {
Self::get_model_type(config)?
};
let per_scale = per_scale_plan
.map(|plan| std::sync::Mutex::new(crate::per_scale::PerScaleDecoder::new(plan)));
debug_assert!(
!matches!(nms, Some(configs::Nms::Auto)),
"Nms::Auto must be resolved to a concrete mode before building Decoder"
);
Ok(Decoder {
model_type,
iou_threshold: self.iou_threshold,
score_threshold: self.score_threshold,
nms,
pre_nms_top_k: self.pre_nms_top_k,
max_det: self.max_det,
normalized,
input_dims,
decode_program,
per_scale,
})
}
/// Validate a [`SchemaV2`] and lower it to the (legacy `ConfigOutputs`,
/// optional `DecodeProgram`, optional `PerScalePlan`) tuple the rest
/// of `build()` consumes.
///
/// Centralises the v2 lowering so JSON, YAML, and direct
/// `with_schema` callers all go through the same validation,
/// merge-program, and per-scale plan construction. `SchemaV2::parse_json`
/// / `parse_yaml` already auto-detect v1 vs v2 input and return a v2
/// schema either way (v1 inputs are upgraded in memory via
/// `from_v1`), so this helper is the sole place that turns a
/// schema into builder-ready state.
#[allow(clippy::type_complexity)]
fn build_from_schema(
schema: SchemaV2,
decode_dtype: DecodeDtype,
) -> Result<
(
ConfigOutputs,
Option<DecodeProgram>,
Option<PerScalePlan>,
Option<(usize, usize)>,
),
DecoderError,
> {
schema.validate()?;
let program = DecodeProgram::try_from_schema(&schema)?;
let per_scale = PerScalePlan::try_from_schema(&schema, decode_dtype)?;
// Extract model input (W, H) from `input.shape`/`dshape`. Used by
// the legacy decode path to honour `normalized: false` (see
// EDGEAI-1303). `None` is fine when the schema omits the input
// spec — the decoder falls back to the protobox `>2.0` reject.
let input_dims = schema.input.as_ref().and_then(input_dims_from_spec);
let legacy = schema.to_legacy_config_outputs()?;
Ok((legacy, program, per_scale, input_dims))
}
/// Extracts the normalized flag from config outputs.
/// - `Some(true)`: Boxes are in normalized [0,1] coordinates
/// - `Some(false)`: Boxes are in pixel coordinates
/// - `None`: Unknown (not specified in config), caller must infer
fn get_normalized(outputs: &[ConfigOutput]) -> Option<bool> {
for output in outputs {
match output {
ConfigOutput::Detection(det) => return det.normalized,
ConfigOutput::Boxes(boxes) => return boxes.normalized,
_ => {}
}
}
None // not specified
}
fn get_model_type(configs: ConfigOutputs) -> Result<ModelType, DecoderError> {
// yolo or modelpack
let mut yolo = false;
let mut modelpack = false;
for c in &configs.outputs {
match c.decoder() {
DecoderType::ModelPack => modelpack = true,
DecoderType::Ultralytics => yolo = true,
}
}
match (modelpack, yolo) {
(true, true) => Err(DecoderError::InvalidConfig(
"Both ModelPack and Yolo outputs found in config".to_string(),
)),
(true, false) => Self::get_model_type_modelpack(configs),
(false, true) => Self::get_model_type_yolo(configs),
(false, false) => Err(DecoderError::InvalidConfig(
"No outputs found in config".to_string(),
)),
}
}
fn get_model_type_yolo(configs: ConfigOutputs) -> Result<ModelType, DecoderError> {
let mut boxes = None;
let mut protos = None;
let mut split_boxes = None;
let mut split_scores = None;
let mut split_mask_coeff = None;
let mut split_classes = None;
for c in configs.outputs {
match c {
ConfigOutput::Detection(detection) => boxes = Some(detection),
ConfigOutput::Segmentation(_) => {
return Err(DecoderError::InvalidConfig(
"Invalid Segmentation output with Yolo decoder".to_string(),
));
}
ConfigOutput::Protos(protos_) => protos = Some(protos_),
ConfigOutput::Mask(_) => {
return Err(DecoderError::InvalidConfig(
"Invalid Mask output with Yolo decoder".to_string(),
));
}
ConfigOutput::Scores(scores) => split_scores = Some(scores),
ConfigOutput::Boxes(boxes) => split_boxes = Some(boxes),
ConfigOutput::MaskCoefficients(mask_coeff) => split_mask_coeff = Some(mask_coeff),
ConfigOutput::Classes(classes) => split_classes = Some(classes),
}
}
// Use end-to-end model types when:
// 1. decoder_version is explicitly set to Yolo26 (definitive), OR
// decoder_version is not set but the dshapes are (batch, num_boxes,
// num_features)
let is_end_to_end_dshape = boxes.as_ref().is_some_and(|b| {
let dims = b.dshape.iter().map(|(d, _)| *d).collect::<Vec<_>>();
dims == vec![DimName::Batch, DimName::NumBoxes, DimName::NumFeatures]
});
let is_end_to_end = configs
.decoder_version
.map(|v| v.is_end_to_end())
.unwrap_or(is_end_to_end_dshape);
if is_end_to_end {
if let Some(boxes) = boxes {
if let Some(protos) = protos {
Self::verify_yolo_seg_det_26(&boxes, &protos)?;
return Ok(ModelType::YoloEndToEndSegDet { boxes, protos });
} else {
Self::verify_yolo_det_26(&boxes)?;
return Ok(ModelType::YoloEndToEndDet { boxes });
}
} else if let (Some(split_boxes), Some(split_scores), Some(split_classes)) =
(split_boxes, split_scores, split_classes)
{
if let (Some(split_mask_coeff), Some(protos)) = (split_mask_coeff, protos) {
Self::verify_yolo_split_end_to_end_segdet(
&split_boxes,
&split_scores,
&split_classes,
&split_mask_coeff,
&protos,
)?;
return Ok(ModelType::YoloSplitEndToEndSegDet {
boxes: split_boxes,
scores: split_scores,
classes: split_classes,
mask_coeff: split_mask_coeff,
protos,
});
}
Self::verify_yolo_split_end_to_end_det(
&split_boxes,
&split_scores,
&split_classes,
)?;
return Ok(ModelType::YoloSplitEndToEndDet {
boxes: split_boxes,
scores: split_scores,
classes: split_classes,
});
} else {
return Err(DecoderError::InvalidConfig(
"Invalid Yolo end-to-end model outputs".to_string(),
));
}
}
if let Some(boxes) = boxes {
match (split_mask_coeff, protos) {
(Some(mask_coeff), Some(protos)) => {
// 2-way split: combined detection + separate mask_coeff + protos
Self::verify_yolo_seg_det_2way(&boxes, &mask_coeff, &protos)?;
Ok(ModelType::YoloSegDet2Way {
boxes,
mask_coeff,
protos,
})
}
(_, Some(protos)) => {
// Unsplit: mask_coefs embedded in detection tensor
Self::verify_yolo_seg_det(&boxes, &protos)?;
Ok(ModelType::YoloSegDet { boxes, protos })
}
_ => {
Self::verify_yolo_det(&boxes)?;
Ok(ModelType::YoloDet { boxes })
}
}
} else if let (Some(boxes), Some(scores)) = (split_boxes, split_scores) {
if let (Some(mask_coeff), Some(protos)) = (split_mask_coeff, protos) {
Self::verify_yolo_split_segdet(&boxes, &scores, &mask_coeff, &protos)?;
Ok(ModelType::YoloSplitSegDet {
boxes,
scores,
mask_coeff,
protos,
})
} else {
Self::verify_yolo_split_det(&boxes, &scores)?;
Ok(ModelType::YoloSplitDet { boxes, scores })
}
} else {
Err(DecoderError::InvalidConfig(
"Invalid Yolo model outputs".to_string(),
))
}
}
fn verify_yolo_det(detect: &configs::Detection) -> Result<(), DecoderError> {
if detect.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Detection shape {:?}",
detect.shape
)));
}
Self::verify_dshapes(
&detect.dshape,
&detect.shape,
"Detection",
&[DimName::Batch, DimName::NumFeatures, DimName::NumBoxes],
)?;
if !detect.dshape.is_empty() {
Self::get_class_count(&detect.dshape, None, None)?;
} else {
Self::get_class_count_no_dshape(detect.into(), None)?;
}
Ok(())
}
fn verify_yolo_det_26(detect: &configs::Detection) -> Result<(), DecoderError> {
if detect.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Detection shape {:?}",
detect.shape
)));
}
Self::verify_dshapes(
&detect.dshape,
&detect.shape,
"Detection",
&[DimName::Batch, DimName::NumFeatures, DimName::NumBoxes],
)?;
if !detect.shape.contains(&6) {
return Err(DecoderError::InvalidConfig(
"Yolo26 Detection must have 6 features".to_string(),
));
}
Ok(())
}
fn verify_yolo_seg_det(
detection: &configs::Detection,
protos: &configs::Protos,
) -> Result<(), DecoderError> {
if detection.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Detection shape {:?}",
detection.shape
)));
}
if protos.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Protos shape {:?}",
protos.shape
)));
}
Self::verify_dshapes(
&detection.dshape,
&detection.shape,
"Detection",
&[DimName::Batch, DimName::NumFeatures, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&protos.dshape,
&protos.shape,
"Protos",
&[
DimName::Batch,
DimName::Height,
DimName::Width,
DimName::NumProtos,
],
)?;
let protos_count = Self::get_protos_count(&protos.dshape)
.unwrap_or_else(|| protos.shape[1].min(protos.shape[3]));
log::debug!("Protos count: {}", protos_count);
log::debug!("Detection dshape: {:?}", detection.dshape);
let classes = if !detection.dshape.is_empty() {
Self::get_class_count(&detection.dshape, Some(protos_count), None)?
} else {
Self::get_class_count_no_dshape(detection.into(), Some(protos_count))?
};
if classes == 0 {
return Err(DecoderError::InvalidConfig(
"Yolo Segmentation Detection has zero classes".to_string(),
));
}
Ok(())
}
fn verify_yolo_seg_det_2way(
detection: &configs::Detection,
mask_coeff: &configs::MaskCoefficients,
protos: &configs::Protos,
) -> Result<(), DecoderError> {
if detection.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo 2-Way Detection shape {:?}",
detection.shape
)));
}
if mask_coeff.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo 2-Way Mask Coefficients shape {:?}",
mask_coeff.shape
)));
}
if protos.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo 2-Way Protos shape {:?}",
protos.shape
)));
}
Self::verify_dshapes(
&detection.dshape,
&detection.shape,
"Detection",
&[DimName::Batch, DimName::NumFeatures, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&mask_coeff.dshape,
&mask_coeff.shape,
"Mask Coefficients",
&[DimName::Batch, DimName::NumProtos, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&protos.dshape,
&protos.shape,
"Protos",
&[
DimName::Batch,
DimName::Height,
DimName::Width,
DimName::NumProtos,
],
)?;
// Validate num_boxes match between detection and mask_coeff
let det_num = Self::get_box_count(&detection.dshape).unwrap_or(detection.shape[2]);
let mask_num = Self::get_box_count(&mask_coeff.dshape).unwrap_or(mask_coeff.shape[2]);
if det_num != mask_num {
return Err(DecoderError::InvalidConfig(format!(
"Yolo 2-Way Detection num_boxes {} incompatible with Mask Coefficients num_boxes {}",
det_num, mask_num
)));
}
// Validate mask_coeff channels match protos channels
let mask_channels = if !mask_coeff.dshape.is_empty() {
Self::get_protos_count(&mask_coeff.dshape).ok_or_else(|| {
DecoderError::InvalidConfig(
"Could not find num_protos in mask_coeff config".to_string(),
)
})?
} else {
mask_coeff.shape[1]
};
let proto_channels = if !protos.dshape.is_empty() {
Self::get_protos_count(&protos.dshape).ok_or_else(|| {
DecoderError::InvalidConfig(
"Could not find num_protos in protos config".to_string(),
)
})?
} else {
protos.shape[1].min(protos.shape[3])
};
if mask_channels != proto_channels {
return Err(DecoderError::InvalidConfig(format!(
"Yolo 2-Way Protos channels {} incompatible with Mask Coefficients channels {}",
proto_channels, mask_channels
)));
}
// Validate detection has classes (nc+4 features, no mask_coefs embedded)
if !detection.dshape.is_empty() {
Self::get_class_count(&detection.dshape, None, None)?;
} else {
Self::get_class_count_no_dshape(detection.into(), None)?;
}
Ok(())
}
fn verify_yolo_seg_det_26(
detection: &configs::Detection,
protos: &configs::Protos,
) -> Result<(), DecoderError> {
if detection.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Detection shape {:?}",
detection.shape
)));
}
if protos.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Protos shape {:?}",
protos.shape
)));
}
Self::verify_dshapes(
&detection.dshape,
&detection.shape,
"Detection",
&[DimName::Batch, DimName::NumFeatures, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&protos.dshape,
&protos.shape,
"Protos",
&[
DimName::Batch,
DimName::Height,
DimName::Width,
DimName::NumProtos,
],
)?;
let protos_count = Self::get_protos_count(&protos.dshape)
.unwrap_or_else(|| protos.shape[1].min(protos.shape[3]));
log::debug!("Protos count: {}", protos_count);
log::debug!("Detection dshape: {:?}", detection.dshape);
if !detection.shape.contains(&(6 + protos_count)) {
return Err(DecoderError::InvalidConfig(format!(
"Yolo26 Segmentation Detection must have num_features be 6 + num_protos = {}",
6 + protos_count
)));
}
Ok(())
}
fn verify_yolo_split_det(
boxes: &configs::Boxes,
scores: &configs::Scores,
) -> Result<(), DecoderError> {
if boxes.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Split Boxes shape {:?}",
boxes.shape
)));
}
if scores.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Split Scores shape {:?}",
scores.shape
)));
}
Self::verify_dshapes(
&boxes.dshape,
&boxes.shape,
"Boxes",
&[DimName::Batch, DimName::BoxCoords, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&scores.dshape,
&scores.shape,
"Scores",
&[DimName::Batch, DimName::NumClasses, DimName::NumBoxes],
)?;
let boxes_num = Self::get_box_count(&boxes.dshape).unwrap_or(boxes.shape[2]);
let scores_num = Self::get_box_count(&scores.dshape).unwrap_or(scores.shape[2]);
if boxes_num != scores_num {
return Err(DecoderError::InvalidConfig(format!(
"Yolo Split Detection Boxes num {} incompatible with Scores num {}",
boxes_num, scores_num
)));
}
Ok(())
}
fn verify_yolo_split_segdet(
boxes: &configs::Boxes,
scores: &configs::Scores,
mask_coeff: &configs::MaskCoefficients,
protos: &configs::Protos,
) -> Result<(), DecoderError> {
if boxes.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Split Boxes shape {:?}",
boxes.shape
)));
}
if scores.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Split Scores shape {:?}",
scores.shape
)));
}
if mask_coeff.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Split Mask Coefficients shape {:?}",
mask_coeff.shape
)));
}
if protos.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid Yolo Protos shape {:?}",
mask_coeff.shape
)));
}
Self::verify_dshapes(
&boxes.dshape,
&boxes.shape,
"Boxes",
&[DimName::Batch, DimName::BoxCoords, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&scores.dshape,
&scores.shape,
"Scores",
&[DimName::Batch, DimName::NumClasses, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&mask_coeff.dshape,
&mask_coeff.shape,
"Mask Coefficients",
&[DimName::Batch, DimName::NumProtos, DimName::NumBoxes],
)?;
Self::verify_dshapes(
&protos.dshape,
&protos.shape,
"Protos",
&[
DimName::Batch,
DimName::Height,
DimName::Width,
DimName::NumProtos,
],
)?;
let boxes_num = Self::get_box_count(&boxes.dshape).unwrap_or(boxes.shape[2]);
let scores_num = Self::get_box_count(&scores.dshape).unwrap_or(scores.shape[2]);
let mask_num = Self::get_box_count(&mask_coeff.dshape).unwrap_or(mask_coeff.shape[2]);
let mask_channels = if !mask_coeff.dshape.is_empty() {
Self::get_protos_count(&mask_coeff.dshape).ok_or_else(|| {
DecoderError::InvalidConfig("Could not find num_protos in config".to_string())
})?
} else {
mask_coeff.shape[1]
};
let proto_channels = if !protos.dshape.is_empty() {
Self::get_protos_count(&protos.dshape).ok_or_else(|| {
DecoderError::InvalidConfig("Could not find num_protos in config".to_string())
})?
} else {
protos.shape[1].min(protos.shape[3])
};
if boxes_num != scores_num {
return Err(DecoderError::InvalidConfig(format!(
"Yolo Split Detection Boxes num {} incompatible with Scores num {}",
boxes_num, scores_num
)));
}
if boxes_num != mask_num {
return Err(DecoderError::InvalidConfig(format!(
"Yolo Split Detection Boxes num {} incompatible with Mask Coefficients num {}",
boxes_num, mask_num
)));
}
if proto_channels != mask_channels {
return Err(DecoderError::InvalidConfig(format!(
"Yolo Protos channels {} incompatible with Mask Coefficients channels {}",
proto_channels, mask_channels
)));
}
Ok(())
}
fn verify_yolo_split_end_to_end_det(
boxes: &configs::Boxes,
scores: &configs::Scores,
classes: &configs::Classes,
) -> Result<(), DecoderError> {
if boxes.shape.len() != 3 || !boxes.shape.contains(&4) {
return Err(DecoderError::InvalidConfig(format!(
"Split end-to-end boxes must be [batch, N, 4], got {:?}",
boxes.shape
)));
}
if scores.shape.len() != 3 || !scores.shape.contains(&1) {
return Err(DecoderError::InvalidConfig(format!(
"Split end-to-end scores must be [batch, N, 1], got {:?}",
scores.shape
)));
}
if classes.shape.len() != 3 || !classes.shape.contains(&1) {
return Err(DecoderError::InvalidConfig(format!(
"Split end-to-end classes must be [batch, N, 1], got {:?}",
classes.shape
)));
}
Ok(())
}
fn verify_yolo_split_end_to_end_segdet(
boxes: &configs::Boxes,
scores: &configs::Scores,
classes: &configs::Classes,
mask_coeff: &configs::MaskCoefficients,
protos: &configs::Protos,
) -> Result<(), DecoderError> {
Self::verify_yolo_split_end_to_end_det(boxes, scores, classes)?;
if mask_coeff.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid split end-to-end mask coefficients shape {:?}",
mask_coeff.shape
)));
}
if protos.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid protos shape {:?}",
protos.shape
)));
}
Ok(())
}
fn get_model_type_modelpack(configs: ConfigOutputs) -> Result<ModelType, DecoderError> {
let mut split_decoders = Vec::new();
let mut segment_ = None;
let mut scores_ = None;
let mut boxes_ = None;
for c in configs.outputs {
match c {
ConfigOutput::Detection(detection) => split_decoders.push(detection),
ConfigOutput::Segmentation(segmentation) => segment_ = Some(segmentation),
ConfigOutput::Mask(_) => {}
ConfigOutput::Protos(_) => {
return Err(DecoderError::InvalidConfig(
"ModelPack should not have protos".to_string(),
));
}
ConfigOutput::Scores(scores) => scores_ = Some(scores),
ConfigOutput::Boxes(boxes) => boxes_ = Some(boxes),
ConfigOutput::MaskCoefficients(_) => {
return Err(DecoderError::InvalidConfig(
"ModelPack should not have mask coefficients".to_string(),
));
}
ConfigOutput::Classes(_) => {
return Err(DecoderError::InvalidConfig(
"ModelPack should not have classes output".to_string(),
));
}
}
}
if let Some(segmentation) = segment_ {
if !split_decoders.is_empty() {
let classes = Self::verify_modelpack_split_det(&split_decoders)?;
Self::verify_modelpack_seg(&segmentation, Some(classes))?;
Ok(ModelType::ModelPackSegDetSplit {
detection: split_decoders,
segmentation,
})
} else if let (Some(scores), Some(boxes)) = (scores_, boxes_) {
let classes = Self::verify_modelpack_det(&boxes, &scores)?;
Self::verify_modelpack_seg(&segmentation, Some(classes))?;
Ok(ModelType::ModelPackSegDet {
boxes,
scores,
segmentation,
})
} else {
Self::verify_modelpack_seg(&segmentation, None)?;
Ok(ModelType::ModelPackSeg { segmentation })
}
} else if !split_decoders.is_empty() {
Self::verify_modelpack_split_det(&split_decoders)?;
Ok(ModelType::ModelPackDetSplit {
detection: split_decoders,
})
} else if let (Some(scores), Some(boxes)) = (scores_, boxes_) {
Self::verify_modelpack_det(&boxes, &scores)?;
Ok(ModelType::ModelPackDet { boxes, scores })
} else {
Err(DecoderError::InvalidConfig(
"Invalid ModelPack model outputs".to_string(),
))
}
}
fn verify_modelpack_det(
boxes: &configs::Boxes,
scores: &configs::Scores,
) -> Result<usize, DecoderError> {
if boxes.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Boxes shape {:?}",
boxes.shape
)));
}
if scores.shape.len() != 3 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Scores shape {:?}",
scores.shape
)));
}
Self::verify_dshapes(
&boxes.dshape,
&boxes.shape,
"Boxes",
&[
DimName::Batch,
DimName::NumBoxes,
DimName::Padding,
DimName::BoxCoords,
],
)?;
Self::verify_dshapes(
&scores.dshape,
&scores.shape,
"Scores",
&[DimName::Batch, DimName::NumBoxes, DimName::NumClasses],
)?;
let boxes_num = Self::get_box_count(&boxes.dshape).unwrap_or(boxes.shape[1]);
let scores_num = Self::get_box_count(&scores.dshape).unwrap_or(scores.shape[1]);
if boxes_num != scores_num {
return Err(DecoderError::InvalidConfig(format!(
"ModelPack Detection Boxes num {} incompatible with Scores num {}",
boxes_num, scores_num
)));
}
let num_classes = if !scores.dshape.is_empty() {
Self::get_class_count(&scores.dshape, None, None)?
} else {
Self::get_class_count_no_dshape(scores.into(), None)?
};
Ok(num_classes)
}
fn verify_modelpack_split_det(boxes: &[configs::Detection]) -> Result<usize, DecoderError> {
let mut num_classes = None;
for b in boxes {
let Some(num_anchors) = b.anchors.as_ref().map(|a| a.len()) else {
return Err(DecoderError::InvalidConfig(
"ModelPack Split Detection missing anchors".to_string(),
));
};
if num_anchors == 0 {
return Err(DecoderError::InvalidConfig(
"ModelPack Split Detection has zero anchors".to_string(),
));
}
if b.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Split Detection shape {:?}",
b.shape
)));
}
Self::verify_dshapes(
&b.dshape,
&b.shape,
"Split Detection",
&[
DimName::Batch,
DimName::Height,
DimName::Width,
DimName::NumAnchorsXFeatures,
],
)?;
let classes = if !b.dshape.is_empty() {
Self::get_class_count(&b.dshape, None, Some(num_anchors))?
} else {
Self::get_class_count_no_dshape(b.into(), None)?
};
match num_classes {
Some(n) => {
if n != classes {
return Err(DecoderError::InvalidConfig(format!(
"ModelPack Split Detection inconsistent number of classes: previous {}, current {}",
n, classes
)));
}
}
None => {
num_classes = Some(classes);
}
}
}
Ok(num_classes.unwrap_or(0))
}
fn verify_modelpack_seg(
segmentation: &configs::Segmentation,
classes: Option<usize>,
) -> Result<(), DecoderError> {
if segmentation.shape.len() != 4 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Segmentation shape {:?}",
segmentation.shape
)));
}
Self::verify_dshapes(
&segmentation.dshape,
&segmentation.shape,
"Segmentation",
&[
DimName::Batch,
DimName::Height,
DimName::Width,
DimName::NumClasses,
],
)?;
if let Some(classes) = classes {
let seg_classes = if !segmentation.dshape.is_empty() {
Self::get_class_count(&segmentation.dshape, None, None)?
} else {
Self::get_class_count_no_dshape(segmentation.into(), None)?
};
if seg_classes != classes + 1 {
return Err(DecoderError::InvalidConfig(format!(
"ModelPack Segmentation channels {} incompatible with number of classes {}",
seg_classes, classes
)));
}
}
Ok(())
}
// verifies that dshapes match the given shape
fn verify_dshapes(
dshape: &[(DimName, usize)],
shape: &[usize],
name: &str,
dims: &[DimName],
) -> Result<(), DecoderError> {
for s in shape {
if *s == 0 {
return Err(DecoderError::InvalidConfig(format!(
"{} shape has zero dimension",
name
)));
}
}
if shape.len() != dims.len() {
return Err(DecoderError::InvalidConfig(format!(
"{} shape length {} does not match expected dims length {}",
name,
shape.len(),
dims.len()
)));
}
if dshape.is_empty() {
return Ok(());
}
// check the dshape lengths match the shape lengths
if dshape.len() != shape.len() {
return Err(DecoderError::InvalidConfig(format!(
"{} dshape length does not match shape length",
name
)));
}
// check the dshape values match the shape values
for ((dim_name, dim_size), shape_size) in dshape.iter().zip(shape) {
if dim_size != shape_size {
return Err(DecoderError::InvalidConfig(format!(
"{} dshape dimension {} size {} does not match shape size {}",
name, dim_name, dim_size, shape_size
)));
}
if *dim_name == DimName::Padding && *dim_size != 1 {
return Err(DecoderError::InvalidConfig(
"Padding dimension size must be 1".to_string(),
));
}
if *dim_name == DimName::BoxCoords && *dim_size != 4 {
return Err(DecoderError::InvalidConfig(
"BoxCoords dimension size must be 4".to_string(),
));
}
}
let dims_present = HashSet::<DimName>::from_iter(dshape.iter().map(|(name, _)| *name));
for dim in dims {
if !dims_present.contains(dim) {
return Err(DecoderError::InvalidConfig(format!(
"{} dshape missing required dimension {:?}",
name, dim
)));
}
}
Ok(())
}
fn get_box_count(dshape: &[(DimName, usize)]) -> Option<usize> {
for (dim_name, dim_size) in dshape {
if *dim_name == DimName::NumBoxes {
return Some(*dim_size);
}
}
None
}
fn get_class_count_no_dshape(
config: ConfigOutputRef,
protos: Option<usize>,
) -> Result<usize, DecoderError> {
match config {
ConfigOutputRef::Detection(detection) => match detection.decoder {
DecoderType::Ultralytics => {
if detection.shape[1] <= 4 + protos.unwrap_or(0) {
return Err(DecoderError::InvalidConfig(format!(
"Invalid shape: Yolo num_features {} must be greater than {}",
detection.shape[1],
4 + protos.unwrap_or(0),
)));
}
Ok(detection.shape[1] - 4 - protos.unwrap_or(0))
}
DecoderType::ModelPack => {
let Some(num_anchors) = detection.anchors.as_ref().map(|a| a.len()) else {
return Err(DecoderError::Internal(
"ModelPack Detection missing anchors".to_string(),
));
};
let anchors_x_features = detection.shape[3];
if anchors_x_features <= num_anchors * 5 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Split Detection shape: anchors_x_features {} not greater than number of anchors * 5 = {}",
anchors_x_features,
num_anchors * 5,
)));
}
if !anchors_x_features.is_multiple_of(num_anchors) {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Split Detection shape: anchors_x_features {} not a multiple of number of anchors {}",
anchors_x_features, num_anchors
)));
}
Ok(anchors_x_features / num_anchors - 5)
}
},
ConfigOutputRef::Scores(scores) => match scores.decoder {
DecoderType::Ultralytics => Ok(scores.shape[1]),
DecoderType::ModelPack => Ok(scores.shape[2]),
},
ConfigOutputRef::Segmentation(seg) => Ok(seg.shape[3]),
_ => Err(DecoderError::Internal(
"Attempted to get class count from unsupported config output".to_owned(),
)),
}
}
// get the class count from dshape or calculate from num_features
fn get_class_count(
dshape: &[(DimName, usize)],
protos: Option<usize>,
anchors: Option<usize>,
) -> Result<usize, DecoderError> {
if dshape.is_empty() {
return Ok(0);
}
// if it has num_classes in dshape, return it
for (dim_name, dim_size) in dshape {
if *dim_name == DimName::NumClasses {
return Ok(*dim_size);
}
}
// number of classes can be calculated from num_features - 4 for yolo. If the
// model has protos, we also subtract the number of protos.
for (dim_name, dim_size) in dshape {
if *dim_name == DimName::NumFeatures {
let protos = protos.unwrap_or(0);
if protos + 4 >= *dim_size {
return Err(DecoderError::InvalidConfig(format!(
"Invalid shape: Yolo num_features {} must be greater than {}",
*dim_size,
protos + 4,
)));
}
return Ok(*dim_size - 4 - protos);
}
}
// number of classes can be calculated from number of anchors for modelpack
// split detection
if let Some(num_anchors) = anchors {
for (dim_name, dim_size) in dshape {
if *dim_name == DimName::NumAnchorsXFeatures {
let anchors_x_features = *dim_size;
if anchors_x_features <= num_anchors * 5 {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Split Detection shape: anchors_x_features {} not greater than number of anchors * 5 = {}",
anchors_x_features,
num_anchors * 5,
)));
}
if !anchors_x_features.is_multiple_of(num_anchors) {
return Err(DecoderError::InvalidConfig(format!(
"Invalid ModelPack Split Detection shape: anchors_x_features {} not a multiple of number of anchors {}",
anchors_x_features, num_anchors
)));
}
return Ok((anchors_x_features / num_anchors) - 5);
}
}
}
Err(DecoderError::InvalidConfig(
"Cannot determine number of classes from dshape".to_owned(),
))
}
fn get_protos_count(dshape: &[(DimName, usize)]) -> Option<usize> {
for (dim_name, dim_size) in dshape {
if *dim_name == DimName::NumProtos {
return Some(*dim_size);
}
}
None
}
}