objc2-metal-performance-shaders 0.3.2

Bindings to the MetalPerformanceShaders framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
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
//! This file has been automatically generated by `objc2`'s `header-translator`.
//! DO NOT EDIT
use core::ffi::*;
use core::ptr::NonNull;
use objc2::__framework_prelude::*;
use objc2_foundation::*;
use objc2_metal::*;

use crate::*;

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSCNNLossDataDescriptor specifies a loss data descriptor.
    /// The same descriptor can be used to initialize both the
    /// labels and the optional weights data.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnlossdatadescriptor?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct MPSCNNLossDataDescriptor;
);

extern_conformance!(
    unsafe impl NSCopying for MPSCNNLossDataDescriptor {}
);

unsafe impl CopyingHelper for MPSCNNLossDataDescriptor {
    type Result = Self;
}

extern_conformance!(
    unsafe impl NSObjectProtocol for MPSCNNLossDataDescriptor {}
);

impl MPSCNNLossDataDescriptor {
    extern_methods!(
        #[cfg(all(feature = "MPSCore", feature = "MPSImage"))]
        /// Data layout of loss data. See MPSImage.h for more information.
        ///
        /// This parameter specifies the layout of loss data.
        #[unsafe(method(layout))]
        #[unsafe(method_family = none)]
        pub unsafe fn layout(&self) -> MPSDataLayout;

        /// Size of loss data: (width, height, feature channels}.
        ///
        /// This parameter specifies the size of loss data.
        #[unsafe(method(size))]
        #[unsafe(method_family = none)]
        pub unsafe fn size(&self) -> MTLSize;

        /// Row bytes of loss data.
        ///
        /// This parameter specifies the row bytes of loss data.
        #[unsafe(method(bytesPerRow))]
        #[unsafe(method_family = none)]
        pub unsafe fn bytesPerRow(&self) -> NSUInteger;

        /// Setter for [`bytesPerRow`][Self::bytesPerRow].
        #[unsafe(method(setBytesPerRow:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setBytesPerRow(&self, bytes_per_row: NSUInteger);

        /// Slice bytes of loss data.
        ///
        /// This parameter specifies the slice bytes of loss data.
        #[unsafe(method(bytesPerImage))]
        #[unsafe(method_family = none)]
        pub unsafe fn bytesPerImage(&self) -> NSUInteger;

        /// Setter for [`bytesPerImage`][Self::bytesPerImage].
        #[unsafe(method(setBytesPerImage:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setBytesPerImage(&self, bytes_per_image: NSUInteger);

        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[cfg(all(feature = "MPSCore", feature = "MPSImage"))]
        /// Make a descriptor loss data. The bytesPerRow and bytesPerImage
        /// are automatically calculated assuming a dense array. If it is
        /// not a dense array, adjust bytesPerRow and bytesPerImage to the
        /// right value by changing properties.
        ///
        /// Parameter `data`: The per-element loss data. The data must be in floating point format.
        ///
        /// Parameter `layout`: The data layout of loss data.
        ///
        /// Parameter `size`: The size of loss data.
        ///
        /// Returns: A valid MPSCNNLossDataDescriptor object or nil, if failure.
        #[unsafe(method(cnnLossDataDescriptorWithData:layout:size:))]
        #[unsafe(method_family = none)]
        pub unsafe fn cnnLossDataDescriptorWithData_layout_size(
            data: &NSData,
            layout: MPSDataLayout,
            size: MTLSize,
        ) -> Option<Retained<MPSCNNLossDataDescriptor>>;
    );
}

/// Methods declared on superclass `NSObject`.
impl MPSCNNLossDataDescriptor {
    extern_methods!(
        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSCNNLossLabels is used to hold the per-element weights buffer
    /// used by both MPSCNNLoss forward filter and MPSNNLossGradient backward filter.
    /// The MPSCNNLoss forward filter populates the MPSCNNLossLabels object
    /// and the MPSNNLossGradient backward filter consumes the state object.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnlosslabels?language=objc)
    #[unsafe(super(MPSState, NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    #[cfg(all(feature = "MPSCore", feature = "MPSState"))]
    pub struct MPSCNNLossLabels;
);

#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
extern_conformance!(
    unsafe impl NSObjectProtocol for MPSCNNLossLabels {}
);

#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
impl MPSCNNLossLabels {
    extern_methods!(
        /// Use one of the interfaces below instead.
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        /// Set labels (aka targets, ground truth) for the MPSCNNLossLabels object.
        ///
        /// The labels and weights data are copied into internal storage. The computed loss can either be a
        /// scalar value (in batch mode, a single value per image in a batch) or it
        /// can be one value per feature channel. Thus, the size of the loss image
        /// must either match the size of the input source image or be {1, 1, 1},
        /// which results in a scalar value. In this convinience initializer, the
        /// assumed size of the loss image is {1, 1, 1}.
        ///
        /// Parameter `device`: Device the state resources will be created on.
        ///
        /// Parameter `labelsDescriptor`: Describes the labels data. This includes:
        /// - The per-element labels data. The data must be in floating point format.
        /// - Data layout of labels data. See MPSImage.h for more information.
        /// - Size of labels data: (width, height, feature channels}.
        /// - Optionally, row bytes of labels data.
        /// - Optionally, slice bytes of labels data.
        #[unsafe(method(initWithDevice:labelsDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_labelsDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            labels_descriptor: &MPSCNNLossDataDescriptor,
        ) -> Retained<Self>;

        /// Set labels (aka targets, ground truth) and weights for the MPSCNNLossLabels object.
        /// Weights are optional.
        ///
        /// The labels and weights data are copied into internal storage.
        ///
        /// Parameter `device`: Device the state resources will be created on.
        ///
        /// Parameter `lossImageSize`: The size of the resulting loss image: { width, height, featureChannels }.
        /// The computed loss can either be a scalar value (in batch mode, a single
        /// value per image in a batch) or it can be one value per feature channel.
        /// Thus, the size of the loss image must either match the size of the input
        /// source image or be {1, 1, 1}, which results in a scalar value.
        ///
        /// Parameter `labelsDescriptor`: Describes the labels data. This includes:
        /// - The per-element labels data. The data must be in floating point format.
        /// - Data layout of labels data. See MPSImage.h for more information.
        /// - Size of labels data: (width, height, feature channels}.
        /// - Optionally, row bytes of labels data.
        /// - Optionally, slice bytes of labels data.
        ///
        /// Parameter `weightsDescriptor`: Describes the weights data. This includes:
        /// - The per-element weights data. The data must be in floating point format.
        /// - Data layout of weights data. See MPSImage.h for more information.
        /// - Size of weights data: (width, height, feature channels}.
        /// - Optionally, row bytes of weights data.
        /// - Optionally, slice bytes of weights data.
        /// This parameter is optional. If you are using a single weight, please use the
        /// weight property of the MPSCNNLossDescriptor object.
        #[unsafe(method(initWithDevice:lossImageSize:labelsDescriptor:weightsDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_lossImageSize_labelsDescriptor_weightsDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            loss_image_size: MTLSize,
            labels_descriptor: &MPSCNNLossDataDescriptor,
            weights_descriptor: Option<&MPSCNNLossDataDescriptor>,
        ) -> Retained<Self>;

        #[cfg(feature = "MPSImage")]
        /// Set labels (aka targets, ground truth) and weights for the MPSCNNLossLabels object.
        /// Weights are optional.
        ///
        /// The labels and weights images are retained - it is the users responsibility to make sure that they contain
        /// the right data when the loss filter is run on the device.
        ///
        /// Parameter `device`: Device the state resources will be created on.
        ///
        /// Parameter `lossImageSize`: The size of the resulting loss image: { width, height, featureChannels }.
        /// The computed loss can either be a scalar value (in batch mode, a single
        /// value per image in a batch) or it can be one value per feature channel.
        /// Thus, the size of the loss image must either match the size of the input
        /// source image or be {1, 1, 1}, which results in a scalar value.
        ///
        /// Parameter `labelsImage`: Describes the labels data.
        ///
        /// Parameter `weightsImage`: Describes the weights data.
        /// This parameter is optional. If you are using a single weight, please use the
        /// weight property of the MPSCNNLossDescriptor object.
        #[unsafe(method(initWithDevice:lossImageSize:labelsImage:weightsImage:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_lossImageSize_labelsImage_weightsImage(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            loss_image_size: MTLSize,
            labels_image: &MPSImage,
            weights_image: Option<&MPSImage>,
        ) -> Retained<Self>;

        #[cfg(feature = "MPSImage")]
        /// Loss image accessor method.
        ///
        /// Returns: An autoreleased MPSImage object, containing the loss data.
        /// The loss data is populated in the -encode call, thus the contents
        /// are undefined until you -encode the filter.
        ///
        /// In order to guarantee that the image is correctly synchronized for CPU side access,
        /// it is the application's responsibility to call the [gradientState synchronizeOnCommandBuffer:]
        /// method before accessing the data in the image.
        #[unsafe(method(lossImage))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossImage(&self) -> Retained<MPSImage>;

        #[cfg(feature = "MPSImage")]
        /// Labels image accessor method.
        ///
        /// Returns: An autoreleased MPSImage object, containing the labels data.
        /// The labels data is populated in the -initWithDevice call.
        ///
        /// In order to guarantee that the image is correctly synchronized for CPU side access,
        /// it is the application's responsibility to call the [gradientState synchronizeOnCommandBuffer:]
        /// method before accessing the data in the image.
        #[unsafe(method(labelsImage))]
        #[unsafe(method_family = none)]
        pub unsafe fn labelsImage(&self) -> Retained<MPSImage>;

        #[cfg(feature = "MPSImage")]
        /// Weights image accessor method.
        ///
        /// Returns: An autoreleased MPSImage object, containing the weights data.
        /// The weights data is populated in the -initWithDevice call.
        ///
        /// In order to guarantee that the image is correctly synchronized for CPU side access,
        /// it is the application's responsibility to call the [gradientState synchronizeOnCommandBuffer:]
        /// method before accessing the data in the image.
        #[unsafe(method(weightsImage))]
        #[unsafe(method_family = none)]
        pub unsafe fn weightsImage(&self) -> Retained<MPSImage>;
    );
}

