1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
//! 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 MPSCNNConvolutionDescriptor specifies a convolution descriptor
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiondescriptor?language=objc)
#[unsafe(super(NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MPSCNNConvolutionDescriptor;
);
extern_conformance!(
unsafe impl NSCoding for MPSCNNConvolutionDescriptor {}
);
extern_conformance!(
unsafe impl NSCopying for MPSCNNConvolutionDescriptor {}
);
unsafe impl CopyingHelper for MPSCNNConvolutionDescriptor {
type Result = Self;
}
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionDescriptor {}
);
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNConvolutionDescriptor {}
);
impl MPSCNNConvolutionDescriptor {
extern_methods!(
/// The width of the filter window. The default value is 3.
/// Any positive non-zero value is valid, including even values.
/// The position of the left edge of the filter window is given
/// by offset.x - (kernelWidth>>1)
#[unsafe(method(kernelWidth))]
#[unsafe(method_family = none)]
pub unsafe fn kernelWidth(&self) -> NSUInteger;
/// Setter for [`kernelWidth`][Self::kernelWidth].
#[unsafe(method(setKernelWidth:))]
#[unsafe(method_family = none)]
pub unsafe fn setKernelWidth(&self, kernel_width: NSUInteger);
/// The height of the filter window. The default value is 3.
/// Any positive non-zero value is valid, including even values.
/// The position of the top edge of the filter window is given
/// by offset.y - (kernelHeight>>1)
#[unsafe(method(kernelHeight))]
#[unsafe(method_family = none)]
pub unsafe fn kernelHeight(&self) -> NSUInteger;
/// Setter for [`kernelHeight`][Self::kernelHeight].
#[unsafe(method(setKernelHeight:))]
#[unsafe(method_family = none)]
pub unsafe fn setKernelHeight(&self, kernel_height: NSUInteger);
/// The number of feature channels per pixel in the input image.
#[unsafe(method(inputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn inputFeatureChannels(&self) -> NSUInteger;
/// Setter for [`inputFeatureChannels`][Self::inputFeatureChannels].
#[unsafe(method(setInputFeatureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn setInputFeatureChannels(&self, input_feature_channels: NSUInteger);
/// The number of feature channels per pixel in the output image.
#[unsafe(method(outputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn outputFeatureChannels(&self) -> NSUInteger;
/// Setter for [`outputFeatureChannels`][Self::outputFeatureChannels].
#[unsafe(method(setOutputFeatureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn setOutputFeatureChannels(&self, output_feature_channels: NSUInteger);
/// The output stride (downsampling factor) in the x dimension. The default value is 1.
#[unsafe(method(strideInPixelsX))]
#[unsafe(method_family = none)]
pub unsafe fn strideInPixelsX(&self) -> NSUInteger;
/// Setter for [`strideInPixelsX`][Self::strideInPixelsX].
#[unsafe(method(setStrideInPixelsX:))]
#[unsafe(method_family = none)]
pub unsafe fn setStrideInPixelsX(&self, stride_in_pixels_x: NSUInteger);
/// The output stride (downsampling factor) in the y dimension. The default value is 1.
#[unsafe(method(strideInPixelsY))]
#[unsafe(method_family = none)]
pub unsafe fn strideInPixelsY(&self) -> NSUInteger;
/// Setter for [`strideInPixelsY`][Self::strideInPixelsY].
#[unsafe(method(setStrideInPixelsY:))]
#[unsafe(method_family = none)]
pub unsafe fn setStrideInPixelsY(&self, stride_in_pixels_y: NSUInteger);
/// Number of groups input and output channels are divided into. The default value is 1.
/// Groups lets you reduce the parameterization. If groups is set to n, input is divided into n
/// groups with inputFeatureChannels/n channels in each group. Similarly output is divided into
/// n groups with outputFeatureChannels/n channels in each group. ith group in input is only
/// connected to ith group in output so number of weights (parameters) needed is reduced by factor
/// of n. Both inputFeatureChannels and outputFeatureChannels must be divisible by n and number of
/// channels in each group must be multiple of 4.
#[unsafe(method(groups))]
#[unsafe(method_family = none)]
pub unsafe fn groups(&self) -> NSUInteger;
/// Setter for [`groups`][Self::groups].
#[unsafe(method(setGroups:))]
#[unsafe(method_family = none)]
pub unsafe fn setGroups(&self, groups: NSUInteger);
/// dilationRateX property can be used to implement dilated convolution as described in
/// https://arxiv.org/pdf/1511.07122v3.pdf
/// to aggregate global information in dense prediction problems.
/// Default value is 1. When set to value > 1, original kernel width, kW is dilated to
///
/// kW_Dilated = (kW-1)*dilationRateX + 1
///
/// by inserting d-1 zeros between consecutive entries in each row of the original kernel.
/// The kernel is centered based on kW_Dilated.
#[unsafe(method(dilationRateX))]
#[unsafe(method_family = none)]
pub unsafe fn dilationRateX(&self) -> NSUInteger;
/// Setter for [`dilationRateX`][Self::dilationRateX].
#[unsafe(method(setDilationRateX:))]
#[unsafe(method_family = none)]
pub unsafe fn setDilationRateX(&self, dilation_rate_x: NSUInteger);
/// dilationRateY property can be used to implement dilated convolution as described in
/// https://arxiv.org/pdf/1511.07122v3.pdf
/// to aggregate global information in dense prediction problems.
/// Default value is 1. When set to value > 1, original kernel height, kH is dilated to
///
/// kH_Dilated = (kH-1)*dilationRateY + 1
///
/// by inserting d-1 rows of zeros between consecutive row of the original kernel.
/// The kernel is centered based on kH_Dilated.
#[unsafe(method(dilationRateY))]
#[unsafe(method_family = none)]
pub unsafe fn dilationRateY(&self) -> NSUInteger;
/// Setter for [`dilationRateY`][Self::dilationRateY].
#[unsafe(method(setDilationRateY:))]
#[unsafe(method_family = none)]
pub unsafe fn setDilationRateY(&self, dilation_rate_y: NSUInteger);
#[cfg(feature = "MPSCNNNeuron")]
/// This mathod can be used to add a neuron activation funtion of given type with
/// associated scalar parameters A and B that are shared across all output channels.
/// Neuron activation fucntion is applied to output of convolution. This is a per-pixel
/// operation that is fused with convolution kernel itself for best performance.
/// Note that this method can only be used to fuse neuron of kind for which parameters
/// A and B are shared across all channels of convoution output. It is an error to call
/// this method for neuron activation functions like MPSCNNNeuronTypePReLU,
/// which require per-channel parameter values. For those kind of neuron activation functions,
/// use appropriate setter functions. Default is descriptor with neuronType MPSCNNNeuronTypeNone.
///
/// Note: in certain cases the neuron descriptor will be cached by the MPSNNGraph or the
/// MPSCNNConvolution. If the neuron type changes after either is made, behavior is undefined.
#[unsafe(method(fusedNeuronDescriptor))]
#[unsafe(method_family = none)]
pub unsafe fn fusedNeuronDescriptor(&self) -> Retained<MPSNNNeuronDescriptor>;
#[cfg(feature = "MPSCNNNeuron")]
/// Setter for [`fusedNeuronDescriptor`][Self::fusedNeuronDescriptor].
#[unsafe(method(setFusedNeuronDescriptor:))]
#[unsafe(method_family = none)]
pub unsafe fn setFusedNeuronDescriptor(
&self,
fused_neuron_descriptor: &MPSNNNeuronDescriptor,
);
#[cfg(all(
feature = "MPSCNNKernel",
feature = "MPSCNNNeuron",
feature = "MPSCore",
feature = "MPSKernel"
))]
/// MPSCNNNeuron filter to be applied as part of convolution. This is applied after BatchNormalization in the end.
/// Default is nil.
/// This is deprecated. You dont need to create MPSCNNNeuron object to fuse with convolution. Use neuron properties
/// in this descriptor.
#[deprecated]
#[unsafe(method(neuron))]
#[unsafe(method_family = none)]
pub unsafe fn neuron(&self) -> Option<Retained<MPSCNNNeuron>>;
#[cfg(all(
feature = "MPSCNNKernel",
feature = "MPSCNNNeuron",
feature = "MPSCore",
feature = "MPSKernel"
))]
/// Setter for [`neuron`][Self::neuron].
#[deprecated]
#[unsafe(method(setNeuron:))]
#[unsafe(method_family = none)]
pub unsafe fn setNeuron(&self, neuron: Option<&MPSCNNNeuron>);
/// <NSSecureCoding
/// > support
#[unsafe(method(supportsSecureCoding))]
#[unsafe(method_family = none)]
pub unsafe fn supportsSecureCoding() -> bool;
/// <NSSecureCoding
/// > support
///
/// # Safety
///
/// `a_coder` possibly has further requirements.
#[unsafe(method(encodeWithCoder:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeWithCoder(&self, a_coder: &NSCoder);
/// <NSSecureCoding
/// > support
///
/// # 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>>;
#[cfg(all(
feature = "MPSCNNKernel",
feature = "MPSCNNNeuron",
feature = "MPSCore",
feature = "MPSKernel"
))]
/// This method is deprecated. Please use neuronType, neuronParameterA and neuronParameterB properites to fuse
/// neuron with convolution.
///
/// Parameter `kernelWidth`: The width of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `kernelHeight`: The height of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `inputFeatureChannels`: The number of feature channels in the input image. Must be >= 1.
///
/// Parameter `outputFeatureChannels`: The number of feature channels in the output image. Must be >= 1.
///
/// Parameter `neuronFilter`: An optional neuron filter that can be applied to the output of convolution.
///
/// Returns: A valid MPSCNNConvolutionDescriptor object or nil, if failure.
#[deprecated]
#[unsafe(method(cnnConvolutionDescriptorWithKernelWidth:kernelHeight:inputFeatureChannels:outputFeatureChannels:neuronFilter:))]
#[unsafe(method_family = none)]
pub unsafe fn cnnConvolutionDescriptorWithKernelWidth_kernelHeight_inputFeatureChannels_outputFeatureChannels_neuronFilter(
kernel_width: NSUInteger,
kernel_height: NSUInteger,
input_feature_channels: NSUInteger,
output_feature_channels: NSUInteger,
neuron_filter: Option<&MPSCNNNeuron>,
) -> Retained<Self>;
/// Creates a convolution descriptor.
///
/// Parameter `kernelWidth`: The width of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `kernelHeight`: The height of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `inputFeatureChannels`: The number of feature channels in the input image. Must be >= 1.
///
/// Parameter `outputFeatureChannels`: The number of feature channels in the output image. Must be >= 1.
///
/// Returns: A valid MPSCNNConvolutionDescriptor object or nil, if failure.
#[unsafe(method(cnnConvolutionDescriptorWithKernelWidth:kernelHeight:inputFeatureChannels:outputFeatureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn cnnConvolutionDescriptorWithKernelWidth_kernelHeight_inputFeatureChannels_outputFeatureChannels(
kernel_width: NSUInteger,
kernel_height: NSUInteger,
input_feature_channels: NSUInteger,
output_feature_channels: NSUInteger,
) -> Retained<Self>;
/// Adds batch normalization for inference, it copies all the float arrays provided, expecting
/// outputFeatureChannels elements in each.
///
///
/// This method will be used to pass in batch normalization parameters to the convolution during the
/// init call. For inference we modify weights and bias going in convolution or Fully Connected layer to combine
/// and optimize the layers.
///
/// w: weights for a corresponding output feature channel
/// b: bias for a corresponding output feature channel
/// W: batch normalized weights for a corresponding output feature channel
/// B: batch normalized bias for a corresponding output feature channel
///
/// I = gamma / sqrt(variance + epsilon), J = beta - ( I * mean )
///
/// W = w * I
/// B = b * I + J
///
/// Every convolution has (OutputFeatureChannel * kernelWidth * kernelHeight * InputFeatureChannel) weights
///
/// I, J are calculated, for every output feature channel separately to get the corresponding weights and bias
/// Thus, I, J are calculated and then used for every (kernelWidth * kernelHeight * InputFeatureChannel)
/// weights, and this is done OutputFeatureChannel number of times for each output channel.
///
/// thus, internally, batch normalized weights are computed as:
///
/// W[no][i][j][ni] = w[no][i][j][ni] * I[no]
///
/// no: index into outputFeatureChannel
/// i : index into kernel Height
/// j : index into kernel Width
/// ni: index into inputFeatureChannel
///
/// One usually doesn't see a bias term and batch normalization together as batch normalization potentially cancels
/// out the bias term after training, but in MPS if the user provides it, batch normalization will use the above
/// formula to incorporate it, if user does not have bias terms then put a float array of zeroes in the convolution
/// init for bias terms of each output feature channel.
///
/// this comes from:
/// https://arxiv.org/pdf/1502.03167v3.pdf
///
/// Note: in certain cases the batch normalization parameters will be cached by the MPSNNGraph
/// or the MPSCNNConvolution. If the batch normalization parameters change after either is made,
/// behavior is undefined.
///
///
/// Parameter `mean`: Pointer to an array of floats of mean for each output feature channel
///
/// Parameter `variance`: Pointer to an array of floats of variance for each output feature channel
///
/// Parameter `gamma`: Pointer to an array of floats of gamma for each output feature channel
///
/// Parameter `beta`: Pointer to an array of floats of beta for each output feature channel
///
/// Parameter `epsilon`: A small float value used to have numerical stability in the code
///
/// # Safety
///
/// - `mean` must be a valid pointer or null.
/// - `variance` must be a valid pointer or null.
/// - `gamma` must be a valid pointer or null.
/// - `beta` must be a valid pointer or null.
#[unsafe(method(setBatchNormalizationParametersForInferenceWithMean:variance:gamma:beta:epsilon:))]
#[unsafe(method_family = none)]
pub unsafe fn setBatchNormalizationParametersForInferenceWithMean_variance_gamma_beta_epsilon(
&self,
mean: *const c_float,
variance: *const c_float,
gamma: *const c_float,
beta: *const c_float,
epsilon: c_float,
);
#[cfg(feature = "MPSCNNNeuronType")]
/// Adds a neuron activation function to convolution descriptor.
///
///
/// This mathod can be used to add a neuron activation funtion of given type with
/// associated scalar parameters A and B that are shared across all output channels.
/// Neuron activation fucntion is applied to output of convolution. This is a per-pixel
/// operation that is fused with convolution kernel itself for best performance.
/// Note that this method can only be used to fuse neuron of kind for which parameters
/// A and B are shared across all channels of convoution output. It is an error to call
/// this method for neuron activation functions like MPSCNNNeuronTypePReLU,
/// which require per-channel parameter values. For those kind of neuron activation functions,
/// use appropriate setter functions.
///
/// Note: in certain cases, the neuron descriptor will be cached by the MPSNNGraph or the
/// MPSCNNConvolution. If the neuron type changes after either is made, behavior is undefined.
///
///
/// Parameter `neuronType`: type of neuron activation function. For full list see MPSCNNNeuronType.h
///
/// Parameter `parameterA`: parameterA of neuron activation that is shared across all channels of convolution output.
///
/// Parameter `parameterB`: parameterB of neuron activation that is shared across all channels of convolution output.
#[deprecated]
#[unsafe(method(setNeuronType:parameterA:parameterB:))]
#[unsafe(method_family = none)]
pub unsafe fn setNeuronType_parameterA_parameterB(
&self,
neuron_type: MPSCNNNeuronType,
parameter_a: c_float,
parameter_b: c_float,
);
#[cfg(feature = "MPSCNNNeuronType")]
/// Getter funtion for neuronType set using setNeuronType:parameterA:parameterB method
#[deprecated]
#[unsafe(method(neuronType))]
#[unsafe(method_family = none)]
pub unsafe fn neuronType(&self) -> MPSCNNNeuronType;
/// Getter funtion for neuronType set using setNeuronType:parameterA:parameterB method
#[deprecated]
#[unsafe(method(neuronParameterA))]
#[unsafe(method_family = none)]
pub unsafe fn neuronParameterA(&self) -> c_float;
/// Getter funtion for neuronType set using setNeuronType:parameterA:parameterB method
#[deprecated]
#[unsafe(method(neuronParameterB))]
#[unsafe(method_family = none)]
pub unsafe fn neuronParameterB(&self) -> c_float;
/// Add per-channel neuron parameters A for PReLu neuron activation functions.
///
///
/// This method sets the neuron to PReLU, zeros parameters A and B and sets the per-channel
/// neuron parameters A to an array containing a unique value of A for each output feature
/// channel.
///
/// If the neuron function is f(v,a,b), it will apply
///
/// OutputImage(x,y,i) = f( ConvolutionResult(x,y,i), A[i], B[i] ) where i in [0,outputFeatureChannels-1]
///
/// See https://arxiv.org/pdf/1502.01852.pdf for details.
///
/// All other neuron types, where parameter A
/// and parameter B are shared across channels must be set using
/// -setNeuronOfType:parameterA:parameterB:
///
/// If batch normalization parameters are set, batch normalization will occur before
/// neuron application i.e. output of convolution is first batch normalized followed
/// by neuron activation. This function automatically sets neuronType to MPSCNNNeuronTypePReLU.
///
/// Note: in certain cases the neuron descriptor will be cached by the MPSNNGraph or the
/// MPSCNNConvolution. If the neuron type changes after either is made, behavior is undefined.
///
///
/// Parameter `A`: An array containing per-channel float values for neuron parameter A.
/// Number of entries must be equal to outputFeatureChannels.
#[deprecated]
#[unsafe(method(setNeuronToPReLUWithParametersA:))]
#[unsafe(method_family = none)]
pub unsafe fn setNeuronToPReLUWithParametersA(&self, a: &NSData);
);
}
/// Methods declared on superclass `NSObject`.
impl MPSCNNConvolutionDescriptor {
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!(
/// MPSCNNSubPixelConvolutionDescriptor can be used to create MPSCNNConvolution object that does sub pixel upsamling
/// and reshaping opeartion as described in
/// http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Shi_Real-Time_Single_Image_CVPR_2016_paper.pdf
///
/// Conceptually MPSCNNConvolution with subPixelScaleFactor > 1 can be thought of as filter performing regular CNN convolution producing N output feature channels at each pixel of
/// an intermediate MPSImage followed by a kernel that rearranges/reshapes these N channels at each pixel of intermediate MPSImage into a pixel block of
/// size subPixelScaleFactor x subPixelScaleFactor with N/(subPixelScaleFactor * subPixelScaleFactor) featureChannels at each pixel of this pixel block. Thus each pixel in intermedaite
/// MPSImage with N channels map to subPixelScaleFactor x subPixelScaleFactor pixel block in final destination MPSImage with N/(subPixelScaleFactor * subPixelScaleFactor) featureChannels.
/// MPSCNNConvolution with subPixelScaleFactor > 1 fuses the convolution and reshaping operation into single compute kernel thus not only saving DRAM roundtrip but also memory
/// needed for intermediate MPSImage had these operation done separately.
/// Let N be the value of outputFeatureChannels property and let r = subPixelScaleFactor.
/// Conceptually Convolution will produce intermedaite image Io of dimensions (treated as 3D tensor) width x height x N where
/// width = (clipRect.size.width + r - 1) / r
/// height = (clipRect.size.height + r -1) / r
/// Reshaping happens as follows
///
/// ```text
/// Destination[clipRect.origin.x+x][clipRect.origin.y+y][c] = Io[ floor(x/r) ][ floor(y/r) ][ (N/r^2) * ( r * mod(y,r) + mod(x,r) ) + c ]
/// where x in [0,clipRect.size.width-1], y in [0,clipRect.size.height-1], c in [0,N/r^2 - 1]
/// ```
///
/// The following conditions must be met:
/// 1) N (outputFeatureChannels) must be multiple of r^2 (subPixelScaleFactor * subPixelScaleFactor).
/// 2) The destination MPSImage to encode call must have at least N/r^2 + destinationFeatureChannelOffset channels.
/// 3) Number of feature channels in reshaped output image (N/r^2) can be any value when groups = 1 but must be multiple of 4 when groups > 1.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnsubpixelconvolutiondescriptor?language=objc)
#[unsafe(super(MPSCNNConvolutionDescriptor, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MPSCNNSubPixelConvolutionDescriptor;
);
extern_conformance!(
unsafe impl NSCoding for MPSCNNSubPixelConvolutionDescriptor {}
);
extern_conformance!(
unsafe impl NSCopying for MPSCNNSubPixelConvolutionDescriptor {}
);
unsafe impl CopyingHelper for MPSCNNSubPixelConvolutionDescriptor {
type Result = Self;
}
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNSubPixelConvolutionDescriptor {}
);
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNSubPixelConvolutionDescriptor {}
);
impl MPSCNNSubPixelConvolutionDescriptor {
extern_methods!(
/// Upsampling scale factor. Each pixel in input is upsampled into a subPixelScaleFactor x subPixelScaleFactor pixel block by rearranging
/// the outputFeatureChannels as described above. Default value is 1.
#[unsafe(method(subPixelScaleFactor))]
#[unsafe(method_family = none)]
pub unsafe fn subPixelScaleFactor(&self) -> NSUInteger;
/// Setter for [`subPixelScaleFactor`][Self::subPixelScaleFactor].
#[unsafe(method(setSubPixelScaleFactor:))]
#[unsafe(method_family = none)]
pub unsafe fn setSubPixelScaleFactor(&self, sub_pixel_scale_factor: NSUInteger);
);
}
/// Methods declared on superclass `MPSCNNConvolutionDescriptor`.
impl MPSCNNSubPixelConvolutionDescriptor {
extern_methods!(
/// <NSSecureCoding
/// > support
///
/// # 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>>;
#[cfg(all(
feature = "MPSCNNKernel",
feature = "MPSCNNNeuron",
feature = "MPSCore",
feature = "MPSKernel"
))]
/// This method is deprecated. Please use neuronType, neuronParameterA and neuronParameterB properites to fuse
/// neuron with convolution.
///
/// Parameter `kernelWidth`: The width of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `kernelHeight`: The height of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `inputFeatureChannels`: The number of feature channels in the input image. Must be >= 1.
///
/// Parameter `outputFeatureChannels`: The number of feature channels in the output image. Must be >= 1.
///
/// Parameter `neuronFilter`: An optional neuron filter that can be applied to the output of convolution.
///
/// Returns: A valid MPSCNNConvolutionDescriptor object or nil, if failure.
#[deprecated]
#[unsafe(method(cnnConvolutionDescriptorWithKernelWidth:kernelHeight:inputFeatureChannels:outputFeatureChannels:neuronFilter:))]
#[unsafe(method_family = none)]
pub unsafe fn cnnConvolutionDescriptorWithKernelWidth_kernelHeight_inputFeatureChannels_outputFeatureChannels_neuronFilter(
kernel_width: NSUInteger,
kernel_height: NSUInteger,
input_feature_channels: NSUInteger,
output_feature_channels: NSUInteger,
neuron_filter: Option<&MPSCNNNeuron>,
) -> Retained<Self>;
/// Creates a convolution descriptor.
///
/// Parameter `kernelWidth`: The width of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `kernelHeight`: The height of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `inputFeatureChannels`: The number of feature channels in the input image. Must be >= 1.
///
/// Parameter `outputFeatureChannels`: The number of feature channels in the output image. Must be >= 1.
///
/// Returns: A valid MPSCNNConvolutionDescriptor object or nil, if failure.
#[unsafe(method(cnnConvolutionDescriptorWithKernelWidth:kernelHeight:inputFeatureChannels:outputFeatureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn cnnConvolutionDescriptorWithKernelWidth_kernelHeight_inputFeatureChannels_outputFeatureChannels(
kernel_width: NSUInteger,
kernel_height: NSUInteger,
input_feature_channels: NSUInteger,
output_feature_channels: NSUInteger,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `NSObject`.
impl MPSCNNSubPixelConvolutionDescriptor {
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!(
/// MPSCNNDepthWiseConvolutionDescriptor can be used to create MPSCNNConvolution object that does depthwise convolution
///
/// Depthwise convolution applies different filter to each input feature channel i.e. no cross channel mixing.
/// Number of outputFeatureChannels can be greater than number of inputFeatureChannels, in which case convolution
/// expects channelMultipler = outputFeactureChannels/inputFeatureChannels number of filters for each input channel.
/// This means channelMultipler filters are applied to each input feature channel producing channelMultipler output feature channels.
/// All channelMultipler output feature channels produced by single input feature channel are stored togather in output image i.e.
/// output[x,y,k*channelMultiplier + q] = input[x,y,k] * filter[k,q]
/// where * here denotes convolution.
/// group must be 1.
/// Weights array returned by MPSCNNConvolutionDataProvier is interpreted as
/// Weights [inputFeatureChannels] [channelMultiplier] [kH] [kW]
/// = Weights [ inputFeatureChannels * channelMultiplier ] [kH] [kW]
/// = Weights [ outputFeatureChannels ] [kH] [kW]
///
/// Currently only channel multipler of 1 is supported i.e. inputFeatureChannels == outputFeatureChannels
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnndepthwiseconvolutiondescriptor?language=objc)
#[unsafe(super(MPSCNNConvolutionDescriptor, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MPSCNNDepthWiseConvolutionDescriptor;
);
extern_conformance!(
unsafe impl NSCoding for MPSCNNDepthWiseConvolutionDescriptor {}
);
extern_conformance!(
unsafe impl NSCopying for MPSCNNDepthWiseConvolutionDescriptor {}
);
unsafe impl CopyingHelper for MPSCNNDepthWiseConvolutionDescriptor {
type Result = Self;
}
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNDepthWiseConvolutionDescriptor {}
);
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNDepthWiseConvolutionDescriptor {}
);
impl MPSCNNDepthWiseConvolutionDescriptor {
extern_methods!(
/// Ratio of outputFeactureChannel to inputFeatureChannels for depthwise convolution i.e. how many output feature channels are
/// produced by each input channel.
#[unsafe(method(channelMultiplier))]
#[unsafe(method_family = none)]
pub unsafe fn channelMultiplier(&self) -> NSUInteger;
);
}
/// Methods declared on superclass `MPSCNNConvolutionDescriptor`.
impl MPSCNNDepthWiseConvolutionDescriptor {
extern_methods!(
/// <NSSecureCoding
/// > support
///
/// # 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>>;
#[cfg(all(
feature = "MPSCNNKernel",
feature = "MPSCNNNeuron",
feature = "MPSCore",
feature = "MPSKernel"
))]
/// This method is deprecated. Please use neuronType, neuronParameterA and neuronParameterB properites to fuse
/// neuron with convolution.
///
/// Parameter `kernelWidth`: The width of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `kernelHeight`: The height of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `inputFeatureChannels`: The number of feature channels in the input image. Must be >= 1.
///
/// Parameter `outputFeatureChannels`: The number of feature channels in the output image. Must be >= 1.
///
/// Parameter `neuronFilter`: An optional neuron filter that can be applied to the output of convolution.
///
/// Returns: A valid MPSCNNConvolutionDescriptor object or nil, if failure.
#[deprecated]
#[unsafe(method(cnnConvolutionDescriptorWithKernelWidth:kernelHeight:inputFeatureChannels:outputFeatureChannels:neuronFilter:))]
#[unsafe(method_family = none)]
pub unsafe fn cnnConvolutionDescriptorWithKernelWidth_kernelHeight_inputFeatureChannels_outputFeatureChannels_neuronFilter(
kernel_width: NSUInteger,
kernel_height: NSUInteger,
input_feature_channels: NSUInteger,
output_feature_channels: NSUInteger,
neuron_filter: Option<&MPSCNNNeuron>,
) -> Retained<Self>;
/// Creates a convolution descriptor.
///
/// Parameter `kernelWidth`: The width of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `kernelHeight`: The height of the filter window. Must be > 0. Large values will take a long time.
///
/// Parameter `inputFeatureChannels`: The number of feature channels in the input image. Must be >= 1.
///
/// Parameter `outputFeatureChannels`: The number of feature channels in the output image. Must be >= 1.
///
/// Returns: A valid MPSCNNConvolutionDescriptor object or nil, if failure.
#[unsafe(method(cnnConvolutionDescriptorWithKernelWidth:kernelHeight:inputFeatureChannels:outputFeatureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn cnnConvolutionDescriptorWithKernelWidth_kernelHeight_inputFeatureChannels_outputFeatureChannels(
kernel_width: NSUInteger,
kernel_height: NSUInteger,
input_feature_channels: NSUInteger,
output_feature_channels: NSUInteger,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `NSObject`.
impl MPSCNNDepthWiseConvolutionDescriptor {
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>;
);
}
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutionweightslayout?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MPSCNNConvolutionWeightsLayout(pub u32);
impl MPSCNNConvolutionWeightsLayout {
#[doc(alias = "MPSCNNConvolutionWeightsLayoutOHWI")]
pub const OHWI: Self = Self(0);
}
unsafe impl Encode for MPSCNNConvolutionWeightsLayout {
const ENCODING: Encoding = u32::ENCODING;
}
unsafe impl RefEncode for MPSCNNConvolutionWeightsLayout {
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnweightsquantizationtype?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MPSCNNWeightsQuantizationType(pub u32);
impl MPSCNNWeightsQuantizationType {
#[doc(alias = "MPSCNNWeightsQuantizationTypeNone")]
pub const None: Self = Self(0);
#[doc(alias = "MPSCNNWeightsQuantizationTypeLinear")]
pub const Linear: Self = Self(1);
#[doc(alias = "MPSCNNWeightsQuantizationTypeLookupTable")]
pub const LookupTable: Self = Self(2);
}
unsafe impl Encode for MPSCNNWeightsQuantizationType {
const ENCODING: Encoding = u32::ENCODING;
}
unsafe impl RefEncode for MPSCNNWeightsQuantizationType {
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
extern_class!(
/// The MPSCNNConvolutionGradientState is returned by resultStateForSourceImage:sourceStates method on MPSCNNConvolution object.
/// Note that resultStateForSourceImage:sourceStates:destinationImage creates the object on autoreleasepool.
/// It will be consumed by MPSCNNConvolutionGradient. This is also used by MPSCNNConvolutionTranspose encode call
/// that returns MPSImage on left hand side to correctly size the destination.
/// Note that state objects are not usable across batches i.e. when batch is done you should nuke the state object and create
/// new one for next batch.
///
/// This state exposes the gradient with respect to weights and biases, as computed by the MPSCNNConvolutionGradient kernel, as a metal buffer to be used
/// during weights and biases update. The standard weights and biases update formula is:
///
/// weights(t+1) = f(weights(t), gradientForWeights(t)) and
/// biases(t+1) = f(biases(t), gradientForBiases(t)),
///
/// where the weights(t)/biases(t) are the wegihts and the biases at step t that are provided by data source provider used to create MPSCNNConvolution and
/// MPSCNNConvoltuionGradient objects. There are multiple ways user can update weights and biases as described below:
///
/// 1) For check pointing, i.e. updating weights/biases and storing:
/// once the command buffer on which MPSCNNConvolutionGradient is enqueued is done (e.g. in command
/// buffer completion callback), the application can simply use
/// float* delta_w = (float*)((char*)[gradientForWeights contents]);
/// float* delta_b = (float*)((char*)[gradientForBiases contents]);
/// to update the weights and biases in the data provider directly.
/// The application can instead provide a metal kernel that reads from gradientForWeights and gradientForBiases buffer and the buffer created using data provided by the data source
/// to do any kind of update it will like to do, then read back the updated weights/biases and store to the data source. Note that lifetime of the
/// gradientForWeights and gradientForBiases buffer is the same as the MPSCNNConvolutionGradientState. So it's the applications's responsibility to make sure the buffer is alive
/// (retained) when the update kernel is running if the command buffer doesn't retain the buffer. Also, in order to gaurantee that the buffer is correctly
/// synchronized for CPU side access, it is the application's responsibility to call
/// [gradientState synchronizeOnCommandBuffer:]
/// before accessing data from the buffer.
///
/// 2) For a CPU side update, once the weights and biases in the data source provider are updated as above, the original MPSCNNConvolution and
/// MPSCNNConvolutionGradient objects need to be updated with the new weigths and biases by calling the
/// -(void) reloadWeightsAndBiasesFromDataSource
/// method. Again application needs to call [gradientState synchronizeOnCommandBuffer:] before touching data on CPU side.
///
/// 3) The above CPU side update requires command buffer to be done. If the application doesn't want to update its data source provider object and would prefer to directly
/// enqueue an update of the internal MPSCNNConvolution and MPSCNNConvolutionGradient weights/biases buffers on the GPU without CPU side involvement, it needs to do
/// following:
/// i) get gradientForWeights and gradientForBiases buffers from this gradient state object and set it as source of update kernel
/// ii) create a temporary buffer, dest, of same size and set it as destination of update kernel
/// iii) enqueue update kernel on command buffer
/// iv) call reloadWeightsAndBiasesWithCommandBuffer:dest:weightsOffset:biasesOffset on MPSCNNConvolution and MPSCNNConvolutionGradient objects. This
/// will reload the weights from application's update kernel in dest on GPU without CPU side involvement.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiongradientstate?language=objc)
#[unsafe(super(MPSNNGradientState, MPSState, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
pub struct MPSCNNConvolutionGradientState;
);
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSNeuralNetworkTypes",
feature = "MPSState"
))]
extern_conformance!(
unsafe impl MPSImageSizeEncodingState for MPSCNNConvolutionGradientState {}
);
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionGradientState {}
);
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
impl MPSCNNConvolutionGradientState {
extern_methods!(
/// A buffer that contains the loss function gradients with respect to weights.
/// Each value in the buffer is a float. The layout of the gradients with respect to the weights is the same as
/// the weights layout provided by data source i.e. it can be interpreted as 4D array
///
/// gradientForWeights[outputFeatureChannels][kernelHeight][kernelWidth][inputFeatureChannels/groups]
/// For depthwise convolution it will be (since we only support channel multiplier of 1 currently)
/// gradientForWeights[outputFeatureChannels][kernelHeight][kernelWidth]
#[unsafe(method(gradientForWeights))]
#[unsafe(method_family = none)]
pub unsafe fn gradientForWeights(&self) -> Retained<ProtocolObject<dyn MTLBuffer>>;
/// A buffer that contains the loss function gradients with respect to biases.
#[unsafe(method(gradientForBiases))]
#[unsafe(method_family = none)]
pub unsafe fn gradientForBiases(&self) -> Retained<ProtocolObject<dyn MTLBuffer>>;
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSKernel"))]
/// The convolution filter that produced the state.
/// For child MPSCNNConvolutionTrasposeGradientState object, convolution
/// below refers to MPSCNNConvolution object that produced MPSCNNConvolutionGradientState object
/// which was used to create MPSCNNConvolutionTransposeGradientState object. See resultStateForSourceImage:sourceStates
/// method of MPSCNNConvolutionTranspose below.
#[unsafe(method(convolution))]
#[unsafe(method_family = none)]
pub unsafe fn convolution(&self) -> Retained<MPSCNNConvolution>;
/// Layout of gradient with respect to weights in gradientForWeights buffer.
/// Currently only MPSCNNConvolutionWeightsLayoutOHWI is supported.
#[unsafe(method(gradientForWeightsLayout))]
#[unsafe(method_family = none)]
pub unsafe fn gradientForWeightsLayout(&self) -> MPSCNNConvolutionWeightsLayout;
);
}
/// Methods declared on superclass `MPSState`.
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
impl MPSCNNConvolutionGradientState {
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>;
#[unsafe(method(init))]
#[unsafe(method_family = init)]
pub unsafe fn init(this: Allocated<Self>) -> Option<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 = "MPSNNGradientState",
feature = "MPSState"
))]
impl MPSCNNConvolutionGradientState {
extern_methods!(
#[unsafe(method(new))]
#[unsafe(method_family = new)]
pub unsafe fn new() -> Retained<Self>;
);
}
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiongradientstatebatch?language=objc)
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
pub type MPSCNNConvolutionGradientStateBatch = NSArray<MPSCNNConvolutionGradientState>;
extern_class!(
/// The MPSCNNConvolutionTransposeGradientState is returned by resultStateForSourceImage:sourceStates method on MPSCNNConvolutionTranspose object.
/// Note that resultStateForSourceImage:sourceStates:destinationImage creates the object on autoreleasepool.
/// It will be consumed by MPSCNNConvolutionTransposeGradient. It contains reference to MPSCNNConvolutionGradientState object that connects
/// MPSCNNConvolution and its corresponding MPSCNNConvolutionTranspose in forward pass of autoencoder. In an autoencoder forward pass, MPSCNNConvolutionGradientState is produced
/// by MPSCNNConvolution object and is used by corresponding MPSCNNConvolutionTraspose of forward pass that "undo" the corresponding MPSCNNConvolution. It is used to correctly size
/// destination image that is returned on left hand side by encode call MPSCNNConvolutionTranspose as well as automatically set kernelOffsetX/Y on MPSCNNConvolutionTranspose using
/// the offset and other properties of corresponding MPSCNNConvolution object. During training, same MPSCNNConvolutionGradientState object will be consumed by MPSCNNConvolutionGradient
/// object and the MPSCNNConvolutionTransposeGradientState produced by MPSCNNConvolutionTranspose's resultStateForSourceImage:sourceStates:destinationImage will be consumed by
/// MPSCNNConvolutionTransposeGradient object
///
/// Note that state objects are not usable across batches i.e. when batch is done you should nuke the state object and create
/// new one for next batch.
/// Weights update process for MPSCNNConvolutionTranspose is same as explained above for MPSCNNConvolution. See comments for MPSCNNConvolutionGradientState.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiontransposegradientstate?language=objc)
#[unsafe(super(MPSCNNConvolutionGradientState, MPSNNGradientState, MPSState, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
pub struct MPSCNNConvolutionTransposeGradientState;
);
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSNeuralNetworkTypes",
feature = "MPSState"
))]
extern_conformance!(
unsafe impl MPSImageSizeEncodingState for MPSCNNConvolutionTransposeGradientState {}
);
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionTransposeGradientState {}
);
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
impl MPSCNNConvolutionTransposeGradientState {
extern_methods!(
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSKernel"))]
/// The convolutionTranspose filter that produced the state.
#[unsafe(method(convolutionTranspose))]
#[unsafe(method_family = none)]
pub unsafe fn convolutionTranspose(&self) -> Retained<MPSCNNConvolutionTranspose>;
);
}
/// Methods declared on superclass `MPSState`.
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
impl MPSCNNConvolutionTransposeGradientState {
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>;
#[unsafe(method(init))]
#[unsafe(method_family = init)]
pub unsafe fn init(this: Allocated<Self>) -> Option<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 = "MPSNNGradientState",
feature = "MPSState"
))]
impl MPSCNNConvolutionTransposeGradientState {
extern_methods!(
#[unsafe(method(new))]
#[unsafe(method_family = new)]
pub unsafe fn new() -> Retained<Self>;
);
}
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiontransposegradientstatebatch?language=objc)
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
pub type MPSCNNConvolutionTransposeGradientStateBatch =
NSArray<MPSCNNConvolutionTransposeGradientState>;
extern_class!(
/// The MPSCNNConvolutionWeightsAndBiasesState is returned by exportWeightsAndBiasesWithCommandBuffer: method on MPSCNNConvolution object.
/// This is mainly used for GPU side weights/biases update process.
/// During training, application can keep a copy of weights, velocity, momentum MTLBuffers in its data source, update the weights (in-place or out of place)
/// with gradients obtained from MPSCNNConvolutionGradientState and call [MPSCNNConvolution reloadWeightsAndBiasesWithCommandBuffer] with resulting updated
/// MTLBuffer. If application does not want to keep a copy of weights/biases, it can call [MPSCNNConvolution exportWeightsAndBiasesWithCommandBuffer:] to get
/// the current weights from convolution itself, do the updated and call reloadWithCommandBuffer.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutionweightsandbiasesstate?language=objc)
#[unsafe(super(MPSState, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
pub struct MPSCNNConvolutionWeightsAndBiasesState;
);
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionWeightsAndBiasesState {}
);
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
impl MPSCNNConvolutionWeightsAndBiasesState {
extern_methods!(
/// A buffer that contains the weights.
/// Each value in the buffer is a float. The layout of the weights with respect to the weights is the same as
/// the weights layout provided by data source i.e. it can be interpreted as 4D array
///
/// weights[outputFeatureChannels][kernelHeight][kernelWidth][inputFeatureChannels/groups]
/// for regular convolution. For depthwise convolution
/// weights[outputFeatureChannels][kernelHeight][kernelWidth] as we currently only support channel multiplier of 1.
#[unsafe(method(weights))]
#[unsafe(method_family = none)]
pub unsafe fn weights(&self) -> Retained<ProtocolObject<dyn MTLBuffer>>;
/// A buffer that contains the biases. Each value is float and there are ouputFeatureChannels values.
#[unsafe(method(biases))]
#[unsafe(method_family = none)]
pub unsafe fn biases(&self) -> Option<Retained<ProtocolObject<dyn MTLBuffer>>>;
/// Offset at which weights start in weights buffer
/// Default value is 0.
#[unsafe(method(weightsOffset))]
#[unsafe(method_family = none)]
pub unsafe fn weightsOffset(&self) -> NSUInteger;
/// Offset at which weights start in biases buffer
/// Default value is 0.
#[unsafe(method(biasesOffset))]
#[unsafe(method_family = none)]
pub unsafe fn biasesOffset(&self) -> NSUInteger;
/// Create and initialize MPSCNNConvolutionWeightsAndBiasesState with application
/// provided weights and biases buffers.
///
/// This is the convinience API when buffers of exact size i.e.
/// [weights length] = inputFeatureChannels*kernelWidth*kernelHeight*channelMultiplier*sizeof(float) // for depthwise convolution
/// outputFeatureChannels*kernelWidth*kernelHeight*(inputChannels/groups)*sizeof(float) // for regular otherwise
/// and [biases length] = outputFeatureChannels*sizeof(float)
///
/// # Safety
///
/// - `weights` may need to be synchronized.
/// - `weights` may be unretained, you must ensure it is kept alive while in use.
/// - `weights` contents should be of the correct type.
/// - `biases` may need to be synchronized.
/// - `biases` may be unretained, you must ensure it is kept alive while in use.
/// - `biases` contents should be of the correct type.
#[unsafe(method(initWithWeights:biases:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithWeights_biases(
this: Allocated<Self>,
weights: &ProtocolObject<dyn MTLBuffer>,
biases: Option<&ProtocolObject<dyn MTLBuffer>>,
) -> Retained<Self>;
/// Create and initialize MPSCNNConvolutionWeightsAndBiasesState with application provided convolution descriptor
///
/// Create weights and biases buffers of appropriate size
#[unsafe(method(initWithDevice:cnnConvolutionDescriptor:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_cnnConvolutionDescriptor(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
descriptor: &MPSCNNConvolutionDescriptor,
) -> Retained<Self>;
/// Create and initialize temporary MPSCNNConvolutionWeightsAndBiasesState with application provided convolution descriptor
///
/// Create weights and biases buffers of appropriate size from command buffer cache.
#[unsafe(method(temporaryCNNConvolutionWeightsAndBiasesStateWithCommandBuffer:cnnConvolutionDescriptor:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryCNNConvolutionWeightsAndBiasesStateWithCommandBuffer_cnnConvolutionDescriptor(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
descriptor: &MPSCNNConvolutionDescriptor,
) -> Retained<Self>;
/// Create and initialize MPSCNNConvolutionWeightsAndBiasesState with application
/// provided weights and biases buffers.
///
/// It gives finer allocation control to application e.g. application can pass same buffer for weights and biases with
/// appropriate offsets. Or offset into some larger buffer from application managed heap etc. Number of weights
/// and biases or the length of weights and biases buffer this object owns (will read or write to), starting at offset is
/// determined by MPSCNNConvolutionDescriptor passed in.
/// weightsLength = inputFeatureChannels*kernelWidth*kernelHeight*channelMultiplier*sizeof(float) // for depthwise convolution
/// outputFeatureChannels*kernelWidth*kernelHeight*(inputChannels/groups)*sizeof(float) // for regular otherwise
/// biasesLength = outputFeatureChannels*sizeof(float)
/// Thus filters operating on this object will read or write to NSRange(weightsOffset, weightsLength) of weights buffer
/// and NSRange(biasesOffset, biasesLength) of biases buffer. Thus sizes of buffers provided must be such that
/// weightsOffset + weightsLength
/// <
/// = [weights length]
/// and biasesOffset + biasesLength
/// <
/// = [biases length]
/// Offsets must of sizeof(float) aligned i.e. multiple of 4.
///
/// # Safety
///
/// - `weights` may need to be synchronized.
/// - `weights` may be unretained, you must ensure it is kept alive while in use.
/// - `weights` contents should be of the correct type.
/// - `biases` may need to be synchronized.
/// - `biases` may be unretained, you must ensure it is kept alive while in use.
/// - `biases` contents should be of the correct type.
#[unsafe(method(initWithWeights:weightsOffset:biases:biasesOffset:cnnConvolutionDescriptor:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithWeights_weightsOffset_biases_biasesOffset_cnnConvolutionDescriptor(
this: Allocated<Self>,
weights: &ProtocolObject<dyn MTLBuffer>,
weights_offset: NSUInteger,
biases: Option<&ProtocolObject<dyn MTLBuffer>>,
biases_offset: NSUInteger,
descriptor: &MPSCNNConvolutionDescriptor,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `MPSState`.
#[cfg(all(feature = "MPSCore", feature = "MPSState"))]
impl MPSCNNConvolutionWeightsAndBiasesState {
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>;
#[unsafe(method(init))]
#[unsafe(method_family = init)]
pub unsafe fn init(this: Allocated<Self>) -> Option<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 MPSCNNConvolutionWeightsAndBiasesState {
extern_methods!(
#[unsafe(method(new))]
#[unsafe(method_family = new)]
pub unsafe fn new() -> Retained<Self>;
);
}
extern_protocol!(
/// Provides convolution filter weights and bias terms
///
/// The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNConvolution uses to obtain the weights and bias terms
/// for the CNN convolution filter.
///
/// Why? CNN weights can be large. If multiple copies of all the weights
/// for all the convolutions are available unpacked in memory at the same
/// time, some devices can run out of memory. The MPSCNNConvolutionDataSource
/// is used to encapsulate a reference to the weights such as a file path,
/// so that unpacking can be deferred until needed, then purged soon thereafter
/// so that not all of the data must be in memory at the same time.
/// MPS does not provide a class that conforms to this protocol. It is up to
/// the developer to craft his own to encapsulate his data.
///
/// Batch normalization and the neuron activation function are handled using the
/// -descriptor method.
///
/// Thread safety: The MPSCNNConvolutionDataSource object can be called by
/// threads that are not the main thread. If you will be creating multiple
/// MPSNNGraph objects concurrently in multiple threads and these share
/// MPSCNNConvolutionDataSources, then the data source objects may be called
/// reentrantly.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiondatasource?language=objc)
pub unsafe trait MPSCNNConvolutionDataSource: NSCopying + NSObjectProtocol {
#[cfg(all(feature = "MPSCore", feature = "MPSCoreTypes"))]
/// Alerts MPS what sort of weights are provided by the object
///
/// For MPSCNNConvolution, MPSDataTypeUInt8, MPSDataTypeFloat16
/// and MPSDataTypeFloat32 are supported for normal convolutions
/// using MPSCNNConvolution. MPSCNNBinaryConvolution assumes weights to be
/// of type MPSDataTypeUInt32 always.
#[unsafe(method(dataType))]
#[unsafe(method_family = none)]
unsafe fn dataType(&self) -> MPSDataType;
/// Return a MPSCNNConvolutionDescriptor as needed
///
/// MPS will not modify this object other than perhaps to retain it.
/// User should set the appropriate neuron in the creation of convolution descriptor
/// and for batch normalization use:
///
/// ```text
///
/// -setBatchNormalizationParametersForInferenceWithMean:variance:gamma:beta:epsilon:
/// ```
///
///
/// Returns: A MPSCNNConvolutionDescriptor that describes the kernel housed by this object.
#[unsafe(method(descriptor))]
#[unsafe(method_family = none)]
unsafe fn descriptor(&self) -> Retained<MPSCNNConvolutionDescriptor>;
/// Returns a pointer to the weights for the convolution.
///
/// The type of each entry in array is given by -dataType. The number
/// of entries is equal to:
///
/// ```text
/// inputFeatureChannels * outputFeatureChannels * kernelHeight * kernelWidth
/// ```
///
/// The layout of filter weight is as a 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ inputChannels / groups ]
///
/// Frequently, this function is a single line of code to return
/// a pointer to memory allocated in -load.
///
/// Batch normalization parameters are set using -descriptor.
///
/// Note: For binary-convolutions the layout of the weights are:
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ floor((inputChannels/groups)+31) / 32 ]
/// with each 32 sub input feature channel index specified in machine byte order, so that for example
/// the 13th feature channel bit can be extracted using bitmask = (1U
/// <
/// <
/// 13).
#[unsafe(method(weights))]
#[unsafe(method_family = none)]
unsafe fn weights(&self) -> NonNull<c_void>;
/// Returns a pointer to the bias terms for the convolution.
///
/// Each entry in the array is a single precision IEEE-754 float
/// and represents one bias. The number of entries is equal
/// to outputFeatureChannels.
///
/// Frequently, this function is a single line of code to return
/// a pointer to memory allocated in -load. It may also just
/// return nil.
///
/// Note: bias terms are always float, even when the weights are not.
#[unsafe(method(biasTerms))]
#[unsafe(method_family = none)]
unsafe fn biasTerms(&self) -> *mut c_float;
/// Alerts the data source that the data will be needed soon
///
/// Each load alert will be balanced by a purge later, when MPS
/// no longer needs the data from this object.
/// Load will always be called atleast once after initial construction
/// or each purge of the object before anything else is called.
/// Note: load may be called to merely inspect the descriptor.
/// In some circumstances, it may be worthwhile to postpone
/// weight and bias construction until they are actually needed
/// to save touching memory and keep the working set small.
/// The load function is intended to be an opportunity to open
/// files or mark memory no longer purgeable.
///
/// Returns: Returns YES on success. If NO is returned, expect MPS
/// object construction to fail.
#[unsafe(method(load))]
#[unsafe(method_family = none)]
unsafe fn load(&self) -> bool;
/// Alerts the data source that the data is no longer needed
///
/// Each load alert will be balanced by a purge later, when MPS
/// no longer needs the data from this object.
#[unsafe(method(purge))]
#[unsafe(method_family = none)]
unsafe fn purge(&self);
/// A label that is transferred to the convolution at init time
///
/// Overridden by a MPSCNNConvolutionNode.label if it is non-nil.
#[unsafe(method(label))]
#[unsafe(method_family = none)]
unsafe fn label(&self) -> Option<Retained<NSString>>;
/// A pointer to a 256 entry lookup table containing the values to use for the weight range [0,255]
#[optional]
#[unsafe(method(lookupTableForUInt8Kernel))]
#[unsafe(method_family = none)]
unsafe fn lookupTableForUInt8Kernel(&self) -> NonNull<c_float>;
/// Quantizaiton type of weights. If it returns MPSCNNWeightsQuantizationTypeLookupTable,
/// lookupTableForUInt8Kernel method must be implmented. if it returns MPSCNNWeightsQuantizationTypeLookupLinear,
/// rangesForUInt8Kernel method must be implemented.
#[optional]
#[unsafe(method(weightsQuantizationType))]
#[unsafe(method_family = none)]
unsafe fn weightsQuantizationType(&self) -> MPSCNNWeightsQuantizationType;
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
/// Callback for the MPSNNGraph to update the convolution weights on GPU.
///
/// It is the resposibility of this method to decrement the read count of both the gradientState
/// and the sourceState before returning. BUG: prior to macOS 10.14, ios/tvos 12.0, the MPSNNGraph
/// incorrectly decrements the readcount of the gradientState after this method is called.
///
///
/// Parameter `commandBuffer`: The command buffer on which to do the update.
/// MPSCNNConvolutionGradientNode.MPSNNTrainingStyle controls where you want your update
/// to happen. Provide implementation of this function for GPU side update.
///
/// Parameter `gradientState`: A state object produced by the MPSCNNConvolution and updated by MPSCNNConvolutionGradient
/// containing weight gradients.
///
/// Parameter `sourceState`: A state object containing the convolution weights
///
/// Returns: If NULL, no update occurs. If nonnull, the result will be used to update the
/// weights in the MPSNNGraph
#[optional]
#[unsafe(method(updateWithCommandBuffer:gradientState:sourceState:))]
#[unsafe(method_family = none)]
unsafe fn updateWithCommandBuffer_gradientState_sourceState(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
gradient_state: &MPSCNNConvolutionGradientState,
source_state: &MPSCNNConvolutionWeightsAndBiasesState,
) -> Option<Retained<MPSCNNConvolutionWeightsAndBiasesState>>;
#[cfg(all(
feature = "MPSCore",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
/// Callback for the MPSNNGraph to update the convolution weights on CPU.
/// MPSCNNConvolutionGradientNode.MPSNNTrainingStyle controls where you want your update
/// to happen. Provide implementation of this function for CPU side update.
///
/// Parameter `gradientState`: A state object produced by the MPSCNNConvolution and updated by MPSCNNConvolutionGradient
/// containing weight gradients. MPSNNGraph is responsible for calling [gradientState synchronizeOnCommandBuffer:]
/// so that application get correct gradients for CPU side update.
///
/// Parameter `sourceState`: A state object containing the convolution weights used. MPSCNNConvolution and MPSCNNConvolutionGradient reloadWeightsWithDataSource
/// will be called right after this method is called. Note that the weights returned here may not match the weights
/// in your data source due to conversion loss. These are the weights actually used, and should
/// be what you use to calculate the new weights. Your copy may be incorrect. Write the new weights
/// to your copy and return them out the left hand side.
///
/// Returns: TRUE if success/no error, FALSE in case of failure.
#[optional]
#[unsafe(method(updateWithGradientState:sourceState:))]
#[unsafe(method_family = none)]
unsafe fn updateWithGradientState_sourceState(
&self,
gradient_state: &MPSCNNConvolutionGradientState,
source_state: &MPSCNNConvolutionWeightsAndBiasesState,
) -> bool;
/// When copyWithZone:device on convolution is called, data source copyWithZone:device
/// will be called if data source object responds to this selector. If not, copyWithZone:
/// will be called if data source responds to it. Otherwise, it is simply retained.
/// This is to allow application to make a separate copy of data source in convolution
/// when convolution itself is coplied, for example when copying training graph for running
/// on second GPU so that weights update on two different GPUs dont end up stomping same
/// data source.
///
/// # Safety
///
/// `zone` must be a valid pointer or null.
#[optional]
#[unsafe(method(copyWithZone:device:))]
#[unsafe(method_family = copy)]
unsafe fn copyWithZone_device(
&self,
zone: *mut NSZone,
device: Option<&ProtocolObject<dyn MTLDevice>>,
) -> Retained<Self>;
/// Layout of weights returned by data source. Currently only OHWI layout is supported which is default.
/// See MPSCNNConvolutionWeightsLayout above.
#[optional]
#[unsafe(method(weightsLayout))]
#[unsafe(method_family = none)]
unsafe fn weightsLayout(&self) -> MPSCNNConvolutionWeightsLayout;
#[cfg(all(feature = "MPSCore", feature = "MPSCoreTypes"))]
/// Alerts MPS what weight precision to use in the CNNConvolution kernel
///
/// If precision of weights returned by dataType does not match precision returned by
/// kernelWeightsDataType, weights are converted to precision specified by kernelWeightsDataType
/// before being passed to kernel.
/// For MPSCNNConvolution, dataType precisions of MPSDataTypeUInt8 or MPSDataTypeFloat16
/// must return a kernelWeightsDataType of MPSDataTypeFloat16. dataType precisions of
/// MPSDataTypeFloat32 may return kernelWeightsDataType of MPSDataTypeFloat16 or
/// MPSDataTypeFloat32. When kernelWeightsDataType returns MPSDataTypeFloat32 the
/// accumulatorPrecisionOption on the CNNConvolution object must be set to
/// MPSNNConvolutionAccumulatorPrecisionOptionFloat.
/// When kernelWeightsDataType is unimplemented the kernel will use float16 precision.
/// MPSCNNBinaryConvolution assumes weights to be of type MPSDataTypeUInt32 always,
/// and the kernelWeightsDataType is unused.
#[optional]
#[unsafe(method(kernelWeightsDataType))]
#[unsafe(method_family = none)]
unsafe fn kernelWeightsDataType(&self) -> MPSDataType;
}
);
extern_class!(
/// Dependencies: This depends on Metal.framework
///
/// The MPSCNNConvolution specifies a convolution.
/// The MPSCNNConvolution convolves the input image with a set of filters, each producing one feature map in the output image.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolution?language=objc)
#[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNConvolution;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNConvolution {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolution {
extern_methods!(
/// The number of feature channels per pixel in the input image.
#[unsafe(method(inputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn inputFeatureChannels(&self) -> NSUInteger;
/// The number of feature channels per pixel in the output image.
#[unsafe(method(outputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn outputFeatureChannels(&self) -> NSUInteger;
/// Number of groups input and output channels are divided into.
#[unsafe(method(groups))]
#[unsafe(method_family = none)]
pub unsafe fn groups(&self) -> NSUInteger;
/// dataSource with which convolution object was created
#[unsafe(method(dataSource))]
#[unsafe(method_family = none)]
pub unsafe fn dataSource(
&self,
) -> Retained<ProtocolObject<dyn MPSCNNConvolutionDataSource>>;
/// Sub pixel scale factor which was passed in as part of MPSCNNConvolutionDescriptor when creating this MPSCNNConvolution object.
#[unsafe(method(subPixelScaleFactor))]
#[unsafe(method_family = none)]
pub unsafe fn subPixelScaleFactor(&self) -> NSUInteger;
#[cfg(feature = "MPSCNNNeuron")]
/// MPSCNNNeuron filter to be applied as part of convolution.
/// Can be nil in wich case no neuron activation fuction is applied.
#[deprecated]
#[unsafe(method(neuron))]
#[unsafe(method_family = none)]
pub unsafe fn neuron(&self) -> Option<Retained<MPSCNNNeuron>>;
#[cfg(feature = "MPSCNNNeuronType")]
/// The type of neuron to append to the convolution
///
/// Please see class description for a full list. Default is MPSCNNNeuronTypeNone.
#[deprecated]
#[unsafe(method(neuronType))]
#[unsafe(method_family = none)]
pub unsafe fn neuronType(&self) -> MPSCNNNeuronType;
/// Parameter "a" for the neuron. Default: 1.0f
///
/// Please see class description for interpretation of a.
#[deprecated]
#[unsafe(method(neuronParameterA))]
#[unsafe(method_family = none)]
pub unsafe fn neuronParameterA(&self) -> c_float;
/// Parameter "b" for the neuron. Default: 1.0f
///
/// Please see class description for interpretation of b.
#[deprecated]
#[unsafe(method(neuronParameterB))]
#[unsafe(method_family = none)]
pub unsafe fn neuronParameterB(&self) -> c_float;
/// Parameter "c" for the neuron. Default: 1.0f
///
/// Please see class description for interpretation of c.
#[deprecated]
#[unsafe(method(neuronParameterC))]
#[unsafe(method_family = none)]
pub unsafe fn neuronParameterC(&self) -> c_float;
#[cfg(feature = "MPSCNNNeuron")]
/// Fused neuron descritor passed in convolution descriptor for fusion with convolution.
///
/// Please see class description for interpretation of c.
#[unsafe(method(fusedNeuronDescriptor))]
#[unsafe(method_family = none)]
pub unsafe fn fusedNeuronDescriptor(&self) -> Option<Retained<MPSNNNeuronDescriptor>>;
/// Channel multiplier.
///
/// For convolution created with MPSCNNDepthWiseConvolutionDescriptor, it is the number of
/// output feature channels for each input channel. See MPSCNNDepthWiseConvolutionDescriptor for more details.
/// Default is 0 which means regular CNN convolution.
#[unsafe(method(channelMultiplier))]
#[unsafe(method_family = none)]
pub unsafe fn channelMultiplier(&self) -> NSUInteger;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Precision of accumulator used in convolution.
///
/// See MPSNeuralNetworkTypes.h for discussion. Default is MPSNNConvolutionAccumulatorPrecisionOptionFloat.
#[unsafe(method(accumulatorPrecisionOption))]
#[unsafe(method_family = none)]
pub unsafe fn accumulatorPrecisionOption(
&self,
) -> MPSNNConvolutionAccumulatorPrecisionOption;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Setter for [`accumulatorPrecisionOption`][Self::accumulatorPrecisionOption].
#[unsafe(method(setAccumulatorPrecisionOption:))]
#[unsafe(method_family = none)]
pub unsafe fn setAccumulatorPrecisionOption(
&self,
accumulator_precision_option: MPSNNConvolutionAccumulatorPrecisionOption,
);
/// Initializes a convolution kernel
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolution filter will be used
///
/// Parameter `weights`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource
/// protocol. The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNConvolution uses to obtain the weights and bias terms
/// for the CNN convolution filter.
///
///
/// Returns: A valid MPSCNNConvolution object or nil, if failure.
#[unsafe(method(initWithDevice:weights:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_weights(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
weights: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
) -> Retained<Self>;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Initializes a convolution kernel
/// WARNING: This API is depreated and will be removed in the future. It cannot be used
/// when training. Also serialization/unserialization wont work for MPSCNNConvolution
/// objects created with this init. Please move onto using initWithDevice:weights:.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolution filter will be used
///
/// Parameter `convolutionDescriptor`: A pointer to a MPSCNNConvolutionDescriptor.
///
/// Parameter `kernelWeights`: A pointer to a weights array. Each entry is a float value. The number of entries is =
/// inputFeatureChannels * outputFeatureChannels * kernelHeight * kernelWidth
/// The layout of filter weight is so that it can be reinterpreted as 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ inputChannels / groups ]
/// Weights are converted to half float (fp16) internally for best performance.
///
/// Parameter `biasTerms`: A pointer to bias terms to be applied to the convolution output. Each entry is a float value.
/// The number of entries is = numberOfOutputFeatureMaps
///
/// Parameter `flags`: Currently unused. Pass MPSCNNConvolutionFlagsNone
///
///
/// Returns: A valid MPSCNNConvolution object or nil, if failure.
///
/// # Safety
///
/// - `kernel_weights` must be a valid pointer.
/// - `bias_terms` must be a valid pointer or null.
#[deprecated]
#[unsafe(method(initWithDevice:convolutionDescriptor:kernelWeights:biasTerms:flags:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_convolutionDescriptor_kernelWeights_biasTerms_flags(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
convolution_descriptor: &MPSCNNConvolutionDescriptor,
kernel_weights: NonNull<c_float>,
bias_terms: *const c_float,
flags: MPSCNNConvolutionFlags,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
/// Allocate a MPCNNConvolutionGradientSState to hold the results from a -encodeBatchToCommandBuffer... operation
///
///
/// Parameter `sourceImage`: The MPSImage consumed by the associated -encode call.
///
/// Parameter `sourceStates`: The list of MPSStates consumed by the associated -encode call,
/// for a batch size of 1.
///
/// Returns: The list of states produced by the -encode call for batch size of 1.
/// -isResultStateReusedAcrossBatch returns YES for MPSCNNConvolution so same
/// state is used across entire batch. State object is not reusasable across batches.
#[unsafe(method(resultStateForSourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn resultStateForSourceImage_sourceStates_destinationImage(
&self,
source_image: &MPSImage,
source_states: Option<&NSArray<MPSState>>,
destination_image: &MPSImage,
) -> Option<Retained<MPSCNNConvolutionGradientState>>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(resultStateBatchForSourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn resultStateBatchForSourceImage_sourceStates_destinationImage(
&self,
source_image: &MPSImageBatch,
source_states: Option<&NSArray<MPSStateBatch>>,
destination_image: &MPSImageBatch,
) -> Option<Retained<MPSCNNConvolutionGradientStateBatch>>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(temporaryResultStateForCommandBuffer:sourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryResultStateForCommandBuffer_sourceImage_sourceStates_destinationImage(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImage,
source_states: Option<&NSArray<MPSState>>,
destination_image: &MPSImage,
) -> Option<Retained<MPSCNNConvolutionGradientState>>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(temporaryResultStateBatchForCommandBuffer:sourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryResultStateBatchForCommandBuffer_sourceImage_sourceStates_destinationImage(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImageBatch,
source_states: Option<&NSArray<MPSStateBatch>>,
destination_image: &MPSImageBatch,
) -> Option<Retained<MPSCNNConvolutionGradientStateBatch>>;
/// CPU side reload. Reload the updated weights and biases from data provider into internal weights and bias buffers. Weights and biases
/// gradients needed for update are obtained from MPSCNNConvolutionGradientState object. Data provider passed in init call is used for this purpose.
#[unsafe(method(reloadWeightsAndBiasesFromDataSource))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesFromDataSource(&self);
/// Deprecated. dataSource will be ignored.
#[deprecated]
#[unsafe(method(reloadWeightsAndBiasesWithDataSource:))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesWithDataSource(
&self,
data_source: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
);
#[cfg(feature = "MPSState")]
/// GPU side reload. Reload the updated weights and biases from update buffer produced by application enqueued metal kernel into internal weights
/// and biases buffer. Weights and biases gradients needed for update are obtained from MPSCNNConvolutionGradientState object's gradientForWeights and gradientForBiases metal buffer.
///
///
/// Parameter `commandBuffer`: Metal command buffer on which application update kernel was enqueued consuming MPSCNNConvolutionGradientState's gradientForWeights and gradientForBiases buffers
/// and producing updateBuffer metal buffer.
///
/// Parameter `state`: MPSCNNConvolutionWeightsAndBiasesState containing weights and biases buffers which have updated weights produced by application's update kernel.
/// The state readcount will be decremented.
#[unsafe(method(reloadWeightsAndBiasesWithCommandBuffer:state:))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesWithCommandBuffer_state(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
state: &MPSCNNConvolutionWeightsAndBiasesState,
);
#[cfg(feature = "MPSState")]
/// GPU side export. Enqueue a kernel to export current weights and biases stored in MPSCNNConvoltion's internal buffers into weights and biases MTLBuffer
/// returned in MPSCNNConvolutionWeightsAndBiasesState.
///
///
/// Parameter `commandBuffer`: Metal command buffer on which export kernel is enqueued.
///
/// Parameter `resultStateCanBeTemporary`: If FALSE, state returned will be non-temporary. If TRUE, returned state may or may not be temporary.
///
/// Returns: MPSCNNConvolutionWeightsAndBiasesState containing weights and biases buffer to which weights got exported. This state and be
/// temporary or non-temporary depending on the flag resultStateCanBeTemporary
#[unsafe(method(exportWeightsAndBiasesWithCommandBuffer:resultStateCanBeTemporary:))]
#[unsafe(method_family = none)]
pub unsafe fn exportWeightsAndBiasesWithCommandBuffer_resultStateCanBeTemporary(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
result_state_can_be_temporary: bool,
) -> Retained<MPSCNNConvolutionWeightsAndBiasesState>;
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolution {
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 MPSCNNConvolution {
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>;
);
}
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiongradientoption?language=objc)
// NS_OPTIONS
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MPSCNNConvolutionGradientOption(pub NSUInteger);
bitflags::bitflags! {
impl MPSCNNConvolutionGradientOption: NSUInteger {
#[doc(alias = "MPSCNNConvolutionGradientOptionGradientWithData")]
const GradientWithData = 1;
#[doc(alias = "MPSCNNConvolutionGradientOptionGradientWithWeightsAndBias")]
const GradientWithWeightsAndBias = 2;
#[doc(alias = "MPSCNNConvolutionGradientOptionAll")]
const All = MPSCNNConvolutionGradientOption::GradientWithData.0|MPSCNNConvolutionGradientOption::GradientWithWeightsAndBias.0;
}
}
unsafe impl Encode for MPSCNNConvolutionGradientOption {
const ENCODING: Encoding = NSUInteger::ENCODING;
}
unsafe impl RefEncode for MPSCNNConvolutionGradientOption {
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
extern_class!(
/// Dependencies: This depends on Metal.framework
///
/// The MPSCNNConvolutionGradient implementents backward propagation of gradient i.e. it computes the gradient of loss function
/// with respect input data of corresonding forward convolution and gradient of loss function with respect to weights and bias
/// of corresponding convolution in forward pass.
///
/// Gradient with respect to data
/// ==============================
/// Gradient with respect to input data of corresponding forward convolution will be written in destination image passed to
/// encode call of MPSCNNConvolutionGradient.
/// This step is similar to convolution transpose in that the strided convolution in forward pass become zero filled convolution in
/// backward propagation of gradients. The difference between MPSCNNConvolutionTranspose and gradient wrt data is how the
/// weights, that are provided by data source, are interpreted. MPSCNNConvolution and MPSCNNConvolutionTranspose interpret weights
/// provided by data source as
/// weights[outputFeatureChannels][kernelWidth][kernelHeight][inputFeatureChannels]
/// whereas convoution gradient with respect to data interpret the weights as
/// weights[inputFeatureChannels][kernelWidth][kernelHeight][outputFeatureChannels]
/// i.e. weights are transposed in inputFeatureChannels/outputFeatureChannels dimension and also rotated 180 degress in spatial dimension
///
/// User should use the same data source provider to initialize MPSCNNConvolutionGradient as is used to initialize corresponding
/// forward MPSCNNConvolution. Implementation will do the transposition/shuffling needed.
/// Thus, while the forward MPSCNNConvolution takes sourceImage of inputFeatureChannels and convolves it with
/// Wt[outputFeatureChannels][kernelHeight][kernelWidth][inputFeatureChannels] to produce destinationImage of outputFeatureChannels,
/// MPSConvolutionGradient takes sourceGradient of outputFeatureChannels which is out of previous layer (nomally neuron backward layer),
/// convolves it with transposed and rotated weights and produces destinationGradient of inputFeatureChannels.
/// If the user decide to double buffer data source provider i.e. different data source providers are passed to forward MPSCNNConvolution object and
/// corresponding MPSCNNConvolutionGradient object, it is user responsibility to make sure both data source providers provide same weights/bias data
/// and have same properties in convolution descriptor else behavior is undefined.
///
/// Gradient with respect to weights and bias
/// =========================================
/// Gradient with respect to weights and bias are returned in MPSCNNConvolutionGradientState object to be used in weights update functions.
/// If I denotes the input image to corresponding MPSCNNConvolution in forward pass and E denoates the loss gradient from previous layer
/// (normally neuron backward layer) in backward pass, gradient of E with respect to weights is
///
/// delta_E/delta_Wkpqc = sum_i sum_j [ E(i, j, k) * I( secondaryStrideInPixelX*i + secondaryOffset.x + secondaryDilationRateX*p,
/// secondaryStrideinPixelY*i + secondaryOffset.y + secondaryDilationRateY*q, c) ]
///
/// where i goes over 0..W-1 and j goes over 0..H-1, (W,H) being width and height of E.
/// p in [0, secondaryKernelWidth-1]
/// q in [0, secondaryKernelHeight-1]
/// c in [0, inputeFeatureChannels/groups - 1]
/// k in [0, outputFeatureChannels]
///
/// and gradient with respect to bias
///
/// delta_E/delta_bk = sum_i sum_j [ E(i, j, k) ]
///
/// These gradients with respect to weights and bias are returned as buffers in MPSCNNConvolutionGradientState object passed in the encode call.
/// These are consumed by MPSCNNConvolution object's -updateWeightsAndBias:MPSCNNConvolutionGradientState* method for CPU side update and
/// encodeWeightsAndBiasUpdate:commandBuffer:MPSCNNConvolutionGradientState* method of MPSCNNConvolution object for GPU side update.
/// UPdated weights and biases are computed as
///
/// Wkpqc_new = Wkpqc_old + delta_E/delta_Wkpqc
/// bk_new = bk_old + delta_E/delta_bk
///
/// Note that MPSCNNConvolutionGradientState objects's buffers that contain gradients, for CPU side update, will only contain
/// valid data after command buffer is complete so
/// its only makes sense to call -updateWeightsAndBias method on MPSCNNConvolution objects after command bufer is
/// complete. One can achieve this by enqueueing a command buffer completion handler block that make this call.
/// Since MPSCNNConvolutionGradientState is used across command buffers i.e. its created in forward pass, consumed by MPSCNNConvolutionGradient in backward pass in same command buffer and passed onto MPSCNNConvolution updateWeightsAndBias method
/// after completion of command buffer, it cannot be a temporary state.
///
/// In order to gaurantee consistency between forward pass (MPSCNNConvolution) and weights gradient computation in this filter, certain requirements
/// must be met.
/// 1) Dimensions of loss gradient E from previous layer in backward pass must be equal to clipRect.size of corresponding MPSCNNConvolution in forward pass.
/// This is to gaurantee that only those pixels for which weights/bias contributed in destination of forward pass end up contributing to weights/bias gradient update.
/// If the dimension of loss gradient E from previous layer is not equal to clipRect.size of corresponding forward MPSCNNConvolution,
/// i) one can insert a slice operation to extract out the region of size clipRect.size from appropriate offset in E and set primaryOffset = 0 Or
/// ii) set primatryOffset to offset in E at which valid data starts and make sure data outside is zeroed.
/// 2) secondaryOffset should be set to what offset property of MPSCNNConvolution was set to in forward pass.
///
/// Currently back propagation for gradients is only supported for regualar convolution and depthwise convolution. Back propagation
/// sub-pixel convolution are not supported. So channelMultiplier and subPixelScaleFactor must be one.
///
/// Note on setting correct offsets
/// ===============================
/// If the forward convolution is called with
/// offset = _offset; kernelWidth = kW; kernelHeight = kH; strideInPixelsX = sX; strideInPixelsY = sY;
/// dilationRateX = dX; dilationRateY = dY;
/// thus dilated filter parameters are
/// kW_Dilated = (kW - 1)*dX + 1; kH_Dilated = (kH - 1)*dY + 1;
/// Then the correct offset can be computed as follows.
/// Convoluton Gradient with Data
/// =============================
/// Convolution gradient with data of forward convolution with stride > 1 is essentially normal convoution with unit stride,
/// on an image that is formed by inserting strideInPixelsX-1 zeros in between each column and strideInPixelsY-1 zeros in between each
/// row of input gradient (output gradient of last layer) with kernel weights that are rotated by 180 degrees in spatial dimension (MPSCNNConvolutionGradient
/// does this rotation internally). primaryOffset property defines offset in original input gradient coordinate system. In order to
/// translate it in zero filled intermediate image coordinate system, kernelOffsetX and kernelOffsetY properties can be used as follows
/// offsetInZeroFilledImageX = primaryOffset.x * primaryStrideInPixelsX + kernelOffsetX;
/// offsetInZeroFilledImageY = primaryOffset.y * primaryStrideInPixelsY + kernelOffsetY;
/// This is what internally MPSCNNConvolutionGradient do. In order to correctly match forward convolution offset setting (so that padding policy is
/// consistent), application should set
/// primaryOffset.x = 0; primaryOffset.y = 0;
/// kernelOffset.x = -_offset.x + (~(NSInteger) kW_Dilated
/// &
/// 1L);
/// kernelOffset.y = -_offset.y + (~(NSInteger) kH_Dilated
/// &
/// 1L);
/// Convolution gradient with data does not use secondaryOffset.
///
/// Convolution Gradient with Weights and Biases
/// ============================================
/// For consistent padding policy with respect to forward convolution,
/// secondaryOffset.x = _offset.x - kW_Dilated/2
/// secondaryOffset.y = _offset.y - kH_Dilated/2
/// Convolution gradient with weights and biases does not use primaryOffset (or it is assumed to be zero) as summation is over entire
/// gradient image and only gradient image without any padding is currently accepted. If previous layer produces gradient image with
/// padding, slice operation should be used to extract out the gradient which will be input to MPSCNNConvolutionGradient.
///
/// Note that if application uses encode method that return destination gradient on left hand side and consumes MPSCNNConvolutionGradientState
/// object produced by forward MPSCNNConvolution, all these parameters are set automatically for the application i.e. applicaiton does not
/// need to worry about setting these.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiongradient?language=objc)
#[unsafe(super(MPSCNNGradientKernel, MPSCNNBinaryKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNConvolutionGradient;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNConvolutionGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNConvolutionGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNConvolutionGradient {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNConvolutionGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolutionGradient {
extern_methods!(
/// The number of feature channels per pixel in the gradient image (primarySource) of encode call. This is same is outputFeatureChannels
/// or the feature channels of destination image in forward convolution i.e. dataSource.descriptor.outputFeatureChannels
#[unsafe(method(sourceGradientFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn sourceGradientFeatureChannels(&self) -> NSUInteger;
/// The number of feature channels per pixel in the input image to forward convolution which is used here as secondarySource.
/// This is same as dataSource.descriptor.inputFeatureChannels. This is also the number of feature channels in destinatin image
/// here i.e. gradient with respect to data.
#[unsafe(method(sourceImageFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn sourceImageFeatureChannels(&self) -> NSUInteger;
/// Number of groups input and output channels are divided into.
#[unsafe(method(groups))]
#[unsafe(method_family = none)]
pub unsafe fn groups(&self) -> NSUInteger;
/// Channel multiplier.
///
/// For convolution created with MPSCNNDepthWiseConvolutionDescriptor, it is the number of
/// output feature channels for each input channel. See MPSCNNDepthWiseConvolutionDescriptor for more details.
/// Default is 0 which means regular CNN convolution. Currently only channelMultiplier of 1 is supported i.e. inputChannels == outputChannels
#[unsafe(method(channelMultiplier))]
#[unsafe(method_family = none)]
pub unsafe fn channelMultiplier(&self) -> NSUInteger;
/// dataSource with which gradient object was created
#[unsafe(method(dataSource))]
#[unsafe(method_family = none)]
pub unsafe fn dataSource(
&self,
) -> Retained<ProtocolObject<dyn MPSCNNConvolutionDataSource>>;
/// Option to control which gradient to compute. Default is MPSCNNConvolutionGradientOptionAll
/// which means both gradient with respect to data and gradient with respect to weight and bias are computed.
#[unsafe(method(gradientOption))]
#[unsafe(method_family = none)]
pub unsafe fn gradientOption(&self) -> MPSCNNConvolutionGradientOption;
/// Setter for [`gradientOption`][Self::gradientOption].
#[unsafe(method(setGradientOption:))]
#[unsafe(method_family = none)]
pub unsafe fn setGradientOption(&self, gradient_option: MPSCNNConvolutionGradientOption);
/// Property to control serialization of weights and bias.
///
/// During serialization of convolution object in -encodeWithCoder call, weights and biases are saved so that convolution
/// object can be properly unserialized/restored in -initWithCoder call. If data source provied is NSSecureCoding compliant,
/// data source is serialized else weights and biases are serialized.
/// As weights/biases data may be several MB and these are same for both gradient and forward convolution object,
/// application may already have weights/biases on disk through convolution, it can
/// save disk space by setting this property false so convolution gradient object does not end up storing another copy of weights/biases.
/// Default is NO. When application decides to set it to NO, it MUST call
/// -(void) reloadWeightsAndBiasesFromDataSource
/// after initWithCoder has initialized convolution object.
#[deprecated]
#[unsafe(method(serializeWeightsAndBiases))]
#[unsafe(method_family = none)]
pub unsafe fn serializeWeightsAndBiases(&self) -> bool;
/// Setter for [`serializeWeightsAndBiases`][Self::serializeWeightsAndBiases].
#[deprecated]
#[unsafe(method(setSerializeWeightsAndBiases:))]
#[unsafe(method_family = none)]
pub unsafe fn setSerializeWeightsAndBiases(&self, serialize_weights_and_biases: bool);
/// Initializes a convolution gradient (with respect to weights and bias) object.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolutionGradient filter will be used
///
/// Parameter `weights`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource
/// protocol. Note that same data source as provided to forward convolution should be used.
///
///
/// Returns: A valid MPSCNNConvolutionGradient object or nil, if failure.
#[unsafe(method(initWithDevice:weights:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_weights(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
weights: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
/// CPU side reload. Reload the updated weights and biases from data provider into internal weights and bias buffers. Weights and biases
/// gradients needed for update are obtained from MPSCNNConvolutionGradientState object. Data provider passed in init call is used for this purpose.
#[unsafe(method(reloadWeightsAndBiasesFromDataSource))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesFromDataSource(&self);
#[cfg(feature = "MPSState")]
/// GPU side reload. Reload the updated weights and biases from update buffer produced by application enqueued metal kernel into internal weights
/// and biases buffer. Weights and biases gradients needed for update are obtained from MPSCNNConvolutionGradientState object's gradientForWeights and gradientForBiases metal buffer.
///
///
/// Parameter `commandBuffer`: Metal command buffer on which application update kernel was enqueued consuming MPSCNNConvolutionGradientState's gradientForWeights and gradientForBiases buffer
/// and producing updateBuffer metal buffer.
///
/// Parameter `state`: MPSCNNConvolutionWeightsAndBiasesState containing weights and biases buffers which have updated weights produced by application's update kernel.
#[unsafe(method(reloadWeightsAndBiasesWithCommandBuffer:state:))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesWithCommandBuffer_state(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
state: &MPSCNNConvolutionWeightsAndBiasesState,
);
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolutionGradient {
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 MPSCNNConvolutionGradient {
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 MPSCNNFullyConnected specifies a fully connected convolution layer a.k.a. Inner product
/// layer. A fully connected CNN layer is one where every input channel is connected
/// to every output channel. The kernel width is equal to width of source image
/// and the kernel height is equal to the height of source image. Width and height of the output
/// is 1x1. Thus, it takes a srcW x srcH x Ni MPSCNNImage, convolves it with Weights[No][SrcW][srcH][Ni]
/// and produces a 1 x 1 x No output. The following must be true:
///
/// ```text
/// kernelWidth == source.width
/// kernelHeight == source.height
/// clipRect.size.width == 1
/// clipRect.size.height == 1
/// ```
///
/// One can think of a fully connected layer as a matrix multiplication that flattens an image into a vector of length
/// srcW*srcH*Ni. The weights are arragned in a matrix of dimension No x (srcW*srcH*Ni) for product output vectors
/// of length No. The strideInPixelsX, strideInPixelsY, and group must be 1. Offset is not applicable and is ignored.
/// Since clipRect is clamped to the destination image bounds, if the destination is 1x1, one doesn't need to set the
/// clipRect.
///
/// Note that one can implement an inner product using MPSCNNConvolution by setting
///
/// ```text
/// offset = (kernelWidth/2,kernelHeight/2)
/// clipRect.origin = (ox,oy), clipRect.size = (1,1)
/// strideX = strideY = group = 1
/// ```
///
/// However, using the MPSCNNFullyConnected for this is better for performance as it lets us choose the most
/// performant method which may not be possible when using a general convolution. For example,
/// we may internally use matrix multiplication or special reduction kernels for a specific platform.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnfullyconnected?language=objc)
#[unsafe(super(MPSCNNConvolution, MPSCNNKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNFullyConnected;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNFullyConnected {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNFullyConnected {
extern_methods!(
/// Initializes a fully connected kernel
///
/// Parameter `device`: The MTLDevice on which this MPSCNNFullyConnected filter will be used
///
/// Parameter `weights`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource
/// protocol. The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNFullyConnected uses to obtain the weights and bias terms
/// for the CNN fully connected filter.
///
///
/// Returns: A valid MPSCNNFullyConnected object or nil, if failure.
#[unsafe(method(initWithDevice:weights:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_weights(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
weights: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
) -> Retained<Self>;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Initializes a convolution kernel
/// WARNING: This API is depreated and will be removed in the future. It cannot be used
/// when training. Also serialization/unserialization wont work for MPSCNNConvolution
/// objects created with this init. Please move onto using initWithDevice:weights:.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolution filter will be used
///
/// Parameter `convolutionDescriptor`: A pointer to a MPSCNNConvolutionDescriptor.
///
/// Parameter `kernelWeights`: A pointer to a weights array. Each entry is a float value. The number of entries is =
/// inputFeatureChannels * outputFeatureChannels * kernelHeight * kernelWidth
/// The layout of filter weight is so that it can be reinterpreted as 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ inputChannels / groups ]
/// Weights are converted to half float (fp16) internally for best performance.
///
/// Parameter `biasTerms`: A pointer to bias terms to be applied to the convolution output. Each entry is a float value.
/// The number of entries is = numberOfOutputFeatureMaps
///
/// Parameter `flags`: Currently unused. Pass MPSCNNConvolutionFlagsNone
///
///
/// Returns: A valid MPSCNNConvolution object or nil, if failure.
///
/// # Safety
///
/// - `kernel_weights` must be a valid pointer.
/// - `bias_terms` must be a valid pointer or null.
#[deprecated]
#[unsafe(method(initWithDevice:convolutionDescriptor:kernelWeights:biasTerms:flags:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_convolutionDescriptor_kernelWeights_biasTerms_flags(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
convolution_descriptor: &MPSCNNConvolutionDescriptor,
kernel_weights: NonNull<c_float>,
bias_terms: *const c_float,
flags: MPSCNNConvolutionFlags,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNFullyConnected {
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 MPSCNNFullyConnected {
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
///
/// Compute the gradient for fully connected layer.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnfullyconnectedgradient?language=objc)
#[unsafe(super(
MPSCNNConvolutionGradient,
MPSCNNGradientKernel,
MPSCNNBinaryKernel,
MPSKernel,
NSObject
))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNFullyConnectedGradient;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNFullyConnectedGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNFullyConnectedGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNFullyConnectedGradient {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNFullyConnectedGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNFullyConnectedGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNFullyConnectedGradient {
extern_methods!(
/// Initializes a convolution gradient (with respect to weights and bias) object.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolutionGradient filter will be used
///
/// Parameter `weights`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource
/// protocol. Note that same data source as provided to forward convolution should be used.
///
///
/// Returns: A valid MPSCNNConvolutionGradient object or nil, if failure.
#[unsafe(method(initWithDevice:weights:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_weights(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
weights: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNFullyConnectedGradient {
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 MPSCNNFullyConnectedGradient {
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 MPSCNNConvolutionTranspose specifies a transposed convolution.
/// The MPSCNNConvolutionTranspose convolves the input image with a set of filters, each producing one feature map in the output image.
///
/// Some third-party frameworks may rotate the weights spatially by 180 degrees for Convolution Transpose. MPS uses the weights
/// specified by the developer as-is and does not perform any rotation. The developer may need to rotate the weights appropriately
/// in case this rotation is needed before the convolution transpose is applied.
///
/// When the stride in any dimension is greater than 1, the convolution transpose puts (stride - 1) zeroes in-between the source
/// image pixels to create an expanded image. Then a convolution is done over the expanded image to generate the output of the
/// convolution transpose.
///
/// Intermediate image size = (srcSize - 1) * Stride + 1
///
/// Examples:
///
///
/// ```text
/// So in case of sride == 2 (this behaves same in both dimensions)
///
/// Source image:
/// _______________
/// | | | | |
/// | 1 | 2 | 3 | 4 |
/// | | | | |
/// ---------------
///
/// Intermediate Image:
/// ___________________________
/// | | | | | | | |
/// | 1 | 0 | 2 | 0 | 3 | 0 | 4 |
/// | | | | | | | |
/// ---------------------------
///
///
/// NOTE on Offset:
/// There are 2 types of offsets defined:
/// 1) The Offset defined in MPSCNNKernel from which MPSCNNConvolutionTranspose inherits. This offset is applied to from where
/// the kernel will be applied on the source.
/// 2) The kernelOffsetX and kernelOffsetY which is the offset applied to the kernel when it is finally applied on the intermediate
/// image.
///
/// So totalOffset = Offset * stride + kernelOffset
///
/// The offset defined by user refers to the coordinate frame of the expanded image
/// (we are showing only 1 dimension X it can be extended to Y dimension as well) :
///
/// X indicates where the convolution transpose begins:
///
/// Intermediate Image: Offset = 0, kernelOffset = 0
/// ___________________________
/// | | | | | | | |
/// | 1 | 0 | 2 | 0 | 3 | 0 | 4 |
/// | X | | | | | | |
/// ---------------------------
///
///
/// X indicates where the convolution transpose begins:
///
/// Intermediate Image: Offset = 0, kernelOffset = 1
/// ___________________________
/// | | | | | | | |
/// | 1 | 0 | 2 | 0 | 3 | 0 | 4 |
/// | | X | | | | | |
/// ---------------------------
///
///
/// X indicates where the convolution transpose begins:
///
/// Intermediate Image: Offset = 0, kernelOffset = -1
/// ___________________________
/// | | | | | | | |
/// X | 1 | 0 | 2 | 0 | 3 | 0 | 4 |
/// | | | | | | | |
/// ---------------------------
///
///
///
///
/// So if the user wanted to apply an offset of 2 on the source image of convolution transpose:
///
/// Source image:
/// _______________
/// | | | | |
/// | 1 | 2 | 3 | 4 |
/// | | | X | |
/// ---------------
///
/// offset = 2, kernelOffset = 0
///
/// Intermediate Image:
/// ___________________________
/// | | | | | | | |
/// | 1 | 0 | 2 | 0 | 3 | 0 | 4 |
/// | | | | | X | | |
/// ---------------------------
///
/// ```
///
/// Note that if your application is not using MPSCNNConvolutionGradientState to configure the convolution transpose with respect to convolution,
/// your application may do this using padding policy. In such case if convolution uses valid padding policy, than convolution transpose should use
/// full padding policy and vice vera. Full padding remains full.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiontranspose?language=objc)
#[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNConvolutionTranspose;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNConvolutionTranspose {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNConvolutionTranspose {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNConvolutionTranspose {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionTranspose {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNConvolutionTranspose {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolutionTranspose {
extern_methods!(
/// The number of feature channels per pixel in the input image.
#[unsafe(method(inputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn inputFeatureChannels(&self) -> NSUInteger;
/// The number of feature channels per pixel in the output image.
#[unsafe(method(outputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn outputFeatureChannels(&self) -> NSUInteger;
/// Offset in X from which the kernel starts sliding
#[unsafe(method(kernelOffsetX))]
#[unsafe(method_family = none)]
pub unsafe fn kernelOffsetX(&self) -> NSInteger;
/// Setter for [`kernelOffsetX`][Self::kernelOffsetX].
#[unsafe(method(setKernelOffsetX:))]
#[unsafe(method_family = none)]
pub unsafe fn setKernelOffsetX(&self, kernel_offset_x: NSInteger);
/// Offset in Y from which the kernel starts sliding
#[unsafe(method(kernelOffsetY))]
#[unsafe(method_family = none)]
pub unsafe fn kernelOffsetY(&self) -> NSInteger;
/// Setter for [`kernelOffsetY`][Self::kernelOffsetY].
#[unsafe(method(setKernelOffsetY:))]
#[unsafe(method_family = none)]
pub unsafe fn setKernelOffsetY(&self, kernel_offset_y: NSInteger);
/// Number of groups input and output channels are divided into.
#[unsafe(method(groups))]
#[unsafe(method_family = none)]
pub unsafe fn groups(&self) -> NSUInteger;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Precision of accumulator used in convolution.
///
/// See MPSNeuralNetworkTypes.h for discussion. Default is MPSNNConvolutionAccumulatorPrecisionOptionFloat.
#[unsafe(method(accumulatorPrecisionOption))]
#[unsafe(method_family = none)]
pub unsafe fn accumulatorPrecisionOption(
&self,
) -> MPSNNConvolutionAccumulatorPrecisionOption;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Setter for [`accumulatorPrecisionOption`][Self::accumulatorPrecisionOption].
#[unsafe(method(setAccumulatorPrecisionOption:))]
#[unsafe(method_family = none)]
pub unsafe fn setAccumulatorPrecisionOption(
&self,
accumulator_precision_option: MPSNNConvolutionAccumulatorPrecisionOption,
);
/// dataSource with which convolution transpose object was created
#[unsafe(method(dataSource))]
#[unsafe(method_family = none)]
pub unsafe fn dataSource(
&self,
) -> Retained<ProtocolObject<dyn MPSCNNConvolutionDataSource>>;
/// Initializes a convolution transpose kernel
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolutionTranspose filter will be used
///
/// Parameter `weights`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource
/// protocol. The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNConvolutionTranspose uses to obtain the weights and bias terms
/// for the CNN convolutionTranspose filter. Currently we support only Float32 weights.
///
///
/// Returns: A valid MPSCNNConvolutionTranspose object.
#[unsafe(method(initWithDevice:weights:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_weights(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
weights: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
) -> Retained<Self>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> 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 = "MPSNNGradientState",
feature = "MPSState"
))]
/// Encode a MPSCNNKernel into a command Buffer. Create a texture to hold the result and return it.
///
/// In the first iteration on this method, encodeToCommandBuffer:sourceImage:destinationImage:
/// some work was left for the developer to do in the form of correctly setting the offset property
/// and sizing the result buffer. With the introduction of the padding policy (see padding property)
/// the filter can do this work itself. If you would like to have some input into what sort of MPSImage
/// (e.g. temporary vs. regular) or what size it is or where it is allocated, you may set the
/// destinationImageAllocator to allocate the image yourself.
///
/// This method uses the MPSNNPadding padding property to figure out how to size
/// the result image and to set the offset property. See discussion in MPSNeuralNetworkTypes.h.
///
/// Note: the regular encodeToCommandBuffer:sourceImage: method may be used when no state is needed,
/// such as when the convolution transpose operation is not balanced by a matching convolution object upstream.
/// These encode methods are for auto encoders where each convolution in inference pass is coupled with convolution
/// transpose. In order for convolution transpose to correctly undo the convolution downsampling, MPSCNNConvolutionGradientState
/// produced by convolution is needed by convolution transpose to correctly size destination image.
/// These methods are only useful for inference only network. For training, use encode methods that take MPSCNNConvolutionTransposeGradientState below.
///
///
/// Parameter `commandBuffer`: The command buffer
///
/// Parameter `sourceImage`: A MPSImage to use as the source images for the filter.
///
/// Parameter `convolutionGradientState`: A valid MPSCNNConvolutionGradientState from the MPSCNNConvoluton counterpart to this MPSCNNConvolutionTranspose.
/// If there is no forward convolution counterpart, pass NULL here. This state affects the sizing
/// the result.
///
/// Returns: A MPSImage or MPSTemporaryImage allocated per the destinationImageAllocator containing the output of the graph.
/// The offset property will be adjusted to reflect the offset used during the encode.
/// The returned image will be automatically released when the command buffer completes. If you want to
/// keep it around for longer, retain the image. (ARC will do this for you if you use it later.)
#[unsafe(method(encodeToCommandBuffer:sourceImage:convolutionGradientState:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeToCommandBuffer_sourceImage_convolutionGradientState(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImage,
convolution_gradient_state: Option<&MPSCNNConvolutionGradientState>,
) -> Retained<MPSImage>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(encodeBatchToCommandBuffer:sourceImages:convolutionGradientStates:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeBatchToCommandBuffer_sourceImages_convolutionGradientStates(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImageBatch,
convolution_gradient_state: Option<&MPSCNNConvolutionGradientStateBatch>,
) -> Retained<MPSImageBatch>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(encodeToCommandBuffer:sourceImage:convolutionGradientState:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeToCommandBuffer_sourceImage_convolutionGradientState_destinationImage(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImage,
convolution_gradient_state: Option<&MPSCNNConvolutionGradientState>,
destination_image: &MPSImage,
);
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(encodeBatchToCommandBuffer:sourceImages:convolutionGradientStates:destinationImages:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeBatchToCommandBuffer_sourceImages_convolutionGradientStates_destinationImages(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImageBatch,
convolution_gradient_state: Option<&MPSCNNConvolutionGradientStateBatch>,
destination_image: &MPSImageBatch,
);
#[cfg(all(
feature = "MPSImage",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
/// Allocate a MPCNNConvolutionTransposeGradientState to hold the results from a -encodeBatchToCommandBuffer... operation
///
///
/// Parameter `sourceImage`: The MPSImage consumed by the associated -encode call.
///
/// Parameter `sourceStates`: The list of MPSCNNConvolutionGradientState consumed by the associated -encode call,
/// for a batch size of 1. In auto encoders, this state is produced by corresponding MPSCNNConvolution.
///
///
/// Returns: The list of states produced by the -encode call for batch size of 1.
/// -isResultStateReusedAcrossBatch returns YES for MPSCNNConvolutionTranspose so same
/// state is used across entire batch. State object is not reusasable across batches.
#[unsafe(method(resultStateForSourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn resultStateForSourceImage_sourceStates_destinationImage(
&self,
source_image: &MPSImage,
source_states: Option<&NSArray<MPSCNNConvolutionGradientState>>,
destination_image: &MPSImage,
) -> Option<Retained<MPSCNNConvolutionTransposeGradientState>>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(resultStateBatchForSourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn resultStateBatchForSourceImage_sourceStates_destinationImage(
&self,
source_image: &MPSImageBatch,
source_states: Option<&NSArray<MPSCNNConvolutionGradientStateBatch>>,
destination_image: &MPSImageBatch,
) -> Option<Retained<MPSCNNConvolutionTransposeGradientStateBatch>>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(temporaryResultStateForCommandBuffer:sourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryResultStateForCommandBuffer_sourceImage_sourceStates_destinationImage(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImage,
source_states: Option<&NSArray<MPSCNNConvolutionGradientState>>,
destination_image: &MPSImage,
) -> Option<Retained<MPSCNNConvolutionTransposeGradientState>>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(temporaryResultStateBatchForCommandBuffer:sourceImage:sourceStates:destinationImage:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryResultStateBatchForCommandBuffer_sourceImage_sourceStates_destinationImage(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImageBatch,
source_states: Option<&NSArray<MPSCNNConvolutionGradientStateBatch>>,
destination_image: &MPSImageBatch,
) -> Option<Retained<MPSCNNConvolutionTransposeGradientStateBatch>>;
/// CPU side reload. Reload the updated weights and biases from data provider into internal weights and bias buffers. Weights and biases
/// gradients needed for update are obtained from MPSCNNConvolutionTransposeGradientState object. Data provider passed in init call is used for this purpose.
#[unsafe(method(reloadWeightsAndBiasesFromDataSource))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesFromDataSource(&self);
#[cfg(feature = "MPSState")]
/// GPU side reload. Reload the updated weights and biases from update buffer produced by application enqueued metal kernel into internal weights
/// and biases buffer. Weights and biases gradients needed for update are obtained from MPSCNNConvolutionTransposeGradientState object's gradientForWeights and gradientForBiases metal buffer.
///
///
/// Parameter `commandBuffer`: Metal command buffer on which application update kernel was enqueued consuming MPSCNNConvolutionGradientState's gradientForWeights and gradientForBiases buffers
/// and producing updateBuffer metal buffer.
///
/// Parameter `state`: MPSCNNConvolutionWeightsAndBiasesState containing weights and biases buffers which have updated weights produced by application's update kernel.
/// The state readcount will be decremented.
#[unsafe(method(reloadWeightsAndBiasesWithCommandBuffer:state:))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesWithCommandBuffer_state(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
state: &MPSCNNConvolutionWeightsAndBiasesState,
);
#[cfg(feature = "MPSState")]
/// GPU side export. Enqueue a kernel to export current weights and biases stored in MPSCNNConvoltionTranspose's internal buffers into weights and biases MTLBuffer
/// returned in MPSCNNConvolutionWeightsAndBiasesState.
///
///
/// Parameter `commandBuffer`: Metal command buffer on which export kernel is enqueued.
///
/// Parameter `resultStateCanBeTemporary`: If FALSE, state returned will be non-temporary. If TRUE, returned state may or may not be temporary.
///
/// Returns: MPSCNNConvolutionWeightsAndBiasesState containing weights and biases buffer to which weights got exported. This state and be
/// temporary or non-temporary depending on the flag resultStateCanBeTemporary
#[unsafe(method(exportWeightsAndBiasesWithCommandBuffer:resultStateCanBeTemporary:))]
#[unsafe(method_family = none)]
pub unsafe fn exportWeightsAndBiasesWithCommandBuffer_resultStateCanBeTemporary(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
result_state_can_be_temporary: bool,
) -> Retained<MPSCNNConvolutionWeightsAndBiasesState>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
/// These low level encode functions should be used during training. The first two encode functions, which return
/// destination image on left hand side, takes in MPSCNNConvolutionGradientState that was produced by corresponding
/// MPSCNNConvolution when there is one e.g. auto encoders. This state is used to correctly size destination being returned.
/// These encode methods return MPSCNNConvoltionTransposeGradientState object on auto release pool to be consumed by MPSCNNConvolutionTransposeGradient.
#[unsafe(method(encodeToCommandBuffer:sourceImage:convolutionGradientState:destinationState:destinationStateIsTemporary:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeToCommandBuffer_sourceImage_convolutionGradientState_destinationState_destinationStateIsTemporary(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_image: &MPSImage,
convolution_gradient_state: Option<&MPSCNNConvolutionGradientState>,
out_state: &mut Option<Retained<MPSCNNConvolutionTransposeGradientState>>,
is_temporary: bool,
) -> Retained<MPSImage>;
#[cfg(all(
feature = "MPSImage",
feature = "MPSNDArray",
feature = "MPSNNGradientState",
feature = "MPSState"
))]
#[unsafe(method(encodeBatchToCommandBuffer:sourceImages:convolutionGradientStates:destinationStates:destinationStateIsTemporary:))]
#[unsafe(method_family = none)]
pub unsafe fn encodeBatchToCommandBuffer_sourceImages_convolutionGradientStates_destinationStates_destinationStateIsTemporary(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
source_images: &MPSImageBatch,
convolution_gradient_states: Option<&MPSCNNConvolutionGradientStateBatch>,
out_states: &mut Option<Retained<MPSCNNConvolutionTransposeGradientStateBatch>>,
is_temporary: bool,
) -> Retained<MPSImageBatch>;
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolutionTranspose {
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 MPSCNNConvolutionTranspose {
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 MPSCNNConvolutionTransposeGradient implementents backward propagation of gradient for MPSCNNConvolutionTranspose forward filter
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnconvolutiontransposegradient?language=objc)
#[unsafe(super(MPSCNNGradientKernel, MPSCNNBinaryKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNConvolutionTransposeGradient;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNConvolutionTransposeGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNConvolutionTransposeGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNConvolutionTransposeGradient {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNConvolutionTransposeGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNConvolutionTransposeGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolutionTransposeGradient {
extern_methods!(
/// The number of feature channels per pixel in the gradient image (primarySource) of encode call. This is same is outputFeatureChannels
/// or the feature channels of destination image in forward convolution i.e. dataSource.descriptor.outputFeatureChannels
#[unsafe(method(sourceGradientFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn sourceGradientFeatureChannels(&self) -> NSUInteger;
/// The number of feature channels per pixel in the input image to forward convolution which is used here as secondarySource.
/// This is same as dataSource.descriptor.inputFeatureChannels. This is also the number of feature channels in destinatin image
/// here i.e. gradient with respect to data.
#[unsafe(method(sourceImageFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn sourceImageFeatureChannels(&self) -> NSUInteger;
/// Number of groups input and output channels are divided into.
#[unsafe(method(groups))]
#[unsafe(method_family = none)]
pub unsafe fn groups(&self) -> NSUInteger;
/// dataSource with which gradient object was created
#[unsafe(method(dataSource))]
#[unsafe(method_family = none)]
pub unsafe fn dataSource(
&self,
) -> Retained<ProtocolObject<dyn MPSCNNConvolutionDataSource>>;
/// Option to control which gradient to compute. Default is MPSCNNConvolutionGradientOptionAll
/// which means both gradient with respect to data and gradient with respect to weight and bias are computed.
#[unsafe(method(gradientOption))]
#[unsafe(method_family = none)]
pub unsafe fn gradientOption(&self) -> MPSCNNConvolutionGradientOption;
/// Setter for [`gradientOption`][Self::gradientOption].
#[unsafe(method(setGradientOption:))]
#[unsafe(method_family = none)]
pub unsafe fn setGradientOption(&self, gradient_option: MPSCNNConvolutionGradientOption);
/// Initializes a convolution transpose gradient (with respect to weights and bias) object.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNConvolutionGradient filter will be used
///
/// Parameter `weights`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource
/// protocol. Note that same data source as provided to forward convolution should be used.
///
///
/// Returns: A valid MPSCNNConvolutionTransposeGradient object or nil, if failure.
#[unsafe(method(initWithDevice:weights:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_weights(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
weights: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
/// CPU side reload. Reload the updated weights and biases from data provider into internal weights and bias buffers. Weights and biases
/// gradients needed for update are obtained from MPSCNNConvolutionGradientState object. Data provider passed in init call is used for this purpose.
#[unsafe(method(reloadWeightsAndBiasesFromDataSource))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesFromDataSource(&self);
#[cfg(feature = "MPSState")]
/// GPU side reload. Reload the updated weights and biases from update buffer produced by application enqueued metal kernel into internal weights
/// and biases buffer. Weights and biases gradients needed for update are obtained from MPSCNNConvolutionGradientState object's gradientForWeights and gradientForBiases metal buffer.
///
///
/// Parameter `commandBuffer`: Metal command buffer on which application update kernel was enqueued consuming MPSCNNConvolutionGradientState's gradientForWeights and gradientForBiases buffer
/// and producing updateBuffer metal buffer.
///
/// Parameter `state`: MPSCNNConvolutionWeightsAndBiasesState containing weights and biases buffers which have updated weights produced by application's update kernel.
#[unsafe(method(reloadWeightsAndBiasesWithCommandBuffer:state:))]
#[unsafe(method_family = none)]
pub unsafe fn reloadWeightsAndBiasesWithCommandBuffer_state(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
state: &MPSCNNConvolutionWeightsAndBiasesState,
);
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNConvolutionTransposeGradient {
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 MPSCNNConvolutionTransposeGradient {
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 MPSCNNBinaryConvolution specifies a convolution with binary weights and an input image using binary approximations.
/// The MPSCNNBinaryConvolution optionally first binarizes the input image and then convolves the result with a set of
/// binary-valued filters, each producing one feature map in the output image (which is a normal image)
///
/// The output is computed as follows:
///
/// out[i, x, y, c] = ( sum_{dx,dy,f} in[i,x+dx, y+dy, f] x B[c,dx,dy,f] )
/// * scale[c] * beta[i,x,y] + bias[c], where
///
/// the sum over dx,dy is over the spatial filter kernel window defined by 'kernelWidth' and 'KernelHeight',
/// sum over 'f' is over the input feature channel indices within group, 'B' contains the binary weights, interpreted as
/// {-1,1} or { 0, 1 } and scale[c] is the 'outputScaleTerms' array and bias is the 'outputBiasTerms' array. Above 'i' is
/// the image index in batch the sum over input channels 'f' runs through the group indices.
///
/// The convolution operator 'x' is defined by MPSCNNBinaryConvolutionType passed in at initialization time of the filter
/// (
///
/// See: initWithDevice).
/// In case 'type' = MPSCNNBinaryConvolutionTypeBinaryWeights, the input image is not binarized at all
/// and the convolution is computed interpreting the weights as [ 0, 1 ] -> { -1, 1 } with the given scaling terms.
/// In case 'type' = MPSCNNBinaryConvolutionTypeXNOR the convolution is computed by first binarizing the input image
/// using the sign function 'bin(x) = x
/// <
/// 0 ? -1 : 1' and the convolution multiplication is done with the
/// XNOR-operator !(x ^ y) = delta_xy = { (x==y) ? 1 : 0 },
/// and scaled according to the optional scaling operations. Note that we output the values of the bitwise convolutions
/// to interval { -1, 1 }, which means that the output of the XNOR-operator is scaled implicitly as follows:
/// r = 2 * ( !(x ^ y) ) - 1 = { -1, 1 }.
/// This means that for a dot-product of two 32-bit words the result is:
/// r = 2 * popcount(!(x ^ y) ) - 32 = 32 - 2 * popcount( x ^ y ) = { -32, -30, ..., 30, 32 }.
/// In case 'type' = MPSCNNBinaryConvolutionTypeAND the convolution is computed by first binarizing the input image
/// using the sign function 'bin(x) = x
/// <
/// 0 ? -1 : 1' and the convolution multiplication is done with the
/// AND-operator (x
/// &
/// y) = delta_xy * delta_x1 = { (x==y==1) ? 1 : 0 }.
/// and scaled according to the optional scaling operations. Note that we output the values of the AND-operation is
/// assumed to lie in { 0, 1 } interval and hence no more implicit scaling takes place.
/// This means that for a dot-product of two 32-bit words the result is:
/// r = popcount(x
/// &
/// y) = { 0, ..., 31, 32 }.
///
/// The input data can be pre-offset and scaled by providing the 'inputBiasTerms' and 'inputScaleTerms' parameters for the
/// initialization functions and this can be used for example to accomplish batch normalization of the data. The scaling of
/// input values happens before possible beta-image computation.
///
/// The parameter 'beta' above is an optional image which is used to compute scaling factors for each spatial position and image index.
/// For the XNOR-Net based networks this is computed as follows: beta[i,x,y] = sum_{dx,dy} A[i, x+dx, y+dy] / (kx * ky), where
/// (dx,dy) are summed over the convolution filter window [ -kx/2, (kx-1)/2], [ -ky/2, (ky-1)/2 ] and
/// A[i,x,y] = sum_{c} abs( in[i,x,y,c] ) / Nc, where 'in' is the original input image (in full precision) and Nc is the
/// number of input channels in the input image. Parameter 'beta' is not passed as input and to enable beta-scaling the user can
/// provide 'MPSCNNBinaryConvolutionFlagsUseBetaScaling' in the flags parameter in the initialization functions.
///
/// Finally the normal activation neuron is applied and the result is written to the output image.
///
/// NOTE: MPSCNNBinaryConvolution does not currently support groups > 1.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnbinaryconvolution?language=objc)
#[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNBinaryConvolution;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNBinaryConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNBinaryConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNBinaryConvolution {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNBinaryConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNBinaryConvolution {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNBinaryConvolution {
extern_methods!(
#[unsafe(method(inputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn inputFeatureChannels(&self) -> NSUInteger;
/// The number of feature channels per pixel in the output image.
#[unsafe(method(outputFeatureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn outputFeatureChannels(&self) -> NSUInteger;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Initializes a binary convolution kernel with binary weights and a single scaling term.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNBinaryConvolution filter will be used
///
/// Parameter `convolutionData`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource protocol.
/// The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNBinaryConvolution uses to obtain the weights and bias terms as
/// well as the convolution descriptor.
/// Each entry in the convolutionData:weights array is a 32-bit unsigned integer value
/// and each bit represents one filter weight (given in machine byte order).
/// The featurechannel indices increase from the least significant bit within the 32-bits.
/// The number of entries is =
/// ceil( inputFeatureChannels/32.0 ) * outputFeatureChannels * kernelHeight * kernelWidth
/// The layout of filter weight is so that it can be reinterpreted as a 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ ceil( inputChannels / 32.0 ) ]
/// (The ordering of the reduction from 4D tensor to 1D is per C convention. The index based on
/// inputchannels varies most rapidly, followed by kernelWidth, then kernelHeight and finally
/// outputChannels varies least rapidly.)
///
/// Parameter `scaleValue`: A floating point value used to scale the entire convolution.
///
/// Parameter `type`: What kind of binarization strategy is to be used.
///
/// Parameter `flags`: See documentation above and documentation of MPSCNNBinaryConvolutionFlags.
///
///
/// Returns: A valid MPSCNNBinaryConvolution object or nil, if failure.
#[unsafe(method(initWithDevice:convolutionData:scaleValue:type:flags:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_convolutionData_scaleValue_type_flags(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
convolution_data: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
scale_value: c_float,
r#type: MPSCNNBinaryConvolutionType,
flags: MPSCNNBinaryConvolutionFlags,
) -> Retained<Self>;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Initializes a binary convolution kernel with binary weights as well as both pre and post scaling terms.
///
/// Parameter `device`: The MTLDevice on which this MPSCNNBinaryConvolution filter will be used
///
/// Parameter `convolutionData`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource protocol.
/// The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNBinaryConvolution uses to obtain the weights and the convolution descriptor.
/// Each entry in the convolutionData:weights array is a 32-bit unsigned integer value
/// and each bit represents one filter weight (given in machine byte order).
/// The featurechannel indices increase from the least significant bit within the 32-bits.
/// The number of entries is =
/// ceil( inputFeatureChannels/32.0 ) * outputFeatureChannels * kernelHeight * kernelWidth
/// The layout of filter weight is so that it can be reinterpreted as a 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ ceil( inputChannels / 32.0 ) ]
/// (The ordering of the reduction from 4D tensor to 1D is per C convention. The index based on
/// inputchannels varies most rapidly, followed by kernelWidth, then kernelHeight and finally
/// outputChannels varies least rapidly.)
///
/// Parameter `outputBiasTerms`: A pointer to bias terms to be applied to the convolution output. Each entry is a float value.
/// The number of entries is = numberOfOutputFeatureMaps. If nil then 0.0 is used for bias.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `outputScaleTerms`: A pointer to scale terms to be applied to binary convolution results per output feature channel.
/// Each entry is a float value. The number of entries is = numberOfOutputFeatureMaps. If nil then 1.0 is used.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `inputBiasTerms`: A pointer to offset terms to be applied to the input before convolution and before input scaling.
/// Each entry is a float value. The number of entries is 'inputFeatureChannels'. If NULL then 0.0 is used for bias.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `inputScaleTerms`: A pointer to scale terms to be applied to the input before convolution, but after input biasing.
/// Each entry is a float value. The number of entries is 'inputFeatureChannels'. If nil then 1.0 is used.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `type`: What kind of binarization strategy is to be used.
///
/// Parameter `flags`: See documentation above and documentation of MPSCNNBinaryConvolutionFlags.
///
///
/// Returns: A valid MPSCNNBinaryConvolution object or nil, if failure.
///
/// # Safety
///
/// - `output_bias_terms` must be a valid pointer or null.
/// - `output_scale_terms` must be a valid pointer or null.
/// - `input_bias_terms` must be a valid pointer or null.
/// - `input_scale_terms` must be a valid pointer or null.
#[unsafe(method(initWithDevice:convolutionData:outputBiasTerms:outputScaleTerms:inputBiasTerms:inputScaleTerms:type:flags:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_convolutionData_outputBiasTerms_outputScaleTerms_inputBiasTerms_inputScaleTerms_type_flags(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
convolution_data: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
output_bias_terms: *const c_float,
output_scale_terms: *const c_float,
input_bias_terms: *const c_float,
input_scale_terms: *const c_float,
r#type: MPSCNNBinaryConvolutionType,
flags: MPSCNNBinaryConvolutionFlags,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNBinaryConvolution {
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 MPSCNNBinaryConvolution {
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 MPSCNNBinaryFullyConnected specifies a fully connected convolution layer with binary weights
/// and optionally binarized input image.
/// See
/// MPSCNNFullyConnectedfor details on the fully connected layer and
/// MPSCNNBinaryConvolution for binary convolutions.
///
/// The default padding policy for MPSCNNBinaryConvolution is different from most
/// filters. It uses MPSNNPaddingMethodSizeValidOnly instead of MPSNNPaddingMethodSizeSame.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpscnnbinaryfullyconnected?language=objc)
#[unsafe(super(MPSCNNBinaryConvolution, MPSCNNKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSCNNBinaryFullyConnected;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSCNNBinaryFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSCNNBinaryFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSCNNBinaryFullyConnected {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSCNNBinaryFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSCNNBinaryFullyConnected {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNBinaryFullyConnected {
extern_methods!(
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Initializes a binary fully connected kernel with binary weights and a single scaling term.
///
///
/// Parameter `device`: The MTLDevice on which this MPSCNNBinaryFullyConnected filter will be used
///
/// Parameter `convolutionData`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource protocol.
/// The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNBinaryFullyConnected uses to obtain the weights and bias terms as
/// well as the convolution descriptor.
/// Each entry in the convolutionData:weights array is a 32-bit unsigned integer value
/// and each bit represents one filter weight (given in machine byte order).
/// The featurechannel indices increase from the least significant bit within the 32-bits.
/// The number of entries is =
/// ceil( inputFeatureChannels/32.0 ) * outputFeatureChannels * kernelHeight * kernelWidth
/// The layout of filter weight is so that it can be reinterpreted as a 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ ceil( inputChannels / 32.0 ) ]
/// (The ordering of the reduction from 4D tensor to 1D is per C convention. The index based on
/// inputchannels varies most rapidly, followed by kernelWidth, then kernelHeight and finally
/// outputChannels varies least rapidly.)
///
/// Parameter `scaleValue`: A single floating point value used to scale the entire convolution.
/// Each entry is a float value. The number of entries is 'inputFeatureChannels'. If nil then 1.0 is used.
///
/// Parameter `type`: What kind of binarization strategy is to be used.
///
/// Parameter `flags`: See documentation above and documentation of MPSCNNBinaryConvolutionFlags.
///
///
/// Returns: A valid MPSCNNBinaryFullyConnected object or nil, if failure.
#[unsafe(method(initWithDevice:convolutionData:scaleValue:type:flags:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_convolutionData_scaleValue_type_flags(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
convolution_data: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
scale_value: c_float,
r#type: MPSCNNBinaryConvolutionType,
flags: MPSCNNBinaryConvolutionFlags,
) -> Retained<Self>;
#[cfg(feature = "MPSNeuralNetworkTypes")]
/// Initializes a binary fully connected kernel with binary weights as well as both pre and post scaling terms.
///
///
/// Parameter `device`: The MTLDevice on which this MPSCNNBinaryFullyConnected filter will be used
///
/// Parameter `convolutionData`: A pointer to a object that conforms to the MPSCNNConvolutionDataSource protocol.
/// The MPSCNNConvolutionDataSource protocol declares the methods that an
/// instance of MPSCNNBinaryFullyConnected uses to obtain the weights and the convolution descriptor.
/// Each entry in the convolutionData:weights array is a 32-bit unsigned integer value
/// and each bit represents one filter weight (given in machine byte order).
/// The featurechannel indices increase from the least significant bit within the 32-bits.
/// The number of entries is =
/// ceil( inputFeatureChannels/32.0 ) * outputFeatureChannels * kernelHeight * kernelWidth
/// The layout of filter weight is so that it can be reinterpreted as a 4D tensor (array)
/// weight[ outputChannels ][ kernelHeight ][ kernelWidth ][ ceil( inputChannels / 32.0 ) ]
/// (The ordering of the reduction from 4D tensor to 1D is per C convention. The index based on
/// inputchannels varies most rapidly, followed by kernelWidth, then kernelHeight and finally
/// outputChannels varies least rapidly.)
///
///
/// Parameter `outputBiasTerms`: A pointer to bias terms to be applied to the convolution output. Each entry is a float value.
/// The number of entries is = numberOfOutputFeatureMaps. If nil then 0.0 is used for bias.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `outputScaleTerms`: A pointer to scale terms to be applied to binary convolution results per output feature channel.
/// Each entry is a float value. The number of entries is = numberOfOutputFeatureMaps. If nil then 1.0 is used.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `inputBiasTerms`: A pointer to offset terms to be applied to the input before convolution and before input scaling.
/// Each entry is a float value. The number of entries is 'inputFeatureChannels'. If NULL then 0.0 is used for bias.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `inputScaleTerms`: A pointer to scale terms to be applied to the input before convolution, but after input biasing.
/// Each entry is a float value. The number of entries is 'inputFeatureChannels'. If nil then 1.0 is used.
/// The values stored in the pointer are copied in and the array can be freed after this function returns.
///
/// Parameter `type`: What kind of binarization strategy is to be used.
///
/// Parameter `flags`: See documentation above and documentation of MPSCNNBinaryConvolutionFlags.
///
///
/// Returns: A valid MPSCNNBinaryFullyConnected object or nil, if failure.
///
/// # Safety
///
/// - `output_bias_terms` must be a valid pointer or null.
/// - `output_scale_terms` must be a valid pointer or null.
/// - `input_bias_terms` must be a valid pointer or null.
/// - `input_scale_terms` must be a valid pointer or null.
#[unsafe(method(initWithDevice:convolutionData:outputBiasTerms:outputScaleTerms:inputBiasTerms:inputScaleTerms:type:flags:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_convolutionData_outputBiasTerms_outputScaleTerms_inputBiasTerms_inputScaleTerms_type_flags(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
convolution_data: &ProtocolObject<dyn MPSCNNConvolutionDataSource>,
output_bias_terms: *const c_float,
output_scale_terms: *const c_float,
input_bias_terms: *const c_float,
input_scale_terms: *const c_float,
r#type: MPSCNNBinaryConvolutionType,
flags: MPSCNNBinaryConvolutionFlags,
) -> Retained<Self>;
/// 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>>;
#[unsafe(method(initWithDevice:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>;
);
}
/// Methods declared on superclass `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSCNNBinaryFullyConnected {
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 MPSCNNBinaryFullyConnected {
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 MPSNNGramMatrixCalculation filter specifies a layer which computes the uncentered cross-correlation
/// values between the image planes of each feature channel of an image. If the input image batch is
/// x = x[b, y, x, c], where 'b' is batch index, 'y' and 'x' are the image coordinate and
/// 'c' is the feature channel index then this filter computes the values:
///
/// y = y[b, 1, f, c] = alpha * sum_{x,y} x[b,y,x,f] * x[b,y,x,c], where
///
/// 'alpha' is a scaling factor. This operation can be interpreted to be computing all combinations
/// of fully connected layers between the different image planes of the input image. The results
/// are stored in the feature channel and 'x'-coordinate indices of the output batch.
/// The operation is performed independently on different images in the batch.
///
/// NOTE: Due to the nature of the operation this filter specifies a special padding policy
/// and hence does not support non-default offset or cliprect properties.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsnngrammatrixcalculation?language=objc)
#[unsafe(super(MPSCNNKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSNNGramMatrixCalculation;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSNNGramMatrixCalculation {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSNNGramMatrixCalculation {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSNNGramMatrixCalculation {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSNNGramMatrixCalculation {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSNNGramMatrixCalculation {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNGramMatrixCalculation {
extern_methods!(
/// Scaling factor for the output. Default: 1.0f.
#[unsafe(method(alpha))]
#[unsafe(method_family = none)]
pub unsafe fn alpha(&self) -> c_float;
/// Setter for [`alpha`][Self::alpha].
#[unsafe(method(setAlpha:))]
#[unsafe(method_family = none)]
pub unsafe fn setAlpha(&self, alpha: c_float);
/// 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>>;
/// Initializes a MPSNNGramMatrixCalculation kernel.
///
///
/// Parameter `device`: The MTLDevice on which this MPSNNGramMatrixCalculation filter will be used.
///
/// Parameter `alpha`: Scaling factor for the output.
///
/// Returns: A valid MPSNNGramMatrixCalculation object or nil, if failure.
#[unsafe(method(initWithDevice:alpha:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_alpha(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
alpha: c_float,
) -> Retained<Self>;
/// Initializes a MPSNNGramMatrixCalculation kernel with scaling factor alpha = 1.0f.
///
///
/// Parameter `device`: The MTLDevice on which this MPSNNGramMatrixCalculation filter will be used.
///
/// Returns: A valid MPSNNGramMatrixCalculation 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 `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNGramMatrixCalculation {
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 MPSNNGramMatrixCalculation {
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 MPSNNGramMatrixCalculationGradient defines the gradient filter for MPSNNGramMatrixCalculation.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsnngrammatrixcalculationgradient?language=objc)
#[unsafe(super(MPSCNNGradientKernel, MPSCNNBinaryKernel, MPSKernel, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
pub struct MPSNNGramMatrixCalculationGradient;
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCoding for MPSNNGramMatrixCalculationGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSCopying for MPSNNGramMatrixCalculationGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
unsafe impl CopyingHelper for MPSNNGramMatrixCalculationGradient {
type Result = Self;
}
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSObjectProtocol for MPSNNGramMatrixCalculationGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
extern_conformance!(
unsafe impl NSSecureCoding for MPSNNGramMatrixCalculationGradient {}
);
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNGramMatrixCalculationGradient {
extern_methods!(
/// Scaling factor for the output. Default: 1.0f. NOTE: the value for alpha is automatically adjusted by
/// the
/// MPSNNGradientStatewhen it is provided in the encode call.
#[unsafe(method(alpha))]
#[unsafe(method_family = none)]
pub unsafe fn alpha(&self) -> c_float;
/// Setter for [`alpha`][Self::alpha].
#[unsafe(method(setAlpha:))]
#[unsafe(method_family = none)]
pub unsafe fn setAlpha(&self, alpha: c_float);
/// 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>>;
/// Initializes a MPSNNGramMatrixCalculationGradient kernel.
///
///
/// Parameter `device`: The MTLDevice on which this MPSNNGramMatrixCalculationGradient filter will be used.
///
/// Parameter `alpha`: Scaling factor for the output. NOTE: the value for alpha is automatically adjusted by
/// the
/// MPSNNGradientStatewhen it is provided in the encode call.
///
/// Returns: A valid MPSNNGramMatrixCalculationGradient object or nil, if failure.
#[unsafe(method(initWithDevice:alpha:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_alpha(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
alpha: c_float,
) -> Retained<Self>;
/// Initializes a MPSNNGramMatrixCalculationGradient kernel with scaling factor alpha = 1.0f.
///
///
/// Parameter `device`: The MTLDevice on which this MPSNNGramMatrixCalculationGradient filter will be used.
///
/// Returns: A valid MPSNNGramMatrixCalculationGradient 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 `MPSKernel`.
#[cfg(all(feature = "MPSCNNKernel", feature = "MPSCore", feature = "MPSKernel"))]
impl MPSNNGramMatrixCalculationGradient {
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 MPSNNGramMatrixCalculationGradient {
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>;
);
}