/// Methods declared on superclass `MPSState`.
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
impl MPSCNNLossLabels {
    extern_methods!(
        /// Create a MPSState holding a temporary MTLBuffer
        ///
        /// Parameter `cmdBuf`: The command buffer against which the temporary resource is allocated
        ///
        /// Parameter `bufferSize`: The size of the buffer in bytes
        #[unsafe(method(temporaryStateWithCommandBuffer:bufferSize:))]
        #[unsafe(method_family = none)]
        pub unsafe fn temporaryStateWithCommandBuffer_bufferSize(
            cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
            buffer_size: usize,
        ) -> Retained<Self>;

        /// Create a MPSState holding a temporary MTLTexture
        ///
        /// Parameter `cmdBuf`: The command buffer against which the temporary resource is allocated
        ///
        /// Parameter `descriptor`: A descriptor for the new temporary texture
        #[unsafe(method(temporaryStateWithCommandBuffer:textureDescriptor:))]
        #[unsafe(method_family = none)]
        pub unsafe fn temporaryStateWithCommandBuffer_textureDescriptor(
            cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
            descriptor: &MTLTextureDescriptor,
        ) -> Retained<Self>;

        /// Create a new autoreleased temporary state object without underlying resource
        ///
        /// Parameter `cmdBuf`: The command buffer with which the temporary resource is associated
        #[unsafe(method(temporaryStateWithCommandBuffer:))]
        #[unsafe(method_family = none)]
        pub unsafe fn temporaryStateWithCommandBuffer(
            cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
        ) -> Retained<Self>;

        #[unsafe(method(initWithDevice:bufferSize:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_bufferSize(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            buffer_size: usize,
        ) -> Retained<Self>;

        #[unsafe(method(initWithDevice:textureDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_textureDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            descriptor: &MTLTextureDescriptor,
        ) -> Retained<Self>;

        /// Create a MPSState with a non-temporary MTLResource
        ///
        /// Parameter `resource`: A MTLBuffer or MTLTexture. May be nil.
        ///
        /// # Safety
        ///
        /// - `resource` may need to be synchronized.
        /// - `resource` may be unretained, you must ensure it is kept alive while in use.
        #[unsafe(method(initWithResource:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithResource(
            this: Allocated<Self>,
            resource: Option<&ProtocolObject<dyn MTLResource>>,
        ) -> Retained<Self>;

        /// Initialize a non-temporary state to hold a number of textures and buffers
        ///
        /// The allocation of each resource will be deferred  until it is needed.
        /// This occurs when -resource or -resourceAtIndex: is called.
        ///
        /// Parameter `resourceList`: The list of resources to create.
        #[unsafe(method(initWithDevice:resourceList:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_resourceList(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            resource_list: &MPSStateResourceList,
        ) -> Retained<Self>;

        /// Initialize a temporary state to hold a number of textures and buffers
        ///
        /// The textures occur first in sequence
        #[unsafe(method(temporaryStateWithCommandBuffer:resourceList:))]
        #[unsafe(method_family = none)]
        pub unsafe fn temporaryStateWithCommandBuffer_resourceList(
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            resource_list: &MPSStateResourceList,
        ) -> Retained<Self>;

        /// Create a state object with a list of MTLResources
        ///
        /// Because MPS prefers deferred allocation of resources
        /// your application should use -initWithTextures:bufferSizes:bufferCount:
        /// whenever possible. This method is useful for cases when the
        /// MTLResources must be initialized by the CPU.
        ///
        /// # Safety
        ///
        /// - `resources` generic may need to be synchronized.
        /// - `resources` generic may be unretained, you must ensure it is kept alive while in use.
        #[unsafe(method(initWithResources:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithResources(
            this: Allocated<Self>,
            resources: Option<&NSArray<ProtocolObject<dyn MTLResource>>>,
        ) -> Retained<Self>;
    );
}

/// Methods declared on superclass `NSObject`.
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
impl MPSCNNLossLabels {
    extern_methods!(
        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnlosslabelsbatch?language=objc)
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
pub type MPSCNNLossLabelsBatch = NSArray<MPSCNNLossLabels>;

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSCNNLossDescriptor specifies a loss filter descriptor.
    /// The same descriptor can be used to initialize both the
    /// MPSCNNLoss and the MPSNNLossGradient filters.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnlossdescriptor?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct MPSCNNLossDescriptor;
);

extern_conformance!(
    unsafe impl NSCopying for MPSCNNLossDescriptor {}
);

unsafe impl CopyingHelper for MPSCNNLossDescriptor {
    type Result = Self;
}

extern_conformance!(
    unsafe impl NSObjectProtocol for MPSCNNLossDescriptor {}
);

impl MPSCNNLossDescriptor {
    extern_methods!(
        #[cfg(feature = "MPSCNNTypes")]
        /// The type of a loss filter.
        ///
        /// This parameter specifies the type of a loss filter.
        #[unsafe(method(lossType))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossType(&self) -> MPSCNNLossType;

        #[cfg(feature = "MPSCNNTypes")]
        /// Setter for [`lossType`][Self::lossType].
        #[unsafe(method(setLossType:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setLossType(&self, loss_type: MPSCNNLossType);

        #[cfg(feature = "MPSCNNTypes")]
        /// The type of a reduction operation performed in the loss filter.
        ///
        /// This parameter specifies the type of a reduction operation
        /// performed in the loss filter.
        #[unsafe(method(reductionType))]
        #[unsafe(method_family = none)]
        pub unsafe fn reductionType(&self) -> MPSCNNReductionType;

        #[cfg(feature = "MPSCNNTypes")]
        /// Setter for [`reductionType`][Self::reductionType].
        #[unsafe(method(setReductionType:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setReductionType(&self, reduction_type: MPSCNNReductionType);

        /// If set to YES then the reduction operation is applied also across the batch-index dimension,
        /// ie. the loss value is summed over images in the batch and the result of the reduction is written
        /// on the first loss image in the batch while the other loss images will be set to zero.
        /// If set to NO, then no reductions are performed across the batch dimension and each image in the batch
        /// will contain the loss value associated with that one particular image.
        /// NOTE: If reductionType == MPSCNNReductionTypeNone, then this flag has no effect on results,
        /// that is no reductions are done in this case.
        /// NOTE: If reduceAcrossBatch is set to YES and reductionType == MPSCNNReductionTypeMean then
        /// the final forward loss value is computed by first summing over the components and then by
        /// dividing the result with: number of feature channels * width * height * number of images in the batch.
        /// The default value is NO.
        #[unsafe(method(reduceAcrossBatch))]
        #[unsafe(method_family = none)]
        pub unsafe fn reduceAcrossBatch(&self) -> bool;

        /// Setter for [`reduceAcrossBatch`][Self::reduceAcrossBatch].
        #[unsafe(method(setReduceAcrossBatch:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setReduceAcrossBatch(&self, reduce_across_batch: bool);

        /// The scale factor to apply to each element of a result.
        ///
        /// Each element of a result is multiplied by the weight value.
        /// The default value is 1.0f.
        #[unsafe(method(weight))]
        #[unsafe(method_family = none)]
        pub unsafe fn weight(&self) -> c_float;

        /// Setter for [`weight`][Self::weight].
        #[unsafe(method(setWeight:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setWeight(&self, weight: c_float);

        /// The label smoothing parameter. The default value is 0.0f.
        ///
        /// This parameter is valid only for the loss functions of the following type(s):
        /// MPSCNNLossFunctionTypeSoftmaxCrossEntropy, MPSCNNLossFunctionTypeSigmoidCrossEntropy.
        ///
        /// MPSCNNLossFunctionTypeSoftmaxCrossEntropy: given labels (ground truth), it is applied in the following way:
        /// labels = labelSmoothing > 0 ? labels * (1 - labelSmoothing) + labelSmoothing / numberOfClasses : labels
        ///
        /// MPSCNNLossFunctionTypeSigmoidCrossEntropy: given labels (ground truth), it is applied in the following way:
        /// labels = labelSmoothing > 0 ? labels * (1 - labelSmoothing) + 0.5 * labelSmoothing : labels
        #[unsafe(method(labelSmoothing))]
        #[unsafe(method_family = none)]
        pub unsafe fn labelSmoothing(&self) -> c_float;

        /// Setter for [`labelSmoothing`][Self::labelSmoothing].
        #[unsafe(method(setLabelSmoothing:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setLabelSmoothing(&self, label_smoothing: c_float);

        /// The number of classes parameter. The default value is 1.
        ///
        /// This parameter is valid only for the loss functions of the following type(s):
        /// MPSCNNLossFunctionTypeSoftmaxCrossEntropy.
        ///
        /// Given labels (ground truth), it is applied in the following way:
        /// labels = labelSmoothing > 0 ? labels * (1 - labelSmoothing) + labelSmoothing / numberOfClasses : labels
        #[unsafe(method(numberOfClasses))]
        #[unsafe(method_family = none)]
        pub unsafe fn numberOfClasses(&self) -> NSUInteger;

        /// Setter for [`numberOfClasses`][Self::numberOfClasses].
        #[unsafe(method(setNumberOfClasses:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setNumberOfClasses(&self, number_of_classes: NSUInteger);

        /// The epsilon parameter. The default value is 1e-7.
        ///
        /// This parameter is valid only for the loss functions of the following type(s):
        /// MPSCNNLossTypeLog.
        ///
        /// Given predictions and labels (ground truth), it is applied in the following way:
        /// -(labels * log(predictions + epsilon)) - ((1 - labels) * log(1 - predictions + epsilon))
        #[unsafe(method(epsilon))]
        #[unsafe(method_family = none)]
        pub unsafe fn epsilon(&self) -> c_float;

        /// Setter for [`epsilon`][Self::epsilon].
        #[unsafe(method(setEpsilon:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setEpsilon(&self, epsilon: c_float);

        /// The delta parameter. The default value is 1.0f.
        ///
        /// This parameter is valid only for the loss functions of the following type(s):
        /// MPSCNNLossTypeHuber.
        ///
        /// Given predictions and labels (ground truth), it is applied in the following way:
        /// if (|predictions - labels|
        /// <
        /// = delta, loss = 0.5f * predictions^2
        /// if (|predictions - labels| >  delta, loss = 0.5 * delta^2 + delta * (|predictions - labels| - delta)
        #[unsafe(method(delta))]
        #[unsafe(method_family = none)]
        pub unsafe fn delta(&self) -> c_float;

        /// Setter for [`delta`][Self::delta].
        #[unsafe(method(setDelta:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setDelta(&self, delta: c_float);

        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[cfg(feature = "MPSCNNTypes")]
        /// Make a descriptor for a MPSCNNLoss or MPSNNLossGradient object.
        ///
        /// Parameter `lossType`: The type of a loss filter.
        ///
        /// Parameter `reductionType`: The type of a reduction operation to apply.
        /// This argument is ignored in the MPSNNLossGradient filter.
        ///
        /// Returns: A valid MPSCNNLossDescriptor object or nil, if failure.
        #[unsafe(method(cnnLossDescriptorWithType:reductionType:))]
        #[unsafe(method_family = none)]
        pub unsafe fn cnnLossDescriptorWithType_reductionType(
            loss_type: MPSCNNLossType,
            reduction_type: MPSCNNReductionType,
        ) -> Retained<MPSCNNLossDescriptor>;
    );
}

/// Methods declared on superclass `NSObject`.
impl MPSCNNLossDescriptor {
    extern_methods!(
        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSCNNLoss filter is only used for training. This filter performs both the forward and
    /// backward pass computations. Specifically, it computes the loss between the input (predictions)
    /// and target data (labels) and the loss gradient. The loss value can be a 1 x 1 x 1 image containing
    /// a scalar loss value or an image (of the same size as the input source image) with per feature
    /// channel losses. The loss value is used to determine whether to continue the training operation or
    /// to terminate it, once satisfactory results are achieved. The loss gradient is the first gradient
    /// computed for the backward pass and serves as input to the next gradient filter (in the backward
    /// direction).
    ///
    /// The MPSCNNLoss filter is created with a MPSCNNLossDescriptor describing the type of a loss filter
    /// and the type of a reduction to use for computing the overall loss.
    ///
    /// The MPSCNNLoss filter takes the output of the inference pass (predictions) as input. It also
    /// requires the target data (labels) and optionally, weights for the labels. If per-label weights
    /// are not supplied, there is an option to use a single weight value by setting the 'weight' properly
    /// on the MPSCNNLossDescriptor object. The labels and optional weights need to be supplied by the user
    /// using the MPSCNNLossLabels object. The labels and weights are described via the MPSCNNLossDataDescriptor
    /// objects, which are in turn used to initialize the MPSCNNLossLabels object.
    ///
    /// If the specified reduction operation is MPSCNNReductionTypeNone, the destinationImage should be
    /// at least as large as the specified clipRect. The destinationImage will then contain per-element
    /// losses. Otherse, a reduction operation will be performed, according to the specified reduction
    /// type, and the filter will return a scalar value containing the overall loss. For more information
    /// on the available reduction types, see MPSCNNTypes.h. Also see MPSCNNLossDescriptor for the
    /// description of optional parameters.
    ///
    /// Here is a code example:
    ///
    /// // Setup
    /// MPSCNNLossDataDescriptor* labelsDescriptor =
    /// [MPSCNNLossDataDescriptor cnnLossDataDescriptorWithData: labelsData
    /// layout: MPSDataLayoutHeightxWidthxFeatureChannels
    /// size: labelsDataSize];
    /// MPSCNNLossLabels* labels = [[MPSCNNLossLabels alloc] initWithDevice: device
    /// labelsDescriptor: labelsDescriptor];
    /// MPSCNNLossDescriptor *lossDescriptor =
    /// [MPSCNNLossDescriptor cnnLossDescriptorWithType: (MPSCNNLossType)MPSCNNLossTypeMeanAbsoluteError
    /// reductionType: (MPSCNNReductionType)MPSCNNReductionTypeSum];
    /// MPSCNNLoss* lossFilter = [[MPSCNNLoss alloc] initWithDevice: device lossDescriptor: lossDescriptor];
    ///
    /// // Encode loss filter.
    /// // The sourceImage is the output of a previous layer, for example, the SoftMax layer. The lossGradientsImage
    /// // is the sourceGradient input image to the first gradient layer (in the backward direction), for example,
    /// // the SoftMax gradient filter.
    /// [lossFilter encodeToCommandBuffer: commandBuffer sourceImage: sourceImage
    /// labels: labels
    /// destinationImage: lossGradientsImage];
    ///
    /// // In order to guarantee that the loss image data is correctly synchronized for CPU side access,
    /// // it is the application's responsibility to call the [labels synchronizeOnCommandBuffer:]
    /// // method before accessing the loss image data.
    /// [labels synchronizeOnCommandBuffer:commandBuffer];
    /// MPSImage* lossImage = [labels lossImage];
    ///
    /// For predictions (y) and labels (t), the available loss filter types are the following:
    ///
    /// Mean Absolute Error loss filter. This filter measures the absolute error of the element-wise
    /// difference between the predictions and labels.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = |y - t|
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// Mean Squared Error loss filter. This filter measures the squared error of the element-wise
    /// difference between the predictions and labels.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = (y - t)^2
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// SoftMax Cross Entropy loss filter. This loss filter is applied element-wise.
    /// This loss filter combines the LogSoftMax and Negative Log Likelihood operations in a
    /// single filter. It is useful for training a classification problem with multiple classes.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = -t * LogSoftMax(y)
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    /// If reductionType is MPSCNNReductionTypeMean, the accumulated
    /// loss value is divided by width * height instead of
    /// width * height * featureChannels.
    ///
    /// Sigmoid Cross Entropy loss filter. This loss filter is applied element-wise.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = max(y, 0) - y * t + log(1 + exp(-|y|))
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// Categorical Cross Entropy loss filter. This loss filter is applied element-wise.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = -t * log(y)
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// Hinge loss filter. This loss filter is applied element-wise.
    /// The labels are expected to be 0.0 or 1.0.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = max(1 - (t * y), 0.0f)
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// Huber loss filter. This loss filter is applied element-wise.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          if (|y - t|
    /// <
    /// = delta, losses = 0.5 * y^2
    /// if (|y - t| >  delta, losses = 0.5 * delta^2 + delta * (|y - t| - delta)
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// Cosine Distance loss filter. This loss filter is applied element-wise.
    /// The only valid reduction type for this loss filter is MPSCNNReductionTypeSum.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          loss = 1 - reduce_sum(y * t)
    /// Compute overall loss:    weighted_loss = weight * loss
    ///
    /// Log loss filter. This loss filter is applied element-wise.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = -(t * log(y + epsilon)) - ((1 - t) * log(1 - y + epsilon))
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// Kullback-Leibler Divergence loss filter. This loss filter is applied element-wise.
    /// The input (predictions) is expected to contain log-probabilities.
    /// This loss function is computed according to the following formulas:
    /// Compute losses:          losses = t * (log(t) - y)
    /// Compute weighted losses: weighted_losses = weight(s) * losses
    /// Compute overall loss:    loss = reduce(weighted_losses, reductionType)
    ///
    /// For predictions (y) and labels (t), the loss gradient for each available loss filter type
    /// is computed as follows:
    ///
    /// Mean Absolute Error loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = (y - t) / |y - t|
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Mean Squared Error loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = 2 * (y - t)
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// SoftMax Cross Entropy loss.
    /// The loss gradient is computed according to the following formulas:
    /// First, apply the same label smoothing as in the MPSCNNLoss filter.
    /// Compute gradient:          d/dy = y - t
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Sigmoid Cross Entropy loss.
    /// The loss gradient is computed according to the following formulas:
    /// First, apply the same label smoothing as in the MPSCNNLoss filter.
    /// Compute gradient:          d/dy = (1 / (1 + exp(-y)) - t
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Categorical Cross Entropy loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = -t / y
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Hinge loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = ((1 + ((1 - (2 * t)) * y)) > 0) ? 1 - (2 * t) : 0
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Huber loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = |y - t| > delta ? delta : y - t
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Cosine Distance loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = -t
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Log loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = (-2 * epsilon * t - t + y + epsilon) / (y * (1 - y) + epsilon * (epsilon + 1))
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// Kullback-Leibler Divergence loss.
    /// The loss gradient is computed according to the following formulas:
    /// Compute gradient:          d/dy = -t / y
    /// Compute weighted gradient: weighted_gradient = weight(s) * gradient
    ///
    /// The number of output feature channels remains the same as the number of input feature
    /// channels.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnloss?language=objc)
    #[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    #[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
    pub struct MPSCNNLoss;
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCoding for MPSCNNLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCopying for MPSCNNLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNLoss {
    type Result = Self;
}

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSObjectProtocol for MPSCNNLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSSecureCoding for MPSCNNLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNLoss {
    extern_methods!(
        #[cfg(feature = "MPSCNNTypes")]
        /// See MPSCNNLossDescriptor for information about the following properties.
        #[unsafe(method(lossType))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossType(&self) -> MPSCNNLossType;

        #[cfg(feature = "MPSCNNTypes")]
        #[unsafe(method(reductionType))]
        #[unsafe(method_family = none)]
        pub unsafe fn reductionType(&self) -> MPSCNNReductionType;

        #[unsafe(method(weight))]
        #[unsafe(method_family = none)]
        pub unsafe fn weight(&self) -> c_float;

        #[unsafe(method(labelSmoothing))]
        #[unsafe(method_family = none)]
        pub unsafe fn labelSmoothing(&self) -> c_float;

        #[unsafe(method(numberOfClasses))]
        #[unsafe(method_family = none)]
        pub unsafe fn numberOfClasses(&self) -> NSUInteger;

        #[unsafe(method(epsilon))]
        #[unsafe(method_family = none)]
        pub unsafe fn epsilon(&self) -> c_float;

        #[unsafe(method(delta))]
        #[unsafe(method_family = none)]
        pub unsafe fn delta(&self) -> c_float;

        #[unsafe(method(reduceAcrossBatch))]
        #[unsafe(method_family = none)]
        pub unsafe fn reduceAcrossBatch(&self) -> bool;

        #[unsafe(method(initWithDevice:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Retained<Self>;

        /// Initialize the loss filter with a loss descriptor.
        ///
        /// Parameter `device`: The device the filter will run on.
        ///
        /// Parameter `lossDescriptor`: The loss descriptor.
        ///
        /// Returns: A valid MPSCNNLoss object or nil, if failure.
        #[unsafe(method(initWithDevice:lossDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_lossDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            loss_descriptor: &MPSCNNLossDescriptor,
        ) -> Retained<Self>;

        /// <NSSecureCoding
        /// > support
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:device:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder_device(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Option<Retained<Self>>;

        #[cfg(all(feature = "MPSImage", feature = "MPSState"))]
        /// Encode a MPSCNNLoss filter and return a gradient in the destinationImage.
        ///
        /// This filter consumes the output of a previous layer, for example, the SoftMax layer containing
        /// predictions, and the MPSCNNLossLabels object containing the target data (labels) and optionally,
        /// weights for the labels. The destinationImage contains the computed gradient for the loss layer.
        /// It serves as a source gradient input image to the first gradient layer (in the backward direction),
        /// in our example, the SoftMax gradient layer.
        ///
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode.
        ///
        /// Parameter `sourceImage`: The source image from the previous filter in the graph (in the inference direction).
        ///
        /// Parameter `labels`: The object containing the target data (labels) and optionally, weights for the labels.
        ///
        /// Parameter `destinationImage`: The MPSImage into which to write the gradient result.
        #[unsafe(method(encodeToCommandBuffer:sourceImage:labels:destinationImage:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeToCommandBuffer_sourceImage_labels_destinationImage(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImage,
            labels: &MPSCNNLossLabels,
            destination_image: &MPSImage,
        );

        #[cfg(all(feature = "MPSImage", feature = "MPSState"))]
        /// Encode a MPSCNNLoss filter and return a gradient.
        ///
        /// This -encode call is similar to the encodeToCommandBuffer:sourceImage:labels:destinationImage: above,
        /// except that it creates and returns the MPSImage with the loss gradient result.
        ///
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode.
        ///
        /// Parameter `sourceImage`: The source image from the previous filter in the graph (in the inference direction).
        ///
        /// Parameter `labels`: The object containing the target data (labels) and optionally, weights for the labels.
        ///
        /// Returns: The MPSImage containing the gradient result.
        #[unsafe(method(encodeToCommandBuffer:sourceImage:labels:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeToCommandBuffer_sourceImage_labels(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImage,
            labels: &MPSCNNLossLabels,
        ) -> Retained<MPSImage>;

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        #[unsafe(method(encodeBatchToCommandBuffer:sourceImages:labels:destinationImages:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceImages_labels_destinationImages(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImageBatch,
            labels: &MPSCNNLossLabelsBatch,
            destination_image: &MPSImageBatch,
        );

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        #[unsafe(method(encodeBatchToCommandBuffer:sourceImages:labels:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceImages_labels(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImageBatch,
            labels: &MPSCNNLossLabelsBatch,
        ) -> Retained<MPSImageBatch>;
    );
}

/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNLoss {
    extern_methods!(
        /// Called by NSCoder to decode MPSKernels
        ///
        /// This isn't the right interface to decode a MPSKernel, but
        /// it is the one that NSCoder uses. To enable your NSCoder
        /// (e.g. NSKeyedUnarchiver) to set which device to use
        /// extend the object to adopt the MPSDeviceProvider
        /// protocol. Otherwise, the Metal system default device
        /// will be used.
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
        ) -> Option<Retained<Self>>;
    );
}

/// Methods declared on superclass `NSObject`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNLoss {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSCNNYOLOLossDescriptor specifies a loss filter descriptor
    /// that is used to create a MPSCNNLoss filter. The MPSCNNYOLOLoss is a filter that
    /// has been specialized for object detection tasks and follows a specific layout
    /// for the feature-channels of the input, output, weight and label data.
    ///
    /// The layout of the data within the feature-channels is as follows:
    ///
    /// Each anchorbox uses ( 2+2+1 + numberOfClasses = 5 + numberOfClasses ) feature channels.
    ///
    /// Therefore the total number of feature channels used is: (5 + numberOfClasses) * numberOfAnchorBoxes.
    /// The first feature channel for anchorbox index 'anchorIdx' is at fcIndex = (5 + numberOfClasses) * anchorIdx,
    /// and the feature channels within each anchorbox are stored in the layout: 'XYWHCFFFFFF...', where (XY) are
    /// the so-called raw x and y coordinates of the bounding box within each gridcell and (WH) are the corresponding
    /// width and height. 'C' signifies a confidence for having an object in the cell and FFFFF... are the feature channel
    /// values for each class of object to be classified in the object detector.
    ///
    /// The YOLO-loss filter works by operating mostly independently on each anchorbox:
    /// *   The XY-channels of the inputs are first transformed to relative XY-values by applying the sigmoid-neuron on them,
    /// after which they are passed through the loss function defined by
    /// XYLossDescriptor,which is typically chosen
    /// to be the
    /// MPSCNNLossTypeMeanSquaredErrortype loss function.
    /// *   The WH-channels contain the raw width and height of the bounding box and they are operated with the
    /// loss function defined by
    /// WHLossDescriptor,which is typically of type
    /// MPSCNNLossTypeHuber.*   The C-channel contains the confidence value of having an object in the bounding box and it is operated
    /// by the loss function defined by
    /// confidenceLossDescriptor,which is typically chosen to be
    /// MPSCNNLossTypeSigmoidCrossEntropy.*   The FFFFF... (number of channels is number of classes) channels contains the raw feature channels for
    /// object classes, used to identify which objects are the most probable ones in the bounding box and
    /// these channels are passed through the loss function defined by
    /// classesLossDescriptor,which in
    /// typical cases is of the type
    /// MPSCNNLossTypeSoftMaxCrossEntropy.
    /// For details on how to set up the label values and anchorboxes see https://arxiv.org/abs/1612.08242
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnyololossdescriptor?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct MPSCNNYOLOLossDescriptor;
);

extern_conformance!(
    unsafe impl NSCopying for MPSCNNYOLOLossDescriptor {}
);

unsafe impl CopyingHelper for MPSCNNYOLOLossDescriptor {
    type Result = Self;
}

extern_conformance!(
    unsafe impl NSObjectProtocol for MPSCNNYOLOLossDescriptor {}
);

impl MPSCNNYOLOLossDescriptor {
    extern_methods!(
        /// The type of a loss filter.
        ///
        /// This parameter specifies the type of a loss filter.
        #[unsafe(method(XYLossDescriptor))]
        #[unsafe(method_family = none)]
        pub unsafe fn XYLossDescriptor(&self) -> Retained<MPSCNNLossDescriptor>;

        /// Setter for [`XYLossDescriptor`][Self::XYLossDescriptor].
        #[unsafe(method(setXYLossDescriptor:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setXYLossDescriptor(&self, xy_loss_descriptor: &MPSCNNLossDescriptor);

        /// The type of a loss filter.
        ///
        /// This parameter specifies the type of a loss filter.
        #[unsafe(method(WHLossDescriptor))]
        #[unsafe(method_family = none)]
        pub unsafe fn WHLossDescriptor(&self) -> Retained<MPSCNNLossDescriptor>;

        /// Setter for [`WHLossDescriptor`][Self::WHLossDescriptor].
        #[unsafe(method(setWHLossDescriptor:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setWHLossDescriptor(&self, wh_loss_descriptor: &MPSCNNLossDescriptor);

        /// The type of a loss filter.
        ///
        /// This parameter specifies the type of a loss filter.
        #[unsafe(method(confidenceLossDescriptor))]
        #[unsafe(method_family = none)]
        pub unsafe fn confidenceLossDescriptor(&self) -> Retained<MPSCNNLossDescriptor>;

        /// Setter for [`confidenceLossDescriptor`][Self::confidenceLossDescriptor].
        #[unsafe(method(setConfidenceLossDescriptor:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setConfidenceLossDescriptor(
            &self,
            confidence_loss_descriptor: &MPSCNNLossDescriptor,
        );

        /// The type of a loss filter.
        ///
        /// This parameter specifies the type of a loss filter.
        #[unsafe(method(classesLossDescriptor))]
        #[unsafe(method_family = none)]
        pub unsafe fn classesLossDescriptor(&self) -> Retained<MPSCNNLossDescriptor>;

        /// Setter for [`classesLossDescriptor`][Self::classesLossDescriptor].
        #[unsafe(method(setClassesLossDescriptor:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setClassesLossDescriptor(
            &self,
            classes_loss_descriptor: &MPSCNNLossDescriptor,
        );

        #[cfg(feature = "MPSCNNTypes")]
        /// ReductionType shared accross all losses (so they may generate same sized output)
        #[unsafe(method(reductionType))]
        #[unsafe(method_family = none)]
        pub unsafe fn reductionType(&self) -> MPSCNNReductionType;

        #[cfg(feature = "MPSCNNTypes")]
        /// Setter for [`reductionType`][Self::reductionType].
        #[unsafe(method(setReductionType:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setReductionType(&self, reduction_type: MPSCNNReductionType);

        /// If set to YES then the reduction operation is applied also across the batch-index dimension,
        /// ie. the loss value is summed over images in the batch and the result of the reduction is written
        /// on the first loss image in the batch while the other loss images will be set to zero.
        /// If set to NO, then no reductions are performed across the batch dimension and each image in the batch
        /// will contain the loss value associated with that one particular image.
        /// NOTE: If reductionType == MPSCNNReductionTypeNone, then this flag has no effect on results,
        /// that is no reductions are done in this case.
        /// NOTE: If reduceAcrossBatch is set to YES and reductionType == MPSCNNReductionTypeMean then
        /// the final forward loss value is computed by first summing over the components and then by
        /// dividing the result with: number of feature channels * width * height * number of images in the batch.
        /// The default value is NO.
        #[unsafe(method(reduceAcrossBatch))]
        #[unsafe(method_family = none)]
        pub unsafe fn reduceAcrossBatch(&self) -> bool;

        /// Setter for [`reduceAcrossBatch`][Self::reduceAcrossBatch].
        #[unsafe(method(setReduceAcrossBatch:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setReduceAcrossBatch(&self, reduce_across_batch: bool);

        /// Rescore pertains to multiplying the confidence groundTruth with IOU (intersection over union)
        /// of predicted bounding box and the groundTruth boundingBox. Default is YES
        #[unsafe(method(rescore))]
        #[unsafe(method_family = none)]
        pub unsafe fn rescore(&self) -> bool;

        /// Setter for [`rescore`][Self::rescore].
        #[unsafe(method(setRescore:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setRescore(&self, rescore: bool);

        /// scale factor for XY loss and loss gradient default is 10.0
        #[unsafe(method(scaleXY))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleXY(&self) -> c_float;

        /// Setter for [`scaleXY`][Self::scaleXY].
        #[unsafe(method(setScaleXY:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setScaleXY(&self, scale_xy: c_float);

        /// scale factor for WH loss and loss gradient default is 10.0
        #[unsafe(method(scaleWH))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleWH(&self) -> c_float;

        /// Setter for [`scaleWH`][Self::scaleWH].
        #[unsafe(method(setScaleWH:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setScaleWH(&self, scale_wh: c_float);

        /// scale factor for no object confidence loss and loss gradient default is 5.0
        #[unsafe(method(scaleNoObject))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleNoObject(&self) -> c_float;

        /// Setter for [`scaleNoObject`][Self::scaleNoObject].
        #[unsafe(method(setScaleNoObject:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setScaleNoObject(&self, scale_no_object: c_float);

        /// scale factor for no object confidence loss and loss gradient default is 100.0
        #[unsafe(method(scaleObject))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleObject(&self) -> c_float;

        /// Setter for [`scaleObject`][Self::scaleObject].
        #[unsafe(method(setScaleObject:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setScaleObject(&self, scale_object: c_float);

        /// scale factor for no object classes loss and loss gradient default is 2.0
        #[unsafe(method(scaleClass))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleClass(&self) -> c_float;

        /// Setter for [`scaleClass`][Self::scaleClass].
        #[unsafe(method(setScaleClass:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setScaleClass(&self, scale_class: c_float);

        /// If the prediction IOU with groundTruth is higher than this
        /// value we consider it a confident object presence, default is 0.7
        #[unsafe(method(minIOUForObjectPresence))]
        #[unsafe(method_family = none)]
        pub unsafe fn minIOUForObjectPresence(&self) -> c_float;

        /// Setter for [`minIOUForObjectPresence`][Self::minIOUForObjectPresence].
        #[unsafe(method(setMinIOUForObjectPresence:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setMinIOUForObjectPresence(&self, min_iou_for_object_presence: c_float);

        /// If the prediction IOU with groundTruth is lower than this
        /// value we consider it a confident object absence, default is 0.3
        #[unsafe(method(maxIOUForObjectAbsence))]
        #[unsafe(method_family = none)]
        pub unsafe fn maxIOUForObjectAbsence(&self) -> c_float;

        /// Setter for [`maxIOUForObjectAbsence`][Self::maxIOUForObjectAbsence].
        #[unsafe(method(setMaxIOUForObjectAbsence:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setMaxIOUForObjectAbsence(&self, max_iou_for_object_absence: c_float);

        /// number of anchor boxes used to detect object per grid cell
        #[unsafe(method(numberOfAnchorBoxes))]
        #[unsafe(method_family = none)]
        pub unsafe fn numberOfAnchorBoxes(&self) -> NSUInteger;

        /// Setter for [`numberOfAnchorBoxes`][Self::numberOfAnchorBoxes].
        #[unsafe(method(setNumberOfAnchorBoxes:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setNumberOfAnchorBoxes(&self, number_of_anchor_boxes: NSUInteger);

        /// NSData containing the width and height for numberOfAnchorBoxes anchor boxes
        /// This NSData should have 2 float values per anchor box which represent the width
        /// and height of the anchor box.
        ///
        /// ```text
        ///               typedef struct anchorBox{
        ///                   float width;
        ///                   float height;
        ///               }anchorBox;
        ///
        ///
        ///               anchorBox_t gAnchorBoxes[MAX_NUM_ANCHOR_BOXES] = {
        ///                   {.width = 1.f, .height = 2.f},
        ///                   {.width = 1.f, .height = 1.f},
        ///                   {.width = 2.f, .height = 1.f},
        ///               };
        ///               NSData* labelsInputData = [NSData dataWithBytes: gAnchorBoxes length: MAX_NUM_ANCHOR_BOXES * sizeof(anchorBox)];
        /// ```
        #[unsafe(method(anchorBoxes))]
        #[unsafe(method_family = none)]
        pub unsafe fn anchorBoxes(&self) -> Retained<NSData>;

        /// Setter for [`anchorBoxes`][Self::anchorBoxes].
        #[unsafe(method(setAnchorBoxes:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setAnchorBoxes(&self, anchor_boxes: &NSData);

        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[cfg(feature = "MPSCNNTypes")]
        /// Make a descriptor for a MPSCNNYOLOLoss object.
        ///
        /// Parameter `XYLossType`: The type of spatial position loss filter.
        ///
        /// Parameter `WHLossType`: The type of spatial size loss filter.
        ///
        /// Parameter `confidenceLossType`: The type of confidence filter.
        ///
        /// Parameter `classesLossType`: The type of classes filter.
        ///
        /// Parameter `reductionType`: The type of a reduction operation to apply.
        ///
        /// Parameter `anchorBoxes`: This is an NSData which has an array of anchorBoxes defined as a struct{ float width; float height; };
        ///
        /// Returns: A valid MPSCNNYOLOLossDescriptor object or nil, if failure.
        #[unsafe(method(cnnLossDescriptorWithXYLossType:WHLossType:confidenceLossType:classesLossType:reductionType:anchorBoxes:numberOfAnchorBoxes:))]
        #[unsafe(method_family = none)]
        pub unsafe fn cnnLossDescriptorWithXYLossType_WHLossType_confidenceLossType_classesLossType_reductionType_anchorBoxes_numberOfAnchorBoxes(
            xy_loss_type: MPSCNNLossType,
            wh_loss_type: MPSCNNLossType,
            confidence_loss_type: MPSCNNLossType,
            classes_loss_type: MPSCNNLossType,
            reduction_type: MPSCNNReductionType,
            anchor_boxes: &NSData,
            number_of_anchor_boxes: NSUInteger,
        ) -> Retained<MPSCNNYOLOLossDescriptor>;
    );
}

/// Methods declared on superclass `NSObject`.
impl MPSCNNYOLOLossDescriptor {
    extern_methods!(
        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnyololoss?language=objc)
    #[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    #[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
    pub struct MPSCNNYOLOLoss;
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCoding for MPSCNNYOLOLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCopying for MPSCNNYOLOLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNYOLOLoss {
    type Result = Self;
}

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSObjectProtocol for MPSCNNYOLOLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSSecureCoding for MPSCNNYOLOLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNYOLOLoss {
    extern_methods!(
        /// loss filter for prediction of bounding box position
        #[unsafe(method(lossXY))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossXY(&self) -> Retained<MPSCNNLoss>;

        /// loss filter for prediction of bounding box size
        #[unsafe(method(lossWH))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossWH(&self) -> Retained<MPSCNNLoss>;

        /// loss filter for prediction of bounding box probability of presence of object
        #[unsafe(method(lossConfidence))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossConfidence(&self) -> Retained<MPSCNNLoss>;

        /// loss filter for prediction of bounding box predicted class of the detected object
        #[unsafe(method(lossClasses))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossClasses(&self) -> Retained<MPSCNNLoss>;

        /// See MPSCNNYOLOLossDescriptor for information about the following properties.
        #[unsafe(method(scaleXY))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleXY(&self) -> c_float;

        #[unsafe(method(scaleWH))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleWH(&self) -> c_float;

        #[unsafe(method(scaleNoObject))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleNoObject(&self) -> c_float;

        #[unsafe(method(scaleObject))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleObject(&self) -> c_float;

        #[unsafe(method(scaleClass))]
        #[unsafe(method_family = none)]
        pub unsafe fn scaleClass(&self) -> c_float;

        #[unsafe(method(minIOUForObjectPresence))]
        #[unsafe(method_family = none)]
        pub unsafe fn minIOUForObjectPresence(&self) -> c_float;

        #[unsafe(method(maxIOUForObjectAbsence))]
        #[unsafe(method_family = none)]
        pub unsafe fn maxIOUForObjectAbsence(&self) -> c_float;

        #[cfg(feature = "MPSCNNTypes")]
        #[unsafe(method(reductionType))]
        #[unsafe(method_family = none)]
        pub unsafe fn reductionType(&self) -> MPSCNNReductionType;

        #[unsafe(method(numberOfAnchorBoxes))]
        #[unsafe(method_family = none)]
        pub unsafe fn numberOfAnchorBoxes(&self) -> NSUInteger;

        #[unsafe(method(anchorBoxes))]
        #[unsafe(method_family = none)]
        pub unsafe fn anchorBoxes(&self) -> Retained<NSData>;

        #[unsafe(method(reduceAcrossBatch))]
        #[unsafe(method_family = none)]
        pub unsafe fn reduceAcrossBatch(&self) -> bool;

        #[unsafe(method(initWithDevice:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Retained<Self>;

        /// Initialize the loss filter with a loss descriptor.
        ///
        /// Parameter `device`: The device the filter will run on.
        ///
        /// Parameter `lossDescriptor`: The loss descriptor.
        ///
        /// Returns: A valid MPSCNNLoss object or nil, if failure.
        #[unsafe(method(initWithDevice:lossDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_lossDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            loss_descriptor: &MPSCNNYOLOLossDescriptor,
        ) -> Retained<Self>;

        /// <NSSecureCoding
        /// > support
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:device:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder_device(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Option<Retained<Self>>;

        #[cfg(all(feature = "MPSImage", feature = "MPSState"))]
        /// Encode a MPSCNNYOLOLoss filter and return a gradient in the destinationImage.
        ///
        /// This filter consumes the output of a previous layer and the MPSCNNLossLabels object containing
        /// the target data (labels) and optionally, weights for the labels.
        /// The destinationImage contains the computed gradient for the loss layer.
        /// It serves as a source gradient input image to the first gradient layer (in the backward direction).
        /// For information on the data-layout see
        /// MPSCNNYOLOLossDescriptor.
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode.
        ///
        /// Parameter `sourceImage`: The source image from the previous filter in the graph (in the inference direction).
        ///
        /// Parameter `labels`: The object containing the target data (labels) and optionally, weights for the labels.
        ///
        /// Parameter `destinationImage`: The MPSImage into which to write the gradient result.
        #[unsafe(method(encodeToCommandBuffer:sourceImage:labels:destinationImage:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeToCommandBuffer_sourceImage_labels_destinationImage(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImage,
            labels: &MPSCNNLossLabels,
            destination_image: &MPSImage,
        );

        #[cfg(all(feature = "MPSImage", feature = "MPSState"))]
        /// Encode a MPSCNNLoss filter and return a gradient.
        ///
        /// This -encode call is similar to the encodeToCommandBuffer:sourceImage:labels:destinationImage: above,
        /// except that it creates and returns the MPSImage with the loss gradient result.
        ///
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode.
        ///
        /// Parameter `sourceImage`: The source image from the previous filter in the graph (in the inference direction).
        ///
        /// Parameter `labels`: The object containing the target data (labels) and optionally, weights for the labels.
        ///
        /// Returns: The MPSImage containing the gradient result.
        #[unsafe(method(encodeToCommandBuffer:sourceImage:labels:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeToCommandBuffer_sourceImage_labels(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImage,
            labels: &MPSCNNLossLabels,
        ) -> Retained<MPSImage>;

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        #[unsafe(method(encodeBatchToCommandBuffer:sourceImages:labels:destinationImages:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceImages_labels_destinationImages(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImageBatch,
            labels: &MPSCNNLossLabelsBatch,
            destination_image: &MPSImageBatch,
        );

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        #[unsafe(method(encodeBatchToCommandBuffer:sourceImages:labels:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceImages_labels(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_image: &MPSImageBatch,
            labels: &MPSCNNLossLabelsBatch,
        ) -> Retained<MPSImageBatch>;
    );
}

/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNYOLOLoss {
    extern_methods!(
        /// Called by NSCoder to decode MPSKernels
        ///
        /// This isn't the right interface to decode a MPSKernel, but
        /// it is the one that NSCoder uses. To enable your NSCoder
        /// (e.g. NSKeyedUnarchiver) to set which device to use
        /// extend the object to adopt the MPSDeviceProvider
        /// protocol. Otherwise, the Metal system default device
        /// will be used.
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
        ) -> Option<Retained<Self>>;
    );
}

/// Methods declared on superclass `NSObject`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNYOLOLoss {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSNNForwardLoss filter specifies a version of the loss filter which separates the forward
    /// computation from the gradient computation. In order to compute gradients for the loss filter
    /// use
    /// MPSNNLossGradientfilter and in order to start the gradient computation of an arbitrary
    /// image use the
    /// MPSNNInitialGradientfilter.
    /// NOTE: This filter does not support non-default offset or cliprects and setting them to other
    /// than default values will result in undefined results.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsnnforwardloss?language=objc)
    #[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    #[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
    pub struct MPSNNForwardLoss;
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCoding for MPSNNForwardLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCopying for MPSNNForwardLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSNNForwardLoss {
    type Result = Self;
}

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSObjectProtocol for MPSNNForwardLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSSecureCoding for MPSNNForwardLoss {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNForwardLoss {
    extern_methods!(
        #[cfg(feature = "MPSCNNTypes")]
        /// See MPSCNNLossDescriptor for information about the following properties.
        #[unsafe(method(lossType))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossType(&self) -> MPSCNNLossType;

        #[cfg(feature = "MPSCNNTypes")]
        #[unsafe(method(reductionType))]
        #[unsafe(method_family = none)]
        pub unsafe fn reductionType(&self) -> MPSCNNReductionType;

        #[unsafe(method(reduceAcrossBatch))]
        #[unsafe(method_family = none)]
        pub unsafe fn reduceAcrossBatch(&self) -> bool;

        #[unsafe(method(numberOfClasses))]
        #[unsafe(method_family = none)]
        pub unsafe fn numberOfClasses(&self) -> NSUInteger;

        #[unsafe(method(weight))]
        #[unsafe(method_family = none)]
        pub unsafe fn weight(&self) -> c_float;

        /// Setter for [`weight`][Self::weight].
        #[unsafe(method(setWeight:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setWeight(&self, weight: c_float);

        #[unsafe(method(labelSmoothing))]
        #[unsafe(method_family = none)]
        pub unsafe fn labelSmoothing(&self) -> c_float;

        /// Setter for [`labelSmoothing`][Self::labelSmoothing].
        #[unsafe(method(setLabelSmoothing:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setLabelSmoothing(&self, label_smoothing: c_float);

        #[unsafe(method(epsilon))]
        #[unsafe(method_family = none)]
        pub unsafe fn epsilon(&self) -> c_float;

        /// Setter for [`epsilon`][Self::epsilon].
        #[unsafe(method(setEpsilon:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setEpsilon(&self, epsilon: c_float);

        #[unsafe(method(delta))]
        #[unsafe(method_family = none)]
        pub unsafe fn delta(&self) -> c_float;

        /// Setter for [`delta`][Self::delta].
        #[unsafe(method(setDelta:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setDelta(&self, delta: c_float);

        #[unsafe(method(initWithDevice:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Retained<Self>;

        /// Initialize the loss forward pass filter with a loss descriptor.
        ///
        /// Parameter `device`: The device the filter will run on.
        ///
        /// Parameter `lossDescriptor`: The loss descriptor.
        ///
        /// Returns: A valid MPSNNForwardLoss object or nil, if failure.
        #[unsafe(method(initWithDevice:lossDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_lossDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            loss_descriptor: &MPSCNNLossDescriptor,
        ) -> Retained<Self>;

        /// <NSSecureCoding
        /// > support
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:device:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder_device(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Option<Retained<Self>>;

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        /// Encode a MPSNNForwardLoss filter and return the result in the destinationImage.
        ///
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode.
        ///
        /// Parameter `sourceImages`: The source images that contains the network prediction (logits).
        ///
        /// Parameter `labels`: The source images that contains the labels (targets).
        ///
        /// Parameter `weights`: The object containing weights for the labels. Optional.
        ///
        /// Parameter `destinationStates`: Optional gradient state - carries dynamical property values to the gradient pass
        /// (weight, labelSmoothing, epsilon, delta). Create state using resultStateBatchForSourceImage: or
        /// temporaryResultStateBatchForCommandBuffer:.
        ///
        /// Parameter `destinationImages`: The MPSImages into which to write the loss results.
        #[unsafe(method(encodeBatchToCommandBuffer:sourceImages:labels:weights:destinationStates:destinationImages:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceImages_labels_weights_destinationStates_destinationImages(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_images: &MPSImageBatch,
            labels: &MPSImageBatch,
            weights: Option<&MPSImageBatch>,
            destination_states: Option<&MPSStateBatch>,
            destination_images: &MPSImageBatch,
        );

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        /// Encode a MPSNNForwardLoss filter and return the loss result image(s).
        ///
        /// This -encode call is similar to the encodeBatchToCommandBuffer:sourceImages:labels:destinationImages: above,
        /// except that it creates and returns the MPSImages with the loss result.
        ///
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode.
        ///
        /// Parameter `sourceImages`: The source images that contains the network prediction (logits).
        ///
        /// Parameter `labels`: The source images that contains the labels (targets).
        ///
        /// Parameter `weights`: The object containing weights for the labels. Optional.
        ///
        /// Parameter `outStates`: Optional gradient state - carries dynamical property values to the gradient pass
        /// (weight, labelSmoothing, epsilon, delta).
        ///
        /// Parameter `isTemporary`: Whether the returned state (if any) should be temporary or not.
        ///
        /// Returns: The MPSImages containing the loss computation results.
        #[unsafe(method(encodeBatchToCommandBuffer:sourceImages:labels:weights:destinationStates:destinationStateIsTemporary:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceImages_labels_weights_destinationStates_destinationStateIsTemporary(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_images: &MPSImageBatch,
            labels: &MPSImageBatch,
            weights: Option<&MPSImageBatch>,
            out_states: Option<&mut Option<Retained<MPSStateBatch>>>,
            is_temporary: bool,
        ) -> Retained<MPSImageBatch>;
    );
}

/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNForwardLoss {
    extern_methods!(
        /// Called by NSCoder to decode MPSKernels
        ///
        /// This isn't the right interface to decode a MPSKernel, but
        /// it is the one that NSCoder uses. To enable your NSCoder
        /// (e.g. NSKeyedUnarchiver) to set which device to use
        /// extend the object to adopt the MPSDeviceProvider
        /// protocol. Otherwise, the Metal system default device
        /// will be used.
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
        ) -> Option<Retained<Self>>;
    );
}

/// Methods declared on superclass `NSObject`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNForwardLoss {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// Dependencies: This depends on Metal.framework.
    ///
    /// The MPSNNLossGradient filter specifies the gradient filter for
    /// MPSNNForwardLoss.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsnnlossgradient?language=objc)
    #[unsafe(super(MPSCNNBinaryKernel, MPSKernel, NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    #[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
    pub struct MPSNNLossGradient;
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCoding for MPSNNLossGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCopying for MPSNNLossGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSNNLossGradient {
    type Result = Self;
}

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSObjectProtocol for MPSNNLossGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSSecureCoding for MPSNNLossGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNLossGradient {
    extern_methods!(
        #[cfg(feature = "MPSCNNTypes")]
        /// See MPSCNNLossDescriptor for information about the following properties.
        #[unsafe(method(lossType))]
        #[unsafe(method_family = none)]
        pub unsafe fn lossType(&self) -> MPSCNNLossType;

        #[cfg(feature = "MPSCNNTypes")]
        #[unsafe(method(reductionType))]
        #[unsafe(method_family = none)]
        pub unsafe fn reductionType(&self) -> MPSCNNReductionType;

        #[unsafe(method(reduceAcrossBatch))]
        #[unsafe(method_family = none)]
        pub unsafe fn reduceAcrossBatch(&self) -> bool;

        #[unsafe(method(numberOfClasses))]
        #[unsafe(method_family = none)]
        pub unsafe fn numberOfClasses(&self) -> NSUInteger;

        #[unsafe(method(weight))]
        #[unsafe(method_family = none)]
        pub unsafe fn weight(&self) -> c_float;

        /// Setter for [`weight`][Self::weight].
        #[unsafe(method(setWeight:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setWeight(&self, weight: c_float);

        #[unsafe(method(labelSmoothing))]
        #[unsafe(method_family = none)]
        pub unsafe fn labelSmoothing(&self) -> c_float;

        /// Setter for [`labelSmoothing`][Self::labelSmoothing].
        #[unsafe(method(setLabelSmoothing:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setLabelSmoothing(&self, label_smoothing: c_float);

        #[unsafe(method(epsilon))]
        #[unsafe(method_family = none)]
        pub unsafe fn epsilon(&self) -> c_float;

        /// Setter for [`epsilon`][Self::epsilon].
        #[unsafe(method(setEpsilon:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setEpsilon(&self, epsilon: c_float);

        #[unsafe(method(delta))]
        #[unsafe(method_family = none)]
        pub unsafe fn delta(&self) -> c_float;

        /// Setter for [`delta`][Self::delta].
        #[unsafe(method(setDelta:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setDelta(&self, delta: c_float);

        /// The computeLabelGradients property is used to control whether the loss gradient
        /// filter computes gradients for the primary (predictions) or secondary (labels) source image from the forward pass.
        /// Default: NO.
        #[unsafe(method(computeLabelGradients))]
        #[unsafe(method_family = none)]
        pub unsafe fn computeLabelGradients(&self) -> bool;

        /// Setter for [`computeLabelGradients`][Self::computeLabelGradients].
        #[unsafe(method(setComputeLabelGradients:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setComputeLabelGradients(&self, compute_label_gradients: bool);

        #[unsafe(method(initWithDevice:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Retained<Self>;

        /// Initialize the loss gradient filter with a loss descriptor.
        ///
        /// Parameter `device`: The device the filter will run on.
        ///
        /// Parameter `lossDescriptor`: The loss descriptor.
        ///
        /// Returns: A valid MPSNNLossGradient object or nil, if failure.
        #[unsafe(method(initWithDevice:lossDescriptor:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice_lossDescriptor(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
            loss_descriptor: &MPSCNNLossDescriptor,
        ) -> Retained<Self>;

        /// <NSSecureCoding
        /// > support
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:device:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder_device(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Option<Retained<Self>>;

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        /// Encode the loss gradient filter and return a gradient
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode
        ///
        /// Parameter `sourceGradients`: The gradient images from the "next" filter in the graph
        ///
        /// Parameter `sourceImages`: The images used as source image from the forward pass
        ///
        /// Parameter `labels`: The source images that contains the labels (targets).
        ///
        /// Parameter `weights`: The object containing weights for the labels. Optional.
        ///
        /// Parameter `sourceStates`: Optional gradient state - carries dynamical property values from the forward pass
        /// (weight, labelSmoothing, epsilon, delta).
        #[unsafe(method(encodeBatchToCommandBuffer:sourceGradients:sourceImages:labels:weights:sourceStates:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceGradients_sourceImages_labels_weights_sourceStates(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_gradients: &MPSImageBatch,
            source_images: &MPSImageBatch,
            labels: &MPSImageBatch,
            weights: Option<&MPSImageBatch>,
            source_states: Option<&MPSStateBatch>,
        ) -> Retained<MPSImageBatch>;

        #[cfg(all(feature = "MPSImage", feature = "MPSNDArray", feature = "MPSState"))]
        /// Encode the loss gradient filter and return a gradient
        ///
        /// Parameter `commandBuffer`: The MTLCommandBuffer on which to encode
        ///
        /// Parameter `sourceGradients`: The gradient images from the "next" filter in the graph
        ///
        /// Parameter `sourceImages`: The image used as source images from the forward pass
        ///
        /// Parameter `labels`: The source images that contains the labels (targets).
        ///
        /// Parameter `weights`: The object containing weights for the labels. Optional.
        ///
        /// Parameter `sourceStates`: Optional gradient state - carries dynamical property values from the forward pass
        /// (weight, labelSmoothing, epsilon, delta).
        ///
        /// Parameter `destinationGradients`: The MPSImages into which to write the filter result
        #[unsafe(method(encodeBatchToCommandBuffer:sourceGradients:sourceImages:labels:weights:sourceStates:destinationGradients:))]
        #[unsafe(method_family = none)]
        pub unsafe fn encodeBatchToCommandBuffer_sourceGradients_sourceImages_labels_weights_sourceStates_destinationGradients(
            &self,
            command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
            source_gradients: &MPSImageBatch,
            source_images: &MPSImageBatch,
            labels: &MPSImageBatch,
            weights: Option<&MPSImageBatch>,
            source_states: Option<&MPSStateBatch>,
            destination_gradients: &MPSImageBatch,
        );
    );
}

/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNLossGradient {
    extern_methods!(
        /// Called by NSCoder to decode MPSKernels
        ///
        /// This isn't the right interface to decode a MPSKernel, but
        /// it is the one that NSCoder uses. To enable your NSCoder
        /// (e.g. NSKeyedUnarchiver) to set which device to use
        /// extend the object to adopt the MPSDeviceProvider
        /// protocol. Otherwise, the Metal system default device
        /// will be used.
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
        ) -> Option<Retained<Self>>;
    );
}

/// Methods declared on superclass `NSObject`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNLossGradient {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}

extern_class!(
    /// Dependencies: This depends on Metal.framework
    ///
    /// The MPSCNNInitialGradient filter specifies a layer which computes the initial gradient for
    /// an aribitrary input image. The operation itself is extremely simple: it computes the gradient of the input image
    /// with itself, resulting in an output image which is filled with '1's for all the inputs that were used.
    /// This serves as the starting point for the computation of gradients between arbitrary images in a network.
    /// Example:
    /// Suppose that we want to compute gradients for a function that multiplies together two losses:
    /// f = f(L1, L2) = L1 * L2
    /// The losses themselves are computed from some inputs x1,x2:
    /// L1 = L1(x1),
    /// L2 = L2(x2)
    /// The filters to compute f, L1, L2 are:
    /// f = MPSCNNMultiply(L1, L2), where
    /// L1 = MPSNNForwardLoss1(x1) and
    /// L2 = MPSNNForwardLoss1(x2)
    ///
    /// To compute df/dx1 we apply the chain rule:
    ///
    /// df/dx1 = d(L1 * L2)/dx1 = d(L1 * L2)/dL1 * dL1/dx1 + d(L1 * L2)/dL2 * dL2/dx1
    /// = d(L1 * L2)/dL1 * dL1/dx1 = L2 * dL1/dx1
    ///
    /// The MPSCNNMultiplyGradient filter computes for f = L1 * L2 forward op:
    /// dL/dL1 = dL/df * df/dL1 = dL/df * L2 and
    /// dL/dL2 = dL/df * df/dL2 = dL/df * L1 where
    /// dL/df is the input gradient of the chain rule / backpropagation algorithm.
    /// But in our case we want MPSCNNMultiplyGradient to compute the gradient:
    /// df/dL1 = d(L1 * L2)/dL1 = L2,
    /// which shows that
    /// L = f, which means that dL/dL1 = df/df * df/dL1 = 1 * L2, which
    /// shows that we get the correct gradient by providing unit input as input gradient to
    /// the MPSCNNMultiplyGradient.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsnninitialgradient?language=objc)
    #[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    #[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
    pub struct MPSNNInitialGradient;
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCoding for MPSNNInitialGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSCopying for MPSNNInitialGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSNNInitialGradient {
    type Result = Self;
}

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSObjectProtocol for MPSNNInitialGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
    unsafe impl NSSecureCoding for MPSNNInitialGradient {}
);

#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNInitialGradient {
    extern_methods!(
        /// Initializes a MPSNNInitialGradient kernel.
        ///
        ///
        /// Parameter `device`: The MTLDevice on which this MPSNNInitialGradient filter will be used.
        ///
        /// Returns: A valid MPSNNInitialGradient object or nil, if failure.
        #[unsafe(method(initWithDevice:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithDevice(
            this: Allocated<Self>,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Retained<Self>;
    );
}

/// Methods declared on superclass `MPSCNNKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNInitialGradient {
    extern_methods!(
        /// NSSecureCoding compatability
        ///
        /// While the standard NSSecureCoding/NSCoding method
        /// -initWithCoder: should work, since the file can't
        /// know which device your data is allocated on, we
        /// have to guess and may guess incorrectly.  To avoid
        /// that problem, use initWithCoder:device instead.
        ///
        /// Parameter `aDecoder`: The NSCoder subclass with your serialized MPSKernel
        ///
        /// Parameter `device`: The MTLDevice on which to make the MPSKernel
        ///
        /// Returns: A new MPSKernel object, or nil if failure.
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:device:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder_device(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
            device: &ProtocolObject<dyn MTLDevice>,
        ) -> Option<Retained<Self>>;
    );
}

/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNInitialGradient {
    extern_methods!(
        /// Called by NSCoder to decode MPSKernels
        ///
        /// This isn't the right interface to decode a MPSKernel, but
        /// it is the one that NSCoder uses. To enable your NSCoder
        /// (e.g. NSKeyedUnarchiver) to set which device to use
        /// extend the object to adopt the MPSDeviceProvider
        /// protocol. Otherwise, the Metal system default device
        /// will be used.
        ///
        /// # Safety
        ///
        /// `a_decoder` possibly has further requirements.
        #[unsafe(method(initWithCoder:))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithCoder(
            this: Allocated<Self>,
            a_decoder: &NSCoder,
        ) -> Option<Retained<Self>>;
    );
}

/// Methods declared on superclass `NSObject`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNInitialGradient {
    extern_methods!(
        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;

        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}