oarust 0.19.0

GPU-first semantic computing runtime written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
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
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=image.json schema_version=1 generator_version=64
// schema_sha256=850fff7da094fda90deb1885822908eb59de961a0e67423335fc6de4de68b058
//! Per-plane image statistics and histogram metrics.

use crate::{
	DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
	runtime::{
		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
		KernelId, PushConstant,
	},
};

/// Accumulate a per-plane histogram over an FP32 NCHW or CHW image.
///
/// Each `(batch, channel)` plane contributes one row of `bins` buckets to the
/// U32 result whose leading dimensions mirror the image; `[B,C,H,W]` and
/// `[C,H,W]` inputs produce `[B,C,bins]` and `[C,bins]` results. Values below
/// `lower` or at or above `upper` are ignored; in-range values map uniformly
/// onto `[0, bins)`. The accumulator is cleared inside the operation, so a
/// captured plan replays the same counts.
///
/// # Errors
///
/// Returns an error unless `bins` is in `1..=256`, `lower` and `upper` are
/// finite with `lower < upper`, the image is nonempty FP32 NCHW/CHW, and all
/// sizes fit the shader ABI.
pub fn calc_hist(input: &Image, bins: u32, lower: f32, upper: f32) -> Result<Matrix> {
	if bins == 0 || bins > 256 {
		return Err(Error::invalid_argument(
			"image::calc_hist bins must be in 1..=256",
		));
	}
	if !lower.is_finite() || !upper.is_finite() || lower >= upper {
		return Err(Error::invalid_argument(
			"image::calc_hist requires finite bounds with lower < upper",
		));
	}
	let (batch, channels, image_height, image_width) = image_extent(input, "image::calc_hist")?;
	let mut shape = input.as_matrix().shape().to_vec();
	shape.truncate(shape.len() - 2);
	shape.push(bins as usize);
	let histogram_elements = shape
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::calc_hist output size exceeds u32"))?;
	let histogram = Matrix::allocate(
		input.runtime(),
		shape,
		histogram_elements as usize,
		DType::U32,
	)?;
	let clear_buffers = [BufferBinding::write(histogram.storage())];
	let clear_push = [PushConstant::U32(histogram_elements)];
	let count_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(histogram.storage()),
	];
	let count_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(bins),
		PushConstant::F32(lower),
		PushConstant::F32(upper),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageCalcHistClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageCalcHistClearU32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageCalcHistF32,
			buffers: &count_buffers,
			push_constants: &count_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	let attributes = [
		unsigned("bins", bins),
		float("lower", lower),
		float("upper", upper),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::CALC_HIST,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&histogram)],
			attributes: &attributes,
		},
	)?;
	Ok(histogram)
}

/// Equalize a normalized FP32 image histogram per `(batch, channel)` plane.
///
/// Pixel values are quantized into 256 uniform buckets over `[0, 1]`, the
/// per-plane cumulative distribution is spread back over `[0, 1]` following
/// the `equalizeHist` contract, and the result keeps the input layout and
/// format. Values outside `[0, 1]` clamp into the edge buckets.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW and all
/// sizes fit the shader ABI.
pub fn equalize_hist(input: &Image) -> Result<Image> {
	let (batch, channels, image_height, image_width) = image_extent(input, "image::equalize_hist")?;
	let mut histogram_shape = input.as_matrix().shape().to_vec();
	histogram_shape.truncate(histogram_shape.len() - 2);
	histogram_shape.push(256);
	let histogram_elements = histogram_shape
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::equalize_hist workspace exceeds u32"))?;
	let runtime = input.runtime();
	let histogram = Matrix::allocate(
		runtime,
		histogram_shape.clone(),
		histogram_elements as usize,
		DType::U32,
	)?;
	let lut = Matrix::allocate(
		runtime,
		histogram_shape,
		histogram_elements as usize,
		DType::F32,
	)?;
	let output = allocate_like(input, "image::equalize_hist")?;
	let clear_buffers = [BufferBinding::write(histogram.storage())];
	let clear_push = [PushConstant::U32(histogram_elements)];
	let count_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(histogram.storage()),
	];
	let count_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let lut_buffers = [
		BufferBinding::read(histogram.storage()),
		BufferBinding::write(lut.storage()),
	];
	let lut_push = [PushConstant::U32(histogram_elements)];
	let remap_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read(lut.storage()),
		BufferBinding::write(output.storage()),
	];
	let remap_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageEqualizeHistClearU32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistF32,
			buffers: &count_buffers,
			push_constants: &count_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistLutF32,
			buffers: &lut_buffers,
			push_constants: &lut_push,
			workgroups: KernelId::ImageEqualizeHistLutF32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageEqualizeHistRemapF32,
			buffers: &remap_buffers,
			push_constants: &remap_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::EQUALIZE_HIST,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &[],
		},
	)?;
	Ok(output)
}

/// Row-wise histogram comparison metric used by [`compare_hist`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HistogramComparison {
	/// Pearson correlation between centered rows; `1.0` is a perfect match.
	#[default]
	Correlation,
	/// Chi-square distance over paired buckets; `0.0` is a perfect match.
	ChiSquare,
	/// Normalized per-bucket minimum sum; `1.0` is a perfect match.
	Intersection,
	/// Bhattacharyya distance between normalized rows; `0.0` is a perfect match.
	Bhattacharyya,
}

impl HistogramComparison {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Correlation => "correlation",
			Self::ChiSquare => "chi_square",
			Self::Intersection => "intersection",
			Self::Bhattacharyya => "bhattacharyya",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Correlation => 0,
			Self::ChiSquare => 1,
			Self::Intersection => 2,
			Self::Bhattacharyya => 3,
		}
	}
}

/// Compare two same-shape U32 histogram matrices row by row.
///
/// The last dimension is the bucket axis; every leading index is an
/// independent row, so `[B,C,bins]` histograms produce a `[B,C]` FP32 score
/// matrix. Correlation, chi-square, intersection, and Bhattacharyya follow
/// the OpenCV `compareHist` formulas; degenerate rows return `0.0` rather
/// than propagating a zero denominator.
///
/// # Errors
///
/// Returns an error unless both inputs are same-shape nonempty U32 matrices
/// of rank at least two on one runtime, and all sizes fit the shader ABI.
pub fn compare_hist(
	first: &Matrix,
	second: &Matrix,
	method: HistogramComparison,
) -> Result<Matrix> {
	if first.dtype() != DType::U32
		|| second.dtype() != DType::U32
		|| first.shape() != second.shape()
		|| !first.runtime().same_as(second.runtime())
	{
		return Err(Error::invalid_argument(
			"image::compare_hist requires same-shape same-runtime U32 histograms",
		));
	}
	let shape = first.shape();
	if shape.len() < 2 || shape.contains(&0) {
		return Err(Error::invalid_argument(
			"image::compare_hist requires nonempty matrices of rank at least two",
		));
	}
	let bin_count = u32::try_from(shape[shape.len() - 1])
		.map_err(|_| Error::out_of_range("image::compare_hist bin count exceeds u32"))?;
	let row_count = shape[..shape.len() - 1]
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::compare_hist row count exceeds u32"))?;
	let output = Matrix::allocate(
		first.runtime(),
		shape[..shape.len() - 1].to_vec(),
		row_count as usize,
		DType::F32,
	)?;
	first.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageCompareHistU32,
			buffers: &[
				BufferBinding::read(first.storage()),
				BufferBinding::read(second.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(row_count),
				PushConstant::U32(bin_count),
				PushConstant::U32(method.code()),
			],
			workgroups: KernelId::ImageCompareHistU32.linear_workgroups(row_count),
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::COMPARE_HIST,
			inputs: &[
				ImageSemanticInput::Matrix(first),
				ImageSemanticInput::Matrix(second),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &[enumeration("method", method.token())],
		},
	)?;
	Ok(output)
}

/// Histogram-driven threshold selection used by [`threshold_auto`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AutoThreshold {
	/// Maximize between-class variance following `THRESH_OTSU`.
	#[default]
	Otsu,
	/// Maximum-distance triangle construction following `THRESH_TRIANGLE`.
	Triangle,
}

impl AutoThreshold {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Otsu => "otsu",
			Self::Triangle => "triangle",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Otsu => 0,
			Self::Triangle => 1,
		}
	}
}

/// Binary-threshold an FP32 image with a histogram-selected level.
///
/// Each `(batch, channel)` plane is quantized into 256 uniform buckets
/// over `[0, 1]`; the Otsu or Triangle method selects one threshold per
/// plane following the OpenCV `THRESH_OTSU`/`THRESH_TRIANGLE` contracts,
/// and pixels strictly above it produce `max_value` while all others
/// produce `0.0`. Returns the thresholded image together with the
/// per-plane threshold Matrix shaped like the leading dimensions.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
/// `max_value` is finite, and all sizes fit the shader ABI.
pub fn threshold_auto(
	input: &Image,
	method: AutoThreshold,
	max_value: f32,
) -> Result<(Image, Matrix)> {
	if !max_value.is_finite() {
		return Err(Error::invalid_argument(
			"image::threshold_auto requires a finite max_value",
		));
	}
	let (batch, channels, image_height, image_width) = image_extent(input, "image::threshold_auto")?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::threshold_auto plane count exceeds u32"))?;
	let histogram_elements = plane_count
		.checked_mul(256)
		.ok_or_else(|| Error::out_of_range("image::threshold_auto workspace exceeds u32"))?;
	let runtime = input.runtime();
	let mut histogram_shape = input.as_matrix().shape().to_vec();
	histogram_shape.truncate(histogram_shape.len() - 2);
	histogram_shape.push(256);
	let histogram = Matrix::allocate(
		runtime,
		histogram_shape,
		histogram_elements as usize,
		DType::U32,
	)?;
	let thresholds_shape = input.as_matrix().shape()[..input.as_matrix().shape().len() - 2].to_vec();
	let thresholds = Matrix::allocate(runtime, thresholds_shape, plane_count as usize, DType::F32)?;
	let output = allocate_like(input, "image::threshold_auto")?;
	let clear_buffers = [BufferBinding::write(histogram.storage())];
	let clear_push = [PushConstant::U32(histogram_elements)];
	let count_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(histogram.storage()),
	];
	let count_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let select_buffers = [
		BufferBinding::read(histogram.storage()),
		BufferBinding::write(thresholds.storage()),
	];
	let select_push = [
		PushConstant::U32(plane_count),
		PushConstant::U32(method.code()),
	];
	let apply_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read(thresholds.storage()),
		BufferBinding::write(output.storage()),
	];
	let apply_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(max_value),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageThresholdAutoClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageThresholdAutoClearU32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageThresholdAutoF32,
			buffers: &count_buffers,
			push_constants: &count_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageThresholdAutoSelectU32,
			buffers: &select_buffers,
			push_constants: &select_push,
			workgroups: KernelId::ImageThresholdAutoSelectU32.linear_workgroups(plane_count),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageThresholdAutoApplyF32,
			buffers: &apply_buffers,
			push_constants: &apply_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	let attributes = [
		enumeration("method", method.token()),
		float("max_value", max_value),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::THRESHOLD_AUTO,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[
				ImageSemanticOutput::Image(&output),
				ImageSemanticOutput::Matrix(&thresholds),
			],
			attributes: &attributes,
		},
	)?;
	Ok((output, thresholds))
}

/// Compute the per-plane summed-area table of an FP32 image.
///
/// Following the `integral` contract, the result is a `(height + 1)`
/// x `(width + 1)` FP32 Matrix per `(batch, channel)` plane whose
/// zero row and column border the inclusive prefix sums: element
/// `(y, x)` holds the sum over source pixels `[0, y) x [0, x)`. The
/// leading dimensions are preserved ahead of the enlarged spatial
/// extents.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
/// enlarged extents stay nonzero, and all sizes fit the shader ABI.
pub fn integral(input: &Image) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) = image_extent(input, "image::integral")?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::integral plane count exceeds u32"))?;
	let mut shape = input.as_matrix().shape().to_vec();
	let rank = shape.len();
	shape[rank - 2] += 1;
	shape[rank - 1] += 1;
	let elements = shape
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::integral output size exceeds u32"))?;
	let output = Matrix::allocate(input.runtime(), shape, elements as usize, DType::F32)?;
	let row_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(output.storage()),
	];
	let row_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let col_buffers = [BufferBinding::read_write(output.storage())];
	let col_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageIntegralRowsF32,
			buffers: &row_buffers,
			push_constants: &row_push,
			workgroups: KernelId::ImageIntegralRowsF32.linear_workgroups(plane_count * image_height),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageIntegralColsF32,
			buffers: &col_buffers,
			push_constants: &col_push,
			workgroups: KernelId::ImageIntegralColsF32.linear_workgroups(plane_count * (image_width + 1)),
			indirect: None,
		},
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::INTEGRAL,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &[],
		},
	)?;
	Ok(output)
}

/// Back-project a per-plane U32 histogram onto an FP32 image.
///
/// Each pixel is quantized with the `calc_hist` rule over
/// `[lower, upper)` into `bins` buckets taken from the histogram's
/// last dimension; the output pixel carries the histogram count as
/// an FP32 value, or `0.0` when the source falls outside the range.
/// Histogram leading dimensions must equal the image's leading
/// plane dimensions, following `calcBackProject`.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
/// the histogram is a nonempty U32 Matrix of matching leading
/// shape, `lower`/`upper` are finite with `lower < upper`, and all
/// sizes fit the shader ABI.
pub fn calc_back_project(
	input: &Image,
	histogram: &Matrix,
	lower: f32,
	upper: f32,
) -> Result<Image> {
	let (batch, channels, image_height, image_width) =
		image_extent(input, "image::calc_back_project")?;
	if histogram.dtype() != DType::U32 || histogram.shape().is_empty() {
		return Err(Error::invalid_argument(
			"image::calc_back_project requires a nonempty U32 histogram",
		));
	}
	let image_shape = input.as_matrix().shape();
	let histogram_shape = histogram.shape();
	if histogram_shape.len() != image_shape.len() - 1
		|| histogram_shape[..histogram_shape.len() - 1] != image_shape[..image_shape.len() - 2]
	{
		return Err(Error::invalid_argument(
			"image::calc_back_project histogram leading shape must match the image planes",
		));
	}
	let bins = u32::try_from(histogram_shape[histogram_shape.len() - 1])
		.map_err(|_| Error::out_of_range("image::calc_back_project bins exceed u32"))?;
	if bins == 0 || bins > 256 {
		return Err(Error::invalid_argument(
			"image::calc_back_project histogram bins must be in 1..=256",
		));
	}
	if !lower.is_finite() || !upper.is_finite() || lower >= upper {
		return Err(Error::invalid_argument(
			"image::calc_back_project requires finite bounds with lower < upper",
		));
	}
	let output = allocate_like(input, "image::calc_back_project")?;
	let attributes = [float("lower", lower), float("upper", upper)];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageCalcBackProjectF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::read(histogram.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::U32(bins),
				PushConstant::F32(lower),
				PushConstant::F32(upper),
			],
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::CALC_BACK_PROJECT,
			inputs: &[
				ImageSemanticInput::Image(input),
				ImageSemanticInput::Matrix(histogram),
			],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Contrast-limited adaptive histogram equalization per plane.
///
/// Each plane is split into `tile_width` x `tile_height` tiles,
/// quantized into 256 uniform buckets over `[0, 1]`, clipped at
/// `clip_limit` times the per-bin average with the excess spread
/// uniformly, and remapped through bilinear-interpolated tile
/// lookup tables following the `CLAHE` contract.
///
/// # Errors
///
/// Returns an error unless the image is nonempty FP32 NCHW/CHW,
/// `clip_limit` is finite and positive, both tile extents are
/// nonzero, and all sizes fit the shader ABI.
pub fn clahe(input: &Image, clip_limit: f32, tile_width: u32, tile_height: u32) -> Result<Image> {
	let (batch, channels, image_height, image_width) = image_extent(input, "image::clahe")?;
	if !clip_limit.is_finite() || clip_limit <= 0.0 {
		return Err(Error::invalid_argument(
			"image::clahe requires a finite positive clip_limit",
		));
	}
	if tile_width == 0 || tile_height == 0 {
		return Err(Error::invalid_argument(
			"image::clahe requires nonzero tile extents",
		));
	}
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::clahe plane count exceeds u32"))?;
	let tiles_x = image_width.div_ceil(tile_width);
	let tiles_y = image_height.div_ceil(tile_height);
	let tile_count = plane_count
		.checked_mul(tiles_x)
		.and_then(|count| count.checked_mul(tiles_y))
		.ok_or_else(|| Error::out_of_range("image::clahe tile count exceeds u32"))?;
	let histogram_elements = tile_count
		.checked_mul(256)
		.ok_or_else(|| Error::out_of_range("image::clahe histogram size exceeds u32"))?;
	let runtime = input.runtime();
	let histogram = Matrix::allocate(
		runtime,
		vec![histogram_elements as usize],
		histogram_elements as usize,
		DType::U32,
	)?;
	let lut = Matrix::allocate(
		runtime,
		vec![histogram_elements as usize],
		histogram_elements as usize,
		DType::F32,
	)?;
	let output = allocate_like(input, "image::clahe")?;
	let tile_area = tile_width as f32 * tile_height as f32;
	let clear_buffers = [BufferBinding::write(histogram.storage())];
	let clear_push = [PushConstant::U32(histogram_elements)];
	let count_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(histogram.storage()),
	];
	let count_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(tile_width),
		PushConstant::U32(tile_height),
		PushConstant::U32(tiles_x),
	];
	let lut_buffers = [
		BufferBinding::read(histogram.storage()),
		BufferBinding::write(lut.storage()),
	];
	let lut_push = [
		PushConstant::U32(tile_count),
		PushConstant::F32(clip_limit),
		PushConstant::F32(tile_area),
	];
	let remap_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read(lut.storage()),
		BufferBinding::write(output.storage()),
	];
	let remap_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(tile_width),
		PushConstant::U32(tile_height),
		PushConstant::U32(tiles_x),
		PushConstant::U32(tiles_y),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageClaheClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageClaheClearU32.linear_workgroups(histogram_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageClaheF32,
			buffers: &count_buffers,
			push_constants: &count_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageClaheLutU32,
			buffers: &lut_buffers,
			push_constants: &lut_push,
			workgroups: KernelId::ImageClaheLutU32.linear_workgroups(tile_count),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageClaheRemapF32,
			buffers: &remap_buffers,
			push_constants: &remap_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	let attributes = [
		float("clip_limit", clip_limit),
		unsigned("tile_width", tile_width),
		unsigned("tile_height", tile_height),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::CLAHE,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Add one image to a running accumulation image elementwise,
/// following `accumulate`. Both images must share shape, layout,
/// and format; the result is a fresh F32 image, not an in-place
/// update.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format.
pub fn accumulate(input: &Image, accumulator: &Image) -> Result<Image> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(input, accumulator, "image::accumulate")?;
	let output = allocate_like(input, "image::accumulate")?;
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageAccumulateF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::read(accumulator.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
			],
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::ACCUMULATE,
			inputs: &[
				ImageSemanticInput::Image(input),
				ImageSemanticInput::Image(accumulator),
			],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &[],
		},
	)?;
	Ok(output)
}

/// Blend an image into a running average as
/// `input * alpha + accumulator * (1 - alpha)` per element,
/// following `accumulateWeighted`.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format and
/// `alpha` is finite.
pub fn accumulate_weighted(input: &Image, accumulator: &Image, alpha: f32) -> Result<Image> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(input, accumulator, "image::accumulate_weighted")?;
	if !alpha.is_finite() {
		return Err(Error::invalid_argument(
			"image::accumulate_weighted requires a finite alpha",
		));
	}
	let output = allocate_like(input, "image::accumulate_weighted")?;
	let attributes = [float("alpha", alpha)];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageAccumulateWeightedF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::read(accumulator.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::F32(alpha),
			],
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::ACCUMULATE_WEIGHTED,
			inputs: &[
				ImageSemanticInput::Image(input),
				ImageSemanticInput::Image(accumulator),
			],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Compute the ten spatial moments `m00, m10, m01, m20, m11, m02,
/// m30, m21, m12, m03` per image plane through a serial per-plane
/// reduction, following `cv::moments`. The result Matrix carries
/// the image's leading plane dimensions plus a final extent-10
/// moment dimension.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32
/// NCHW/CHW image and all sizes fit the shader ABI.
pub fn moments(input: &Image) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) = image_extent(input, "image::moments")?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::moments plane count exceeds u32"))?;
	let mut shape = input.as_matrix().shape().to_vec();
	shape.truncate(shape.len() - 2);
	shape.push(10);
	let output = Matrix::allocate(
		input.runtime(),
		shape,
		plane_count
			.checked_mul(10)
			.ok_or_else(|| Error::out_of_range("image::moments output size exceeds u32"))? as usize,
		DType::F32,
	)?;
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageMomentsF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
			],
			workgroups: KernelId::ImageMomentsF32.linear_workgroups(plane_count),
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::MOMENTS,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &[],
		},
	)?;
	Ok(output)
}

/// Peak signal-to-noise ratio per image plane in decibels,
/// following `cv::PSNR`: `10 * log10(peak^2 / mse)` through a
/// serial per-plane reduction, `+inf` when the planes match
/// exactly. The result Matrix carries the image's leading plane
/// dimensions.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format and
/// `peak_value` is finite and positive.
pub fn psnr(first: &Image, second: &Image, peak_value: f32) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(first, second, "image::psnr")?;
	if !peak_value.is_finite() || peak_value <= 0.0 {
		return Err(Error::invalid_argument(
			"image::psnr requires a finite positive peak_value",
		));
	}
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::psnr plane count exceeds u32"))?;
	let mut shape = first.as_matrix().shape().to_vec();
	shape.truncate(shape.len() - 2);
	let output = Matrix::allocate(first.runtime(), shape, plane_count as usize, DType::F32)?;
	let attributes = [float("peak_value", peak_value)];
	first.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImagePsnrF32,
			buffers: &[
				BufferBinding::read(first.storage()),
				BufferBinding::read(second.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::F32(peak_value),
			],
			workgroups: KernelId::ImagePsnrF32.linear_workgroups(plane_count),
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::PSNR,
			inputs: &[
				ImageSemanticInput::Image(first),
				ImageSemanticInput::Image(second),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Global structural similarity per image plane through a serial
/// per-plane reduction of means, variances, and covariance with
/// the standard `K1=0.01, K2=0.03` constants over a `[0, 1]`
/// dynamic range, following the SSIM index of Wang et al. rather
/// than OpenCV's windowed map. The result Matrix carries the
/// image's leading plane dimensions.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format.
pub fn ssim(first: &Image, second: &Image) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(first, second, "image::ssim")?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::ssim plane count exceeds u32"))?;
	let mut shape = first.as_matrix().shape().to_vec();
	shape.truncate(shape.len() - 2);
	let output = Matrix::allocate(first.runtime(), shape, plane_count as usize, DType::F32)?;
	first.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageSsimF32,
			buffers: &[
				BufferBinding::read(first.storage()),
				BufferBinding::read(second.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
			],
			workgroups: KernelId::ImageSsimF32.linear_workgroups(plane_count),
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::SSIM,
			inputs: &[
				ImageSemanticInput::Image(first),
				ImageSemanticInput::Image(second),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &[],
		},
	)?;
	Ok(output)
}

/// Template-match score metric used by [`match_template`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MatchTemplate {
	/// `TM_SQDIFF` squared difference.
	#[default]
	Sqdiff,
	/// `TM_SQDIFF_NORMED` normalized squared difference.
	SqdiffNormed,
	/// `TM_CCORR` cross-correlation.
	Ccorr,
	/// `TM_CCORR_NORMED` normalized cross-correlation.
	CcorrNormed,
	/// `TM_CCOEFF` correlation coefficient.
	Ccoeff,
	/// `TM_CCOEFF_NORMED` normalized correlation coefficient.
	CcoeffNormed,
}

impl MatchTemplate {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Sqdiff => "sqdiff",
			Self::SqdiffNormed => "sqdiff_normed",
			Self::Ccorr => "ccorr",
			Self::CcorrNormed => "ccorr_normed",
			Self::Ccoeff => "ccoeff",
			Self::CcoeffNormed => "ccoeff_normed",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Sqdiff => 0,
			Self::SqdiffNormed => 1,
			Self::Ccorr => 2,
			Self::CcorrNormed => 3,
			Self::Ccoeff => 4,
			Self::CcoeffNormed => 5,
		}
	}
}

/// Slide a single-plane template over each image plane and write the
/// per-position match score to a Matrix, following `matchTemplate`.
/// The template's channel count must equal the input's; the output
/// carries the input's leading plane dimensions plus
/// `(height - th + 1) x (width - tw + 1)` score elements computed by
/// a serial per-position reduction over the template window.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32 NCHW/CHW
/// images with matching channel counts, a single-plane template no
/// larger than the image planes, and sizes that fit the shader ABI.
pub fn match_template(input: &Image, template: &Image, method: MatchTemplate) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) = image_extent(input, "image::match_template")?;
	if template.dtype() != DType::F32
		|| !matches!(template.layout(), ImageLayout::Nchw | ImageLayout::Chw)
		|| template.batch_size() != 1
		|| template.channels() != input.channels()
	{
		return Err(Error::invalid_argument(
			"image::match_template requires a single-plane FP32 template with matching channels",
		));
	}
	let template_height = u32::try_from(template.height())
		.map_err(|_| Error::out_of_range("image::match_template template height exceeds u32"))?;
	let template_width = u32::try_from(template.width())
		.map_err(|_| Error::out_of_range("image::match_template template width exceeds u32"))?;
	if template_height == 0
		|| template_width == 0
		|| template_height > image_height
		|| template_width > image_width
	{
		return Err(Error::invalid_argument(
			"image::match_template requires a nonempty template no larger than the image planes",
		));
	}
	let output_height = image_height - template_height + 1;
	let output_width = image_width - template_width + 1;
	let mut shape = input.as_matrix().shape().to_vec();
	let rank = shape.len();
	shape[rank - 2] = output_height as usize;
	shape[rank - 1] = output_width as usize;
	let elements = shape
		.iter()
		.try_fold(1u32, |count, value| {
			count.checked_mul(u32::try_from(*value).ok()?)
		})
		.ok_or_else(|| Error::out_of_range("image::match_template output size exceeds u32"))?;
	let output = Matrix::allocate(input.runtime(), shape, elements as usize, DType::F32)?;
	let attributes = [enumeration("method", method.token())];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageMatchTemplateF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::read(template.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::U32(template_height),
				PushConstant::U32(template_width),
				PushConstant::U32(output_height),
				PushConstant::U32(output_width),
				PushConstant::U32(method.code()),
			],
			workgroups: [
				output_width.div_ceil(16),
				output_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::MATCH_TEMPLATE,
			inputs: &[
				ImageSemanticInput::Image(input),
				ImageSemanticInput::Image(template),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Neighborhood connectivity used by [`connected_components`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Connectivity {
	/// 4-connected cross neighborhood.
	Four,
	/// 8-connected full neighborhood.
	#[default]
	Eight,
}

impl Connectivity {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Four => "four",
			Self::Eight => "eight",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Four => 4,
			Self::Eight => 8,
		}
	}
}

/// Connected-component labeling per plane, following
/// `connectedComponents`: every pixel above `threshold` is a
/// foreground candidate and receives a unique initial label;
/// bounded min-label propagation merges neighbors under the
/// selected connectivity (4 or 8). The U32 output carries
/// plane x height x width labels with `u32::MAX` on background
/// pixels. `propagation_passes` bounds label propagation (zero
/// selects `height + width` per plane); components with
/// diameters beyond the bound resolve to sub-components.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32
/// NCHW/CHW image and `threshold` is finite.
pub fn connected_components(
	input: &Image,
	threshold: f32,
	connectivity: Connectivity,
	propagation_passes: u32,
) -> Result<Matrix> {
	if !threshold.is_finite() {
		return Err(Error::invalid_argument(
			"image::connected_components threshold must be finite",
		));
	}
	let contract = crate::core::operation::image::CONNECTED_COMPONENTS;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::connected_components plane count exceeds u32"))?;
	let plane_elements = plane_count
		.checked_mul(image_height)
		.and_then(|count| count.checked_mul(image_width))
		.ok_or_else(|| Error::out_of_range("image::connected_components label count exceeds u32"))?;
	let relax_passes = if propagation_passes == 0 {
		image_height.checked_add(image_width).ok_or_else(|| {
			Error::out_of_range("image::connected_components propagation bound exceeds u32")
		})?
	} else {
		propagation_passes
	};
	let labels = Matrix::allocate(
		input.runtime(),
		vec![
			plane_count as usize,
			image_height as usize,
			image_width as usize,
		],
		plane_elements as usize,
		DType::U32,
	)?;
	let mut workgroups =
		KernelId::ImageConnectedComponentsInitU32.output_workgroups(image_width, image_height);
	workgroups[2] = plane_count;
	let init_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(labels.storage()),
	];
	let init_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(threshold),
	];
	let relax_buffers = [BufferBinding::read_write(labels.storage())];
	let relax_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(connectivity.code()),
	];
	let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageConnectedComponentsInitU32,
		buffers: &init_buffers,
		push_constants: &init_push,
		workgroups,
		indirect: None,
	});
	for _ in 0..relax_passes {
		dispatches.push(ComputeDispatch {
			kernel: KernelId::ImageConnectedComponentsRelaxU32,
			buffers: &relax_buffers,
			push_constants: &relax_push,
			workgroups,
			indirect: None,
		});
	}
	let attributes = [
		float("threshold", threshold),
		enumeration("connectivity", connectivity.token()),
		unsigned("propagation_passes", propagation_passes),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&labels)],
			attributes: &attributes,
		},
	)?;
	Ok(labels)
}

/// Distance metric used by [`distance_transform`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DistanceType {
	/// 4-neighborhood unit-weight chamfer (exact Manhattan).
	L1,
	/// 8-neighborhood 1/sqrt(2) chamfer approximation.
	#[default]
	L2,
}

impl DistanceType {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::L1 => "l1",
			Self::L2 => "l2",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::L1 => 1,
			Self::L2 => 2,
		}
	}
}

/// Distance transform per plane, following `distanceTransform`:
/// every pixel above `threshold` measures the chamfer distance
/// to the nearest background pixel. `DistanceType::L1` uses a
/// 4-neighborhood with unit weights (exact Manhattan distance);
/// `DistanceType::L2` uses an 8-neighborhood with weights
/// 1 / sqrt(2), the classic 3x3 chamfer approximation. The F32
/// output carries plane x height x width distances, zero on
/// background. `propagation_passes` bounds the relaxation
/// (zero selects `height + width` per plane, the worst-case
/// propagation distance).
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32
/// NCHW/CHW image and `threshold` is finite.
pub fn distance_transform(
	input: &Image,
	threshold: f32,
	distance: DistanceType,
	propagation_passes: u32,
) -> Result<Matrix> {
	if !threshold.is_finite() {
		return Err(Error::invalid_argument(
			"image::distance_transform threshold must be finite",
		));
	}
	let contract = crate::core::operation::image::DISTANCE_TRANSFORM;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::distance_transform plane count exceeds u32"))?;
	let plane_elements = plane_count
		.checked_mul(image_height)
		.and_then(|count| count.checked_mul(image_width))
		.ok_or_else(|| Error::out_of_range("image::distance_transform element count exceeds u32"))?;
	let relax_passes = if propagation_passes == 0 {
		image_height.checked_add(image_width).ok_or_else(|| {
			Error::out_of_range("image::distance_transform propagation bound exceeds u32")
		})?
	} else {
		propagation_passes
	};
	let distances = Matrix::allocate(
		input.runtime(),
		vec![
			plane_count as usize,
			image_height as usize,
			image_width as usize,
		],
		plane_elements as usize,
		DType::F32,
	)?;
	let mut workgroups =
		KernelId::ImageDistanceTransformInitF32.output_workgroups(image_width, image_height);
	workgroups[2] = plane_count;
	let init_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(distances.storage()),
	];
	let init_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(threshold),
	];
	let relax_buffers = [BufferBinding::read_write(distances.storage())];
	let relax_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(distance.code()),
	];
	let mut dispatches = Vec::with_capacity(1 + relax_passes as usize);
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageDistanceTransformInitF32,
		buffers: &init_buffers,
		push_constants: &init_push,
		workgroups,
		indirect: None,
	});
	for _ in 0..relax_passes {
		dispatches.push(ComputeDispatch {
			kernel: KernelId::ImageDistanceTransformRelaxF32,
			buffers: &relax_buffers,
			push_constants: &relax_push,
			workgroups,
			indirect: None,
		});
	}
	let attributes = [
		float("threshold", threshold),
		enumeration("distance", distance.token()),
		unsigned("propagation_passes", propagation_passes),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&distances)],
			attributes: &attributes,
		},
	)?;
	Ok(distances)
}

/// Standard Hough line transform per plane, following
/// `HoughLines`: pixels above `edge_threshold` vote into a
/// (theta x rho) accumulator quantized by `theta_step`
/// (degrees over [0, 180)) and `rho_step`. Accumulator cells
/// reaching `threshold` votes that are strict local maxima in
/// their 3x3 theta-rho neighborhood emit lines. The F32 output
/// carries plane x `max_lines` x 3 rows of (rho, theta degrees,
/// votes) in compacted unsorted order; unused rows are zero.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32
/// NCHW/CHW image, `edge_threshold`/`rho_step`/`theta_step`
/// are finite, `rho_step`/`theta_step` are positive,
/// `theta_step` does not exceed 180, and `max_lines` is
/// nonzero.
pub fn hough_lines(
	input: &Image,
	edge_threshold: f32,
	rho_step: f32,
	theta_step: f32,
	threshold: u32,
	max_lines: u32,
) -> Result<Matrix> {
	if !edge_threshold.is_finite()
		|| !rho_step.is_finite()
		|| !theta_step.is_finite()
		|| rho_step <= 0.0
		|| theta_step <= 0.0
		|| theta_step > 180.0
	{
		return Err(Error::invalid_argument(
			"image::hough_lines steps must be finite, positive, and theta_step <= 180",
		));
	}
	if max_lines == 0 {
		return Err(Error::invalid_argument(
			"image::hough_lines max_lines must be nonzero",
		));
	}
	let contract = crate::core::operation::image::HOUGH_LINES;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::hough_lines plane count exceeds u32"))?;
	let num_theta = (180.0f32 / theta_step).ceil() as u32;
	let span = (image_width as f64).hypot(image_height as f64).ceil();
	let num_rho = ((2.0 * span) / rho_step as f64).ceil() as u32 + 1;
	let bins = num_theta
		.checked_mul(num_rho)
		.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator size exceeds u32"))?;
	let acc_stride = bins
		.checked_add(1)
		.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator stride exceeds u32"))?;
	let acc_elements = plane_count
		.checked_mul(acc_stride)
		.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator elements exceed u32"))?;
	let line_elements = plane_count
		.checked_mul(max_lines)
		.and_then(|count| count.checked_mul(3))
		.ok_or_else(|| Error::out_of_range("image::hough_lines output elements exceed u32"))?;
	let acc_cells = plane_count
		.checked_mul(bins)
		.ok_or_else(|| Error::out_of_range("image::hough_lines accumulator cells exceed u32"))?;
	let accumulator = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, acc_stride as usize],
		acc_elements as usize,
		DType::U32,
	)?;
	let lines = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, max_lines as usize, 3],
		line_elements as usize,
		DType::F32,
	)?;
	let mut workgroups =
		KernelId::ImageHoughLinesAccumulateF32.output_workgroups(image_width, image_height);
	workgroups[2] = plane_count;
	let rho_span = span as f32;
	let clear_buffers = [
		BufferBinding::write(accumulator.storage()),
		BufferBinding::write(lines.storage()),
	];
	let clear_push = [
		PushConstant::U32(acc_elements),
		PushConstant::U32(line_elements),
	];
	let accumulate_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(accumulator.storage()),
	];
	let accumulate_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(edge_threshold),
		PushConstant::F32(rho_step),
		PushConstant::F32(theta_step),
		PushConstant::U32(num_theta),
		PushConstant::U32(num_rho),
		PushConstant::F32(rho_span),
	];
	let extract_buffers = [
		BufferBinding::read_write(accumulator.storage()),
		BufferBinding::write(lines.storage()),
	];
	let extract_push = [
		PushConstant::U32(num_theta),
		PushConstant::U32(num_rho),
		PushConstant::U32(plane_count),
		PushConstant::U32(threshold),
		PushConstant::U32(max_lines),
		PushConstant::F32(rho_step),
		PushConstant::F32(theta_step),
		PushConstant::F32(rho_span),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageHoughLinesClearU32.linear_workgroups(acc_elements + line_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesAccumulateF32,
			buffers: &accumulate_buffers,
			push_constants: &accumulate_push,
			workgroups,
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesExtractU32,
			buffers: &extract_buffers,
			push_constants: &extract_push,
			workgroups: KernelId::ImageHoughLinesExtractU32.linear_workgroups(acc_cells),
			indirect: None,
		},
	];
	let attributes = [
		float("edge_threshold", edge_threshold),
		float("rho_step", rho_step),
		float("theta_step", theta_step),
		unsigned("threshold", threshold),
		unsigned("max_lines", max_lines),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&lines)],
			attributes: &attributes,
		},
	)?;
	Ok(lines)
}

/// Probabilistic Hough segment transform per plane, following
/// `HoughLinesP`: votes accumulate as in `hough_lines`, strict
/// local-maxima cells above `threshold` emit candidate lines,
/// and each candidate is walked along its direction to find
/// the dominant contiguous edge run that tolerates gaps of up
/// to `max_line_gap` pixels and reaches `min_line_length`.
/// The F32 output carries plane x `max_lines` x 4 rows of
/// (x1, y1, x2, y2) endpoints; line slots without a qualifying
/// run are zero.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32
/// NCHW/CHW image, `edge_threshold`/`rho_step`/`theta_step`
/// are finite, `rho_step`/`theta_step` are positive,
/// `theta_step` does not exceed 180, `min_line_length` is
/// nonnegative, and `max_lines` is nonzero.
#[allow(clippy::too_many_arguments)]
pub fn hough_lines_p(
	input: &Image,
	edge_threshold: f32,
	rho_step: f32,
	theta_step: f32,
	threshold: u32,
	max_lines: u32,
	min_line_length: f32,
	max_line_gap: u32,
) -> Result<Matrix> {
	if !edge_threshold.is_finite()
		|| !rho_step.is_finite()
		|| !theta_step.is_finite()
		|| !min_line_length.is_finite()
		|| rho_step <= 0.0
		|| theta_step <= 0.0
		|| theta_step > 180.0
		|| min_line_length < 0.0
	{
		return Err(Error::invalid_argument(
			"image::hough_lines_p steps must be finite/positive, theta_step <= 180, min_line_length >= 0",
		));
	}
	if max_lines == 0 {
		return Err(Error::invalid_argument(
			"image::hough_lines_p max_lines must be nonzero",
		));
	}
	let contract = crate::core::operation::image::HOUGH_LINES_P;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p plane count exceeds u32"))?;
	let num_theta = (180.0f32 / theta_step).ceil() as u32;
	let span = (image_width as f64).hypot(image_height as f64).ceil();
	let num_rho = ((2.0 * span) / rho_step as f64).ceil() as u32 + 1;
	let bins = num_theta
		.checked_mul(num_rho)
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator size exceeds u32"))?;
	let acc_stride = bins
		.checked_add(1)
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator stride exceeds u32"))?;
	let acc_elements = plane_count
		.checked_mul(acc_stride)
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator elements exceed u32"))?;
	let acc_cells = plane_count
		.checked_mul(bins)
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p accumulator cells exceed u32"))?;
	let line_elements = plane_count
		.checked_mul(max_lines)
		.and_then(|count| count.checked_mul(3))
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p line elements exceed u32"))?;
	let segment_elements = plane_count
		.checked_mul(max_lines)
		.and_then(|count| count.checked_mul(4))
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p segment elements exceed u32"))?;
	let line_slots = plane_count
		.checked_mul(max_lines)
		.ok_or_else(|| Error::out_of_range("image::hough_lines_p line slots exceed u32"))?;
	let accumulator = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, acc_stride as usize],
		acc_elements as usize,
		DType::U32,
	)?;
	let lines = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, max_lines as usize, 3],
		line_elements as usize,
		DType::F32,
	)?;
	let segments = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, max_lines as usize, 4],
		segment_elements as usize,
		DType::F32,
	)?;
	let mut workgroups =
		KernelId::ImageHoughLinesAccumulateF32.output_workgroups(image_width, image_height);
	workgroups[2] = plane_count;
	let rho_span = span as f32;
	let clear_buffers = [
		BufferBinding::write(accumulator.storage()),
		BufferBinding::write(lines.storage()),
	];
	let clear_push = [
		PushConstant::U32(acc_elements),
		PushConstant::U32(line_elements),
	];
	let accumulate_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read_write(accumulator.storage()),
	];
	let accumulate_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(edge_threshold),
		PushConstant::F32(rho_step),
		PushConstant::F32(theta_step),
		PushConstant::U32(num_theta),
		PushConstant::U32(num_rho),
		PushConstant::F32(rho_span),
	];
	let extract_buffers = [
		BufferBinding::read_write(accumulator.storage()),
		BufferBinding::write(lines.storage()),
	];
	let extract_push = [
		PushConstant::U32(num_theta),
		PushConstant::U32(num_rho),
		PushConstant::U32(plane_count),
		PushConstant::U32(threshold),
		PushConstant::U32(max_lines),
		PushConstant::F32(rho_step),
		PushConstant::F32(theta_step),
		PushConstant::F32(rho_span),
	];
	let probe_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read(lines.storage()),
		BufferBinding::write(segments.storage()),
	];
	let probe_push = [
		PushConstant::U32(plane_count),
		PushConstant::U32(max_lines),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(edge_threshold),
		PushConstant::F32(min_line_length),
		PushConstant::U32(max_line_gap),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesPClearU32,
			buffers: &clear_buffers,
			push_constants: &clear_push,
			workgroups: KernelId::ImageHoughLinesPClearU32
				.linear_workgroups(acc_elements + line_elements),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesPAccumulateF32,
			buffers: &accumulate_buffers,
			push_constants: &accumulate_push,
			workgroups,
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesPExtractU32,
			buffers: &extract_buffers,
			push_constants: &extract_push,
			workgroups: KernelId::ImageHoughLinesPExtractU32.linear_workgroups(acc_cells),
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageHoughLinesProbeF32,
			buffers: &probe_buffers,
			push_constants: &probe_push,
			workgroups: KernelId::ImageHoughLinesProbeF32.linear_workgroups(line_slots),
			indirect: None,
		},
	];
	let attributes = [
		float("edge_threshold", edge_threshold),
		float("rho_step", rho_step),
		float("theta_step", theta_step),
		unsigned("threshold", threshold),
		unsigned("max_lines", max_lines),
		float("min_line_length", min_line_length),
		unsigned("max_line_gap", max_line_gap),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Matrix(&segments)],
			attributes: &attributes,
		},
	)?;
	Ok(segments)
}

/// External contour extraction per plane, following `findContours`
/// with `RETR_EXTERNAL` semantics: foreground pixels above
/// `threshold` are labeled as connected components under the
/// selected connectivity, each component's minimum-index
/// boundary pixel seeds a Moore-neighbor trace that emits an
/// ordered `(x, y)` point list. Returns an F32
/// `[planes, max_contours, max_points, 2]` point matrix and a U32
/// `[planes, max_contours]` length matrix; unused slots stay zero.
/// `max_points` bounds each contour (zero selects
/// `4 * (height + width)`; longer contours truncate), and
/// `max_contours` bounds the per-plane contour count.
/// `propagation_passes` bounds component labeling (zero selects
/// `height + width`). Contour order and slot assignment are
/// unspecified across planes.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32
/// NCHW/CHW image, `threshold` is finite, and `max_contours` is
/// nonzero.
pub fn find_contours(
	input: &Image,
	threshold: f32,
	connectivity: Connectivity,
	max_contours: u32,
	max_points: u32,
	propagation_passes: u32,
) -> Result<(Matrix, Matrix)> {
	if !threshold.is_finite() {
		return Err(Error::invalid_argument(
			"image::find_contours threshold must be finite",
		));
	}
	if max_contours == 0 {
		return Err(Error::invalid_argument(
			"image::find_contours max_contours must be nonzero",
		));
	}
	let contract = crate::core::operation::image::FIND_CONTOURS;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::find_contours plane count exceeds u32"))?;
	let plane_elements = image_height
		.checked_mul(image_width)
		.ok_or_else(|| Error::out_of_range("image::find_contours plane size exceeds u32"))?;
	let label_elements = plane_count
		.checked_mul(plane_elements)
		.ok_or_else(|| Error::out_of_range("image::find_contours label count exceeds u32"))?;
	let relax_passes = if propagation_passes == 0 {
		image_height
			.checked_add(image_width)
			.ok_or_else(|| Error::out_of_range("image::find_contours propagation bound exceeds u32"))?
	} else {
		propagation_passes
	};
	let resolved_max_points = if max_points == 0 {
		image_height
			.checked_add(image_width)
			.and_then(|sum| sum.checked_mul(4))
			.ok_or_else(|| Error::out_of_range("image::find_contours point bound exceeds u32"))?
	} else {
		max_points
	};
	let labels = Matrix::allocate(
		input.runtime(),
		vec![
			plane_count as usize,
			image_height as usize,
			image_width as usize,
		],
		label_elements as usize,
		DType::U32,
	)?;
	let seed_stride = max_contours
		.checked_add(1)
		.ok_or_else(|| Error::out_of_range("image::find_contours seed stride exceeds u32"))?;
	let seed_elements = plane_count
		.checked_mul(seed_stride)
		.ok_or_else(|| Error::out_of_range("image::find_contours seed count exceeds u32"))?;
	let point_elements = plane_count
		.checked_mul(max_contours)
		.and_then(|count| count.checked_mul(resolved_max_points))
		.and_then(|count| count.checked_mul(2))
		.ok_or_else(|| Error::out_of_range("image::find_contours point count exceeds u32"))?;
	let length_elements = plane_count
		.checked_mul(max_contours)
		.ok_or_else(|| Error::out_of_range("image::find_contours length count exceeds u32"))?;
	let seeds = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, seed_stride as usize],
		seed_elements as usize,
		DType::U32,
	)?;
	let points = Matrix::allocate(
		input.runtime(),
		vec![
			plane_count as usize,
			max_contours as usize,
			resolved_max_points as usize,
			2,
		],
		point_elements as usize,
		DType::F32,
	)?;
	let lengths = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, max_contours as usize],
		length_elements as usize,
		DType::U32,
	)?;
	let clear_elements = seed_elements.max(point_elements).max(length_elements);
	let trace_slots = plane_count
		.checked_mul(max_contours)
		.ok_or_else(|| Error::out_of_range("image::find_contours slot count exceeds u32"))?;
	let mut workgroups =
		KernelId::ImageFindContoursInitU32.output_workgroups(image_width, image_height);
	workgroups[2] = plane_count;
	let clear_buffers = [
		BufferBinding::write(seeds.storage()),
		BufferBinding::write(points.storage()),
		BufferBinding::write(lengths.storage()),
	];
	let clear_push = [
		PushConstant::U32(seed_elements),
		PushConstant::U32(point_elements),
		PushConstant::U32(length_elements),
	];
	let init_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(labels.storage()),
	];
	let init_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::F32(threshold),
	];
	let relax_buffers = [BufferBinding::read_write(labels.storage())];
	let relax_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(connectivity.code()),
	];
	let seeds_buffers = [
		BufferBinding::read(labels.storage()),
		BufferBinding::read_write(seeds.storage()),
	];
	let seeds_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(max_contours),
	];
	let trace_buffers = [
		BufferBinding::read(labels.storage()),
		BufferBinding::read(seeds.storage()),
		BufferBinding::write(points.storage()),
		BufferBinding::write(lengths.storage()),
	];
	let trace_push = [
		PushConstant::U32(plane_count),
		PushConstant::U32(max_contours),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(resolved_max_points),
	];
	let mut dispatches = Vec::with_capacity(4 + relax_passes as usize);
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageFindContoursClearU32,
		buffers: &clear_buffers,
		push_constants: &clear_push,
		workgroups: KernelId::ImageFindContoursClearU32.linear_workgroups(clear_elements),
		indirect: None,
	});
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageFindContoursInitU32,
		buffers: &init_buffers,
		push_constants: &init_push,
		workgroups,
		indirect: None,
	});
	for _ in 0..relax_passes {
		dispatches.push(ComputeDispatch {
			kernel: KernelId::ImageFindContoursRelaxU32,
			buffers: &relax_buffers,
			push_constants: &relax_push,
			workgroups,
			indirect: None,
		});
	}
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageFindContoursSeedsU32,
		buffers: &seeds_buffers,
		push_constants: &seeds_push,
		workgroups,
		indirect: None,
	});
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageFindContoursTraceU32,
		buffers: &trace_buffers,
		push_constants: &trace_push,
		workgroups: KernelId::ImageFindContoursTraceU32.linear_workgroups(trace_slots),
		indirect: None,
	});
	let attributes = [
		float("threshold", threshold),
		enumeration("connectivity", connectivity.token()),
		unsigned("max_contours", max_contours),
		unsigned("max_points", resolved_max_points),
		unsigned("propagation_passes", propagation_passes),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[
				ImageSemanticOutput::Matrix(&points),
				ImageSemanticOutput::Matrix(&lengths),
			],
			attributes: &attributes,
		},
	)?;
	Ok((points, lengths))
}

/// Corner response function used by [`corner_score`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CornerScore {
	/// Harris response `det(M) - k * trace(M)^2` over the windowed second moments.
	#[default]
	Harris,
	/// Shi-Tomasi smallest-eigenvalue response `lambda_min(M)`.
	MinEigen,
}

impl CornerScore {
	pub(super) const fn token(self) -> &'static str {
		match self {
			Self::Harris => "harris",
			Self::MinEigen => "min_eigen",
		}
	}

	pub(super) const fn code(self) -> u32 {
		match self {
			Self::Harris => 0,
			Self::MinEigen => 1,
		}
	}
}

/// Per-pixel corner response over each plane: 3x3 Sobel gradients feed
/// windowed second moments `M = [sum Ix^2, sum IxIy; sum IxIy, sum Iy^2]`
/// inside a `block_size` x `block_size` box. `Harris` emits
/// `det(M) - k * trace(M)^2`; `MinEigen` emits the smaller eigenvalue
/// of `M` (Shi-Tomasi). Borders reflect101 like `cornerHarris`.
///
/// The response map shares the input geometry; combine with a local
/// max pass for candidate keypoints.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
/// image, `k` is finite, and `block_size` is odd and at least 3.
pub fn corner_score(
	input: &Image,
	block_size: u32,
	k: f32,
	score_type: CornerScore,
) -> Result<Image> {
	if !k.is_finite() {
		return Err(Error::invalid_argument(
			"image::corner_score k must be finite",
		));
	}
	if block_size < 3 || block_size.is_multiple_of(2) {
		return Err(Error::invalid_argument(
			"image::corner_score block_size must be odd and at least 3",
		));
	}
	let contract = crate::core::operation::image::CORNER_SCORE;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::corner_score plane count exceeds u32"))?;
	let product_elements = plane_count
		.checked_mul(image_height)
		.and_then(|count| count.checked_mul(image_width))
		.and_then(|count| count.checked_mul(3))
		.ok_or_else(|| Error::out_of_range("image::corner_score scratch size exceeds u32"))?;
	let products = Matrix::allocate(
		input.runtime(),
		vec![product_elements as usize],
		product_elements as usize,
		DType::F32,
	)?;
	let output = allocate_like(input, contract.name())?;
	let gradient_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(products.storage()),
	];
	let gradient_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let score_buffers = [
		BufferBinding::read(products.storage()),
		BufferBinding::write(output.storage()),
	];
	let score_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(block_size),
		PushConstant::F32(k),
		PushConstant::U32(score_type.code()),
	];
	let dispatches = [
		ComputeDispatch {
			kernel: KernelId::ImageCornerScoreGradientF32,
			buffers: &gradient_buffers,
			push_constants: &gradient_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ComputeDispatch {
			kernel: KernelId::ImageCornerScoreF32,
			buffers: &score_buffers,
			push_constants: &score_push,
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
	];
	let attributes = [
		unsigned("block_size", block_size),
		float("k", k),
		enumeration("score_type", score_type.token()),
	];
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// FAST corner response per plane on the radius-3 circle of 16
/// samples: for each pixel the score is the largest deviation `t`
/// such that `arc_length` contiguous circle samples are all brighter
/// than `center + t` or all darker than `center - t`, zero when no
/// such arc exists. Pixels within 3 of the border score 0.0.
///
/// The response map shares the input geometry; non-maximum
/// suppression and thresholding select candidate keypoints.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
/// image and `arc_length` is in `9..=16`.
pub fn corner_fast(input: &Image, arc_length: u32) -> Result<Image> {
	if !(9..=16).contains(&arc_length) {
		return Err(Error::invalid_argument(
			"image::corner_fast arc_length must be in 9..=16",
		));
	}
	let contract = crate::core::operation::image::CORNER_FAST;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let output = allocate_like(input, contract.name())?;
	let attributes = [unsigned("arc_length", arc_length)];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageCornerFastF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::U32(arc_length),
			],
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Brute-force Hamming descriptor matching: for each row of `query`,
/// scan every row of `train` and record the two smallest XOR popcount
/// distances. Both inputs are U8 `[N, D]` matrices sharing `D`.
///
/// Returns an F32 `[N_query, 4]` matrix whose rows are
/// `(best_index, best_distance, second_index, second_distance)`,
/// mirroring `BFMatcher.knnMatch(k=2)` on `NORM_HAMMING`. Rows with
/// fewer than two candidates fill unused columns with `-1`.
///
/// # Errors
///
/// Returns an error unless both inputs are nonempty U8 matrices with
/// identical trailing descriptor width and at least one row each.
pub fn bf_match(query: &Matrix, train: &Matrix) -> Result<Matrix> {
	if query.dtype() != DType::U8 || train.dtype() != DType::U8 {
		return Err(Error::invalid_argument(
			"image::bf_match requires U8 descriptor matrices",
		));
	}
	if query.shape().len() != 2 || train.shape().len() != 2 {
		return Err(Error::invalid_argument(
			"image::bf_match requires [N, D] descriptor matrices",
		));
	}
	let desc_len = query.shape()[1];
	if desc_len == 0 || train.shape()[1] != desc_len {
		return Err(Error::invalid_argument(
			"image::bf_match descriptor widths must match and be nonzero",
		));
	}
	let query_count = query.shape()[0];
	let train_count = train.shape()[0];
	if query_count == 0 || train_count == 0 {
		return Err(Error::invalid_argument(
			"image::bf_match requires nonempty descriptor sets",
		));
	}
	let query_count_u32 = u32::try_from(query_count)
		.map_err(|_| Error::out_of_range("image::bf_match query count exceeds u32"))?;
	let train_count_u32 = u32::try_from(train_count)
		.map_err(|_| Error::out_of_range("image::bf_match train count exceeds u32"))?;
	let desc_len_u32 = u32::try_from(desc_len)
		.map_err(|_| Error::out_of_range("image::bf_match descriptor width exceeds u32"))?;
	let output = Matrix::allocate(
		query.runtime(),
		vec![query_count, 4],
		query_count
			.checked_mul(4)
			.ok_or_else(|| Error::out_of_range("image::bf_match output size exceeds u32"))?,
		DType::F32,
	)?;
	let attributes = [];
	query.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageBfMatchU8,
			buffers: &[
				BufferBinding::read(query.storage()),
				BufferBinding::read(train.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(query_count_u32),
				PushConstant::U32(train_count_u32),
				PushConstant::U32(desc_len_u32),
			],
			workgroups: KernelId::ImageBfMatchU8.linear_workgroups(query_count_u32),
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::BF_MATCH,
			inputs: &[
				ImageSemanticInput::Matrix(query),
				ImageSemanticInput::Matrix(train),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Bounded `goodFeaturesToTrack` selection over a per-plane corner
/// response map: pixels scoring above `quality * plane_max` survive
/// radius suppression when no strictly stronger candidate lies within
/// `min_distance` (ties break by lower linear index). Survivors claim
/// atomic slots per plane up to `max_corners`; slot order is
/// unsorted unlike OpenCV's score-descending emission.
///
/// Returns `(keypoints, counts)`: an F32 `[planes, max_corners, 3]`
/// matrix of `(x, y, score)` rows holding `min(count, max_corners)`
/// valid entries followed by zeros, and a U32 `[planes]` survivor
/// count matrix (may exceed `max_corners` when slots truncate).
/// A `max_corners` of zero selects `height * width` per plane.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
/// image and both `quality` and `min_distance` are finite with
/// quality in [0, 1] and min_distance >= 0.
pub fn good_features_to_track(
	input: &Image,
	max_corners: u32,
	quality: f32,
	min_distance: f32,
) -> Result<(Matrix, Matrix)> {
	if !quality.is_finite()
		|| !(0.0..=1.0).contains(&quality)
		|| !min_distance.is_finite()
		|| min_distance < 0.0
	{
		return Err(Error::invalid_argument(
			"image::good_features_to_track requires quality in [0, 1] and finite min_distance >= 0",
		));
	}
	let contract = crate::core::operation::image::GOOD_FEATURES_TO_TRACK;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::good_features_to_track plane count exceeds u32"))?;
	let corner_cap = if max_corners == 0 {
		image_height
			.checked_mul(image_width)
			.ok_or_else(|| Error::out_of_range("image::good_features_to_track plane size exceeds u32"))?
	} else {
		max_corners
	};
	let row_elements = plane_count
		.checked_mul(image_height)
		.ok_or_else(|| Error::out_of_range("image::good_features_to_track scratch size exceeds u32"))?;
	let row_max = Matrix::allocate(
		input.runtime(),
		vec![row_elements as usize],
		row_elements as usize,
		DType::F32,
	)?;
	let thresholds = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize],
		plane_count as usize,
		DType::F32,
	)?;
	let counts = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize],
		plane_count as usize,
		DType::U32,
	)?;
	let keypoints = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, corner_cap as usize, 3],
		plane_count
			.checked_mul(corner_cap)
			.and_then(|count| count.checked_mul(3))
			.ok_or_else(|| {
				Error::out_of_range("image::good_features_to_track keypoint size exceeds u32")
			})? as usize,
		DType::F32,
	)?;
	let clear_buffers = [
		BufferBinding::write(keypoints.storage()),
		BufferBinding::write(counts.storage()),
	];
	let clear_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(corner_cap),
	];
	let row_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(row_max.storage()),
	];
	let row_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
	];
	let threshold_buffers = [
		BufferBinding::read(row_max.storage()),
		BufferBinding::write(thresholds.storage()),
	];
	let threshold_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::F32(quality),
	];
	let select_buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::read(thresholds.storage()),
		BufferBinding::write(keypoints.storage()),
		BufferBinding::write(counts.storage()),
	];
	let select_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(image_height),
		PushConstant::U32(image_width),
		PushConstant::U32(corner_cap),
		PushConstant::F32(min_distance),
	];
	let attributes = [
		unsigned("max_corners", max_corners),
		float("quality", quality),
		float("min_distance", min_distance),
	];
	input.runtime().record_image_split_semantic(
		&[
			ComputeDispatch {
				kernel: KernelId::ImageGoodFeaturesClearF32,
				buffers: &clear_buffers,
				push_constants: &clear_push,
				workgroups: KernelId::ImageGoodFeaturesClearF32
					.linear_workgroups(plane_count * corner_cap * 3),
				indirect: None,
			},
			ComputeDispatch {
				kernel: KernelId::ImageGoodFeaturesRowMaxF32,
				buffers: &row_buffers,
				push_constants: &row_push,
				workgroups: KernelId::ImageGoodFeaturesRowMaxF32
					.linear_workgroups(plane_count * image_height),
				indirect: None,
			},
			ComputeDispatch {
				kernel: KernelId::ImageGoodFeaturesThresholdF32,
				buffers: &threshold_buffers,
				push_constants: &threshold_push,
				workgroups: KernelId::ImageGoodFeaturesThresholdF32.linear_workgroups(plane_count),
				indirect: None,
			},
			ComputeDispatch {
				kernel: KernelId::ImageGoodFeaturesSelectF32,
				buffers: &select_buffers,
				push_constants: &select_push,
				workgroups: [
					image_width.div_ceil(16),
					image_height.div_ceil(16),
					batch * channels,
				],
				indirect: None,
			},
		],
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[
				ImageSemanticOutput::Matrix(&keypoints),
				ImageSemanticOutput::Matrix(&counts),
			],
			attributes: &attributes,
		},
	)?;
	Ok((keypoints, counts))
}

/// Bounded ORB keypoint + steered rBRIEF descriptor pipeline,
/// following `ORB::detectAndCompute`. Each pyramid level runs the
/// existing corner_fast + good_features_to_track stages (FAST-9
/// response, quality-thresholded radius suppression), then a
/// describe stage computes the intensity-centroid orientation over
/// a 31x31 patch and a 256-bit steered BRIEF descriptor using the
/// OpenCV bit_pattern_31_ test pairs. Scale factor is 2x per level
/// via pyr_down.
///
/// Returns `(keypoints, descriptors, counts)`: an F32
/// `[planes, max_features, 6]` matrix of `(x, y, angle_radians,
/// score, level, size)` rows in level-0 coordinates, a U32
/// `[planes, max_features, 8]` matrix of descriptor words, and a
/// U32 `[planes]` claimed-slot count (may exceed `max_features`).
/// Slot order is unordered across a level's survivors. A
/// `max_features` of zero selects `height * width` per plane.
///
/// # Errors
///
/// Returns an error unless the image is a nonempty FP32 NCHW/CHW
/// image, `levels` >= 1, `edge` >= 18 (rotated test-pair support),
/// quality is in [0, 1], and min_distance is finite and >= 0.
pub fn orb(
	input: &Image,
	max_features: u32,
	quality: f32,
	min_distance: f32,
	levels: u32,
	edge: u32,
) -> Result<(Matrix, Matrix, Matrix)> {
	if !quality.is_finite()
		|| !(0.0..=1.0).contains(&quality)
		|| !min_distance.is_finite()
		|| min_distance < 0.0
	{
		return Err(Error::invalid_argument(
			"image::orb requires quality in [0, 1] and finite min_distance >= 0",
		));
	}
	if levels == 0 || edge < 18 {
		return Err(Error::invalid_argument(
			"image::orb requires levels >= 1 and edge >= 18 for the rotated BRIEF support",
		));
	}
	let contract = crate::core::operation::image::ORB;
	let (batch, channels, image_height, image_width) = image_extent(input, contract.name())?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::orb plane count exceeds u32"))?;
	let feature_cap = if max_features == 0 {
		image_height
			.checked_mul(image_width)
			.ok_or_else(|| Error::out_of_range("image::orb plane size exceeds u32"))?
	} else {
		max_features
	};
	let level_cap = feature_cap;
	let keypoints = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, feature_cap as usize, 6],
		plane_count
			.checked_mul(feature_cap)
			.and_then(|count| count.checked_mul(6))
			.ok_or_else(|| Error::out_of_range("image::orb keypoint size exceeds u32"))? as usize,
		DType::F32,
	)?;
	let descriptors = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize, feature_cap as usize, 8],
		plane_count
			.checked_mul(feature_cap)
			.and_then(|count| count.checked_mul(8))
			.ok_or_else(|| Error::out_of_range("image::orb descriptor size exceeds u32"))? as usize,
		DType::U32,
	)?;
	let counts = Matrix::allocate(
		input.runtime(),
		vec![plane_count as usize],
		plane_count as usize,
		DType::U32,
	)?;
	let clear_buffers = [
		BufferBinding::write(keypoints.storage()),
		BufferBinding::write(descriptors.storage()),
		BufferBinding::write(counts.storage()),
	];
	let clear_push = [
		PushConstant::U32(batch),
		PushConstant::U32(channels),
		PushConstant::U32(feature_cap),
	];
	let mut level_images = Vec::with_capacity(levels as usize);
	let mut level_dims = Vec::with_capacity(levels as usize);
	let mut level_states = Vec::with_capacity(levels as usize);
	level_images.push(input.clone());
	level_dims.push((image_width, image_height, 1.0f32));
	for _ in 1..levels {
		let next = crate::image::pyr_down(
			level_images
				.last()
				.ok_or_else(|| Error::internal("image::orb pyramid level missing"))?,
		)?;
		let (width, height, scale) = level_dims[level_dims.len() - 1];
		level_dims.push((width.div_ceil(2), height.div_ceil(2), scale * 2.0));
		level_images.push(next);
	}
	for level_image in &level_images {
		let score_map = crate::image::corner_fast(level_image, 9)?;
		let (level_keypoints, level_counts) =
			crate::image::good_features_to_track(&score_map, level_cap, quality, min_distance)?;
		level_states.push((level_keypoints, level_counts));
	}
	let mut describe_sets = Vec::with_capacity(levels as usize);
	let mut describe_pushes = Vec::with_capacity(levels as usize);
	for level in 0..levels {
		let level_image = &level_images[level as usize];
		let level_keypoints = &level_states[level as usize].0;
		let level_counts = &level_states[level as usize].1;
		let (level_width, level_height, level_scale) = level_dims[level as usize];
		let describe_buffers = [
			BufferBinding::read(level_image.storage()),
			BufferBinding::read(level_keypoints.storage()),
			BufferBinding::read(level_counts.storage()),
			BufferBinding::write(keypoints.storage()),
			BufferBinding::write(descriptors.storage()),
			BufferBinding::write(counts.storage()),
		];
		let describe_push = [
			PushConstant::U32(batch),
			PushConstant::U32(channels),
			PushConstant::U32(level_height),
			PushConstant::U32(level_width),
			PushConstant::U32(level_cap),
			PushConstant::U32(edge),
			PushConstant::U32(feature_cap),
			PushConstant::U32(level),
			PushConstant::F32(level_scale),
		];
		describe_sets.push(describe_buffers);
		describe_pushes.push(describe_push);
	}
	let attributes = [
		unsigned("max_features", max_features),
		float("quality", quality),
		float("min_distance", min_distance),
		unsigned("levels", levels),
		unsigned("edge", edge),
	];
	let mut dispatches = Vec::with_capacity(describe_sets.len() + 1);
	dispatches.push(ComputeDispatch {
		kernel: KernelId::ImageOrbClearF32,
		buffers: &clear_buffers,
		push_constants: &clear_push,
		workgroups: KernelId::ImageOrbClearF32.linear_workgroups(plane_count * feature_cap * 8),
		indirect: None,
	});
	for (buffers, push_constants) in describe_sets.iter().zip(describe_pushes.iter()) {
		dispatches.push(ComputeDispatch {
			kernel: KernelId::ImageOrbDescribeF32,
			buffers: buffers.as_slice(),
			push_constants: push_constants.as_slice(),
			workgroups: KernelId::ImageOrbDescribeF32.linear_workgroups(plane_count * level_cap),
			indirect: None,
		});
	}
	input.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[
				ImageSemanticOutput::Matrix(&keypoints),
				ImageSemanticOutput::Matrix(&descriptors),
				ImageSemanticOutput::Matrix(&counts),
			],
			attributes: &attributes,
		},
	)?;
	Ok((keypoints, descriptors, counts))
}

/// Sparse Lucas-Kanade optical flow with image pyramids,
/// following `calcOpticalFlowPyrLK`. Each pyramid level runs
/// one `flow_lk_refine` dispatch from the coarsest level to
/// level 0 over `2 * window + 1` windows with the same point
/// set applied to every image plane; the tracked estimate
/// carries between levels in a `[planes, N, 2]` state buffer
/// and the last level writes status and error maps.
///
/// `points` is an F32 `[N, 2]` matrix of `(x, y)` source
/// positions in level-0 pixel coordinates. `window` is the
/// half-window radius. Returns `(next_points, status, error)`:
/// the tracked F32 `[planes, N, 2]` positions, an F32
/// `[planes, N]` found/lost mask, and an F32 `[planes, N]`
/// RMS patch-residual error; status 0 rows carry the final
/// unconverged estimate.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format,
/// `points` is a nonempty F32 `[N, 2]` matrix, `levels`,
/// `window`, and `iterations` are >= 1, `min_eigen` is finite
/// and positive, and the coarsest level still fits the full
/// window.
pub fn optical_flow_pyr_lk(
	previous: &Image,
	next: &Image,
	points: &Matrix,
	levels: u32,
	window: u32,
	iterations: u32,
	min_eigen: f32,
) -> Result<(Matrix, Matrix, Matrix)> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(previous, next, "image::optical_flow_pyr_lk")?;
	if levels == 0 || window == 0 || iterations == 0 || !min_eigen.is_finite() || min_eigen <= 0.0 {
		return Err(Error::invalid_argument(
			"image::optical_flow_pyr_lk requires levels/window/iterations >= 1 and finite min_eigen > 0",
		));
	}
	if points.dtype() != DType::F32
		|| points.shape().len() != 2
		|| points.shape()[0] == 0
		|| points.shape()[1] != 2
	{
		return Err(Error::invalid_argument(
			"image::optical_flow_pyr_lk requires a nonempty F32 [N, 2] points matrix",
		));
	}
	let point_count = u32::try_from(points.shape()[0])
		.map_err(|_| Error::out_of_range("image::optical_flow_pyr_lk point count exceeds u32"))?;
	let support = window
		.checked_mul(2)
		.and_then(|value| value.checked_add(1))
		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk window exceeds u32"))?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk plane count exceeds u32"))?;
	let state_elements = plane_count
		.checked_mul(point_count)
		.and_then(|count| count.checked_mul(2))
		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk state size exceeds u32"))?;
	let map_elements = plane_count
		.checked_mul(point_count)
		.ok_or_else(|| Error::out_of_range("image::optical_flow_pyr_lk map size exceeds u32"))?;
	let contract = crate::core::operation::image::OPTICAL_FLOW_PYR_LK;
	let mut previous_levels = Vec::with_capacity(levels as usize);
	let mut next_levels = Vec::with_capacity(levels as usize);
	let mut level_dims = Vec::with_capacity(levels as usize);
	previous_levels.push(previous.clone());
	next_levels.push(next.clone());
	level_dims.push((image_width, image_height));
	for _ in 1..levels {
		previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
			|| Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
		)?)?);
		next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
			|| Error::internal("image::optical_flow_pyr_lk pyramid level missing"),
		)?)?);
		let (width, height) = level_dims[level_dims.len() - 1];
		level_dims.push((width.div_ceil(2), height.div_ceil(2)));
	}
	let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
	if coarsest_width < support || coarsest_height < support {
		return Err(Error::invalid_argument(
			"image::optical_flow_pyr_lk requires the coarsest level to fit the full window",
		));
	}
	let next_points = Matrix::allocate(
		previous.runtime(),
		vec![plane_count as usize, point_count as usize, 2],
		state_elements as usize,
		DType::F32,
	)?;
	let status = Matrix::allocate(
		previous.runtime(),
		vec![plane_count as usize, point_count as usize],
		map_elements as usize,
		DType::F32,
	)?;
	let error = Matrix::allocate(
		previous.runtime(),
		vec![plane_count as usize, point_count as usize],
		map_elements as usize,
		DType::F32,
	)?;
	let mut stages = Vec::with_capacity(levels as usize);
	for level in (0..levels).rev() {
		let previous_level = &previous_levels[level as usize];
		let next_level = &next_levels[level as usize];
		let (level_width, level_height) = level_dims[level as usize];
		let level_scale = 0.5f32.powi(level as i32);
		let initialize = u32::from(level == levels - 1);
		let finalize = u32::from(level == 0);
		let refine_buffers = [
			BufferBinding::read(previous_level.storage()),
			BufferBinding::read(next_level.storage()),
			BufferBinding::read(points.storage()),
			BufferBinding::read_write(next_points.storage()),
			BufferBinding::write(status.storage()),
			BufferBinding::write(error.storage()),
		];
		let refine_push = [
			PushConstant::U32(batch),
			PushConstant::U32(channels),
			PushConstant::U32(point_count),
			PushConstant::U32(level_height),
			PushConstant::U32(level_width),
			PushConstant::U32(window),
			PushConstant::U32(iterations),
			PushConstant::U32(initialize),
			PushConstant::U32(finalize),
			PushConstant::F32(level_scale),
			PushConstant::F32(min_eigen),
		];
		stages.push((KernelId::ImageFlowLkRefineF32, refine_buffers, refine_push));
	}
	let attributes = [
		unsigned("levels", levels),
		unsigned("window", window),
		unsigned("iterations", iterations),
		float("min_eigen", min_eigen),
	];
	let dispatches: Vec<ComputeDispatch> = stages
		.iter()
		.map(|(kernel, buffers, push_constants)| ComputeDispatch {
			kernel: *kernel,
			buffers: buffers.as_slice(),
			push_constants: push_constants.as_slice(),
			workgroups: KernelId::ImageFlowLkRefineF32.linear_workgroups(plane_count * point_count),
			indirect: None,
		})
		.collect();
	previous.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[
				ImageSemanticInput::Image(previous),
				ImageSemanticInput::Image(next),
				ImageSemanticInput::Matrix(points),
			],
			outputs: &[
				ImageSemanticOutput::Matrix(&next_points),
				ImageSemanticOutput::Matrix(&status),
				ImageSemanticOutput::Matrix(&error),
			],
			attributes: &attributes,
		},
	)?;
	Ok((next_points, status, error))
}

/// Dense Farneback optical flow over a 2x image pyramid,
/// following `calcOpticalFlowFarneback`. Each level expands
/// both frames into polynomial coefficient maps through two
/// separable weighted-least-squares passes (`flow_expand_v`
/// then `flow_expand_h`), then relaxes the flow field with
/// `iterations` Jacobi `flow_update` dispatches over a
/// `2 * window + 1` averaging neighbourhood. The coarsest
/// level starts from a zero field; finer levels initialize
/// from the 2x-upsampled coarser solution.
///
/// `window` is the half-window radius of the update
/// averaging neighbourhood and `poly_n` the half-support of
/// the gaussian-weighted polynomial fit. Returns the F32
/// `[planes, 2, H, W]` flow field at level-0 resolution with
/// x displacement in channel 0 and y displacement in
/// channel 1.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format,
/// `levels`, `window`, `iterations`, and `poly_n` are >= 1,
/// `poly_sigma` is finite and positive, and the coarsest
/// level still fits the polynomial support.
pub fn optical_flow_farneback(
	previous: &Image,
	next: &Image,
	levels: u32,
	window: u32,
	iterations: u32,
	poly_n: u32,
	poly_sigma: f32,
) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(previous, next, "image::optical_flow_farneback")?;
	if levels == 0
		|| window == 0
		|| iterations == 0
		|| poly_n == 0
		|| !poly_sigma.is_finite()
		|| poly_sigma <= 0.0
	{
		return Err(Error::invalid_argument(
			"image::optical_flow_farneback requires levels/window/iterations/poly_n >= 1 and finite poly_sigma > 0",
		));
	}
	let poly_support = poly_n
		.checked_mul(2)
		.and_then(|value| value.checked_add(1))
		.ok_or_else(|| Error::out_of_range("image::optical_flow_farneback poly_n exceeds u32"))?;
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::optical_flow_farneback plane count exceeds u32"))?;
	let contract = crate::core::operation::image::OPTICAL_FLOW_FARNEBACK;
	let mut previous_levels = Vec::with_capacity(levels as usize);
	let mut next_levels = Vec::with_capacity(levels as usize);
	let mut level_dims = Vec::with_capacity(levels as usize);
	previous_levels.push(previous.clone());
	next_levels.push(next.clone());
	level_dims.push((image_width, image_height));
	for _ in 1..levels {
		previous_levels.push(crate::image::pyr_down(previous_levels.last().ok_or_else(
			|| Error::internal("image::optical_flow_farneback pyramid level missing"),
		)?)?);
		next_levels.push(crate::image::pyr_down(next_levels.last().ok_or_else(
			|| Error::internal("image::optical_flow_farneback pyramid level missing"),
		)?)?);
		let (width, height) = level_dims[level_dims.len() - 1];
		level_dims.push((width.div_ceil(2), height.div_ceil(2)));
	}
	let (coarsest_width, coarsest_height) = level_dims[level_dims.len() - 1];
	if coarsest_width < poly_support || coarsest_height < poly_support {
		return Err(Error::invalid_argument(
			"image::optical_flow_farneback requires the coarsest level to fit the polynomial support",
		));
	}
	let workspace_elements = |planes: u32| -> Result<usize> {
		Ok(
			planes
				.checked_mul(image_height)
				.and_then(|count| count.checked_mul(image_width))
				.ok_or_else(|| {
					Error::out_of_range("image::optical_flow_farneback workspace size exceeds u32")
				})? as usize,
		)
	};
	let moment_shape = vec![
		plane_count as usize,
		3,
		image_height as usize,
		image_width as usize,
	];
	let poly_shape = vec![
		plane_count as usize,
		5,
		image_height as usize,
		image_width as usize,
	];
	let flow_shape = vec![
		plane_count as usize,
		2,
		image_height as usize,
		image_width as usize,
	];
	let three_planes = plane_count.checked_mul(3).ok_or_else(|| {
		Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
	})?;
	let five_planes = plane_count.checked_mul(5).ok_or_else(|| {
		Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
	})?;
	let two_planes = plane_count.checked_mul(2).ok_or_else(|| {
		Error::out_of_range("image::optical_flow_farneback workspace planes exceed u32")
	})?;
	let moments_a = Matrix::allocate(
		previous.runtime(),
		moment_shape.clone(),
		workspace_elements(three_planes)?,
		DType::F32,
	)?;
	let moments_b = Matrix::allocate(
		previous.runtime(),
		moment_shape,
		workspace_elements(three_planes)?,
		DType::F32,
	)?;
	let poly1 = Matrix::allocate(
		previous.runtime(),
		poly_shape.clone(),
		workspace_elements(five_planes)?,
		DType::F32,
	)?;
	let poly2 = Matrix::allocate(
		previous.runtime(),
		poly_shape,
		workspace_elements(five_planes)?,
		DType::F32,
	)?;
	let flow_a = Matrix::allocate(
		previous.runtime(),
		flow_shape.clone(),
		workspace_elements(two_planes)?,
		DType::F32,
	)?;
	let flow_b = Matrix::allocate(
		previous.runtime(),
		flow_shape.clone(),
		workspace_elements(two_planes)?,
		DType::F32,
	)?;
	let flow = Matrix::allocate(
		previous.runtime(),
		flow_shape,
		workspace_elements(two_planes)?,
		DType::F32,
	)?;
	let mut stages = Vec::new();
	let mut parent: Option<(&Matrix, u32, u32, bool)> = None;
	for level in (0..levels).rev() {
		let (level_width, level_height) = level_dims[level as usize];
		{
			let expand_input = &previous_levels[level as usize];
			let expand_output = &moments_a;
			let expand_v_buffers = [
				BufferBinding::read(expand_input.storage()),
				BufferBinding::write(expand_output.storage()),
			];
			let expand_v_push = [
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(level_height),
				PushConstant::U32(level_width),
				PushConstant::U32(poly_n),
				PushConstant::F32(poly_sigma),
			];
			stages.push((
				KernelId::ImageFlowExpandVF32,
				expand_v_buffers.to_vec(),
				expand_v_push.to_vec(),
				[
					level_width.div_ceil(16),
					level_height.div_ceil(16),
					plane_count,
				],
			));
		}
		{
			let expand_input = &moments_a;
			let expand_output = &poly1;
			let expand_h_buffers = [
				BufferBinding::read(expand_input.storage()),
				BufferBinding::write(expand_output.storage()),
			];
			let expand_h_push = [
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(level_height),
				PushConstant::U32(level_width),
				PushConstant::U32(poly_n),
				PushConstant::F32(poly_sigma),
			];
			stages.push((
				KernelId::ImageFlowExpandHF32,
				expand_h_buffers.to_vec(),
				expand_h_push.to_vec(),
				[
					level_width.div_ceil(16),
					level_height.div_ceil(16),
					plane_count,
				],
			));
		}
		{
			let expand_input = &next_levels[level as usize];
			let expand_output = &moments_b;
			let expand_v_buffers = [
				BufferBinding::read(expand_input.storage()),
				BufferBinding::write(expand_output.storage()),
			];
			let expand_v_push = [
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(level_height),
				PushConstant::U32(level_width),
				PushConstant::U32(poly_n),
				PushConstant::F32(poly_sigma),
			];
			stages.push((
				KernelId::ImageFlowExpandVF32,
				expand_v_buffers.to_vec(),
				expand_v_push.to_vec(),
				[
					level_width.div_ceil(16),
					level_height.div_ceil(16),
					plane_count,
				],
			));
		}
		{
			let expand_input = &moments_b;
			let expand_output = &poly2;
			let expand_h_buffers = [
				BufferBinding::read(expand_input.storage()),
				BufferBinding::write(expand_output.storage()),
			];
			let expand_h_push = [
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(level_height),
				PushConstant::U32(level_width),
				PushConstant::U32(poly_n),
				PushConstant::F32(poly_sigma),
			];
			stages.push((
				KernelId::ImageFlowExpandHF32,
				expand_h_buffers.to_vec(),
				expand_h_push.to_vec(),
				[
					level_width.div_ceil(16),
					level_height.div_ceil(16),
					plane_count,
				],
			));
		}
		let mut estimate: &Matrix = &flow_a;
		let mut estimate_is_a = true;
		for iteration in 0..iterations {
			let (flow_in, init_mode, flow_in_width, flow_in_height, input_is_a) = if iteration == 0 {
				match parent {
					Some((buffer, width, height, is_a)) => (buffer, 1u32, width, height, is_a),
					None => (&flow_a, 0u32, level_width, level_height, true),
				}
			} else {
				(estimate, 2u32, level_width, level_height, estimate_is_a)
			};
			let output_is_flow = level == 0 && iteration + 1 == iterations;
			let flow_out: &Matrix = if output_is_flow {
				&flow
			} else if input_is_a {
				&flow_b
			} else {
				&flow_a
			};
			let update_buffers = [
				BufferBinding::read(poly1.storage()),
				BufferBinding::read(poly2.storage()),
				BufferBinding::read(flow_in.storage()),
				BufferBinding::write(flow_out.storage()),
			];
			let update_push = [
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(level_height),
				PushConstant::U32(level_width),
				PushConstant::U32(flow_in_height),
				PushConstant::U32(flow_in_width),
				PushConstant::U32(window),
				PushConstant::U32(init_mode),
			];
			stages.push((
				KernelId::ImageFlowUpdateF32,
				update_buffers.to_vec(),
				update_push.to_vec(),
				[
					level_width.div_ceil(16),
					level_height.div_ceil(16),
					plane_count,
				],
			));
			estimate = flow_out;
			estimate_is_a = !input_is_a;
		}
		parent = Some((estimate, level_width, level_height, estimate_is_a));
	}
	let attributes = [
		unsigned("levels", levels),
		unsigned("window", window),
		unsigned("iterations", iterations),
		unsigned("poly_n", poly_n),
		float("poly_sigma", poly_sigma),
	];
	let dispatches: Vec<ComputeDispatch> = stages
		.iter()
		.map(
			|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
				kernel: *kernel,
				buffers: buffers.as_slice(),
				push_constants: push_constants.as_slice(),
				workgroups: *workgroups,
				indirect: None,
			},
		)
		.collect();
	previous.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[
				ImageSemanticInput::Image(previous),
				ImageSemanticInput::Image(next),
			],
			outputs: &[ImageSemanticOutput::Matrix(&flow)],
			attributes: &attributes,
		},
	)?;
	Ok(flow)
}

/// Block-matching stereo disparity over the horizontal search
/// range [0, num_disparities), following cv::StereoBM. The
/// `stereo_sad` pass builds a [planes, num_disparities, H, W]
/// sum-of-absolute-differences volume over an odd block_size
/// window; `stereo_wta` then keeps the per-pixel argmin, applies
/// the `uniqueness` percent runner-up margin test (0 disables),
/// and refines the winner with a symmetric parabola on the
/// neighbouring costs. Pixels outside the border region where
/// the matching window fits for every disparity, and uniqueness
/// losers, are marked -1; the valid range otherwise starts at 0.
/// Returns the F32 [planes, 1, H, W] disparity map.
///
/// # Errors
///
/// Returns an error unless both images are nonempty FP32
/// NCHW/CHW images with identical shape, layout, and format,
/// num_disparities >= 1, block_size is odd and >= 3, and the
/// image fits the combined block and disparity support.
pub fn stereo_bm(
	left: &Image,
	right: &Image,
	num_disparities: u32,
	block_size: u32,
	uniqueness: u32,
) -> Result<Matrix> {
	let (batch, channels, image_height, image_width) =
		validate_accumulation_pair(left, right, "image::stereo_bm")?;
	if num_disparities == 0 || block_size < 3 || block_size.is_multiple_of(2) {
		return Err(Error::invalid_argument(
			"image::stereo_bm requires num_disparities >= 1 and an odd block_size >= 3",
		));
	}
	let support = block_size
		.checked_sub(1)
		.and_then(|value| value.checked_add(num_disparities))
		.ok_or_else(|| Error::out_of_range("image::stereo_bm support exceeds u32"))?;
	if image_width < support || image_height < block_size {
		return Err(Error::invalid_argument(
			"image::stereo_bm requires the image to fit the block and disparity support",
		));
	}
	let plane_count = batch
		.checked_mul(channels)
		.ok_or_else(|| Error::out_of_range("image::stereo_bm plane count exceeds u32"))?;
	let disp_count = plane_count
		.checked_mul(num_disparities)
		.ok_or_else(|| Error::out_of_range("image::stereo_bm disparity slots exceed u32"))?;
	let block_radius = block_size / 2;
	let plane_elements = (image_height as usize)
		.checked_mul(image_width as usize)
		.ok_or_else(|| Error::out_of_range("image::stereo_bm plane size exceeds u32"))?;
	let cost_volume = Matrix::allocate(
		left.runtime(),
		vec![
			plane_count as usize,
			num_disparities as usize,
			image_height as usize,
			image_width as usize,
		],
		plane_elements
			.checked_mul(disp_count as usize)
			.ok_or_else(|| Error::out_of_range("image::stereo_bm cost volume exceeds u32"))?,
		DType::F32,
	)?;
	let output = Matrix::allocate(
		left.runtime(),
		vec![
			plane_count as usize,
			1,
			image_height as usize,
			image_width as usize,
		],
		plane_elements
			.checked_mul(plane_count as usize)
			.ok_or_else(|| Error::out_of_range("image::stereo_bm output size exceeds u32"))?,
		DType::F32,
	)?;
	let contract = crate::core::operation::image::STEREO_BM;
	let mut stages = Vec::new();
	{
		let sad_buffers = [
			BufferBinding::read(left.storage()),
			BufferBinding::read(right.storage()),
			BufferBinding::write(cost_volume.storage()),
		];
		let sad_push = [
			PushConstant::U32(batch),
			PushConstant::U32(channels),
			PushConstant::U32(image_height),
			PushConstant::U32(image_width),
			PushConstant::U32(num_disparities),
			PushConstant::U32(block_radius),
		];
		stages.push((
			KernelId::ImageStereoSadF32,
			sad_buffers.to_vec(),
			sad_push.to_vec(),
			[
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				disp_count,
			],
		));
	}
	{
		let wta_buffers = [
			BufferBinding::read(cost_volume.storage()),
			BufferBinding::write(output.storage()),
		];
		let wta_push = [
			PushConstant::U32(batch),
			PushConstant::U32(channels),
			PushConstant::U32(image_height),
			PushConstant::U32(image_width),
			PushConstant::U32(num_disparities),
			PushConstant::U32(block_radius),
			PushConstant::U32(uniqueness),
		];
		stages.push((
			KernelId::ImageStereoWtaF32,
			wta_buffers.to_vec(),
			wta_push.to_vec(),
			[
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				plane_count,
			],
		));
	}
	let attributes = [
		unsigned("num_disparities", num_disparities),
		unsigned("block_size", block_size),
		unsigned("uniqueness", uniqueness),
	];
	let dispatches: Vec<ComputeDispatch> = stages
		.iter()
		.map(
			|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
				kernel: *kernel,
				buffers: buffers.as_slice(),
				push_constants: push_constants.as_slice(),
				workgroups: *workgroups,
				indirect: None,
			},
		)
		.collect();
	left.runtime().record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract,
			inputs: &[
				ImageSemanticInput::Image(left),
				ImageSemanticInput::Image(right),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Per-pixel reprojection of a disparity map into 3D
/// coordinates, following cv::reprojectImageTo3D. For each
/// pixel it evaluates (X, Y, Z, W) = Q * [x, y, disparity, 1]
/// with the row-major 4x4 F32 matrix `q`, then writes the
/// normalized coordinates X/W, Y/W, Z/W. `disparity` must be
/// F32 [planes, 1, H, W] (the stereo_bm output layout) and
/// `q` F32 [4, 4]; the homogeneous divide is unguarded, so a
/// degenerate last row surfaces as inf/NaN. Returns the F32
/// [planes, 3, H, W] coordinate map.
///
/// # Errors
///
/// Returns an error unless `disparity` is F32 with shape
/// [planes, 1, H, W] and `q` is F32 [4, 4] on the same
/// runtime.
pub fn reproject_image_to_3d(disparity: &Matrix, q: &Matrix) -> Result<Matrix> {
	if disparity.dtype() != DType::F32 || q.dtype() != DType::F32 {
		return Err(Error::invalid_argument(
			"image::reproject_image_to_3d requires F32 disparity and q matrices",
		));
	}
	if disparity.shape().len() != 4 || disparity.shape()[1] != 1 {
		return Err(Error::invalid_argument(
			"image::reproject_image_to_3d requires a [planes, 1, H, W] disparity matrix",
		));
	}
	if q.shape() != [4, 4] {
		return Err(Error::invalid_argument(
			"image::reproject_image_to_3d requires a [4, 4] q matrix",
		));
	}
	let plane_count = u32::try_from(disparity.shape()[0])
		.map_err(|_| Error::out_of_range("image::reproject_image_to_3d plane count exceeds u32"))?;
	let height = u32::try_from(disparity.shape()[2])
		.map_err(|_| Error::out_of_range("image::reproject_image_to_3d height exceeds u32"))?;
	let width = u32::try_from(disparity.shape()[3])
		.map_err(|_| Error::out_of_range("image::reproject_image_to_3d width exceeds u32"))?;
	if plane_count == 0 || height == 0 || width == 0 {
		return Err(Error::invalid_argument(
			"image::reproject_image_to_3d requires a nonempty disparity matrix",
		));
	}
	let plane_elements = (height as usize)
		.checked_mul(width as usize)
		.ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d plane size exceeds u32"))?;
	let output = Matrix::allocate(
		disparity.runtime(),
		vec![plane_count as usize, 3, height as usize, width as usize],
		plane_elements
			.checked_mul(3)
			.and_then(|count| count.checked_mul(plane_count as usize))
			.ok_or_else(|| Error::out_of_range("image::reproject_image_to_3d output size exceeds u32"))?,
		DType::F32,
	)?;
	let attributes = [];
	disparity.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageReproject3dF32,
			buffers: &[
				BufferBinding::read(disparity.storage()),
				BufferBinding::read(q.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(plane_count),
				PushConstant::U32(1),
				PushConstant::U32(height),
				PushConstant::U32(width),
			],
			workgroups: [width.div_ceil(16), height.div_ceil(16), plane_count],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::REPROJECT_IMAGE_TO_3D,
			inputs: &[
				ImageSemanticInput::Matrix(disparity),
				ImageSemanticInput::Matrix(q),
			],
			outputs: &[ImageSemanticOutput::Matrix(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Non-local means denoising over a search window,
/// following cv::fastNlMeansDenoising. Each output pixel is
/// the weighted mean of samples in the (search_window)^2
/// neighbourhood with weights exp(-d / h^2), where d is the
/// patch SSD over an odd template_window normalized by its
/// area; the center weight equals the largest neighbour
/// weight so a uniform region stays untouched. Returns an
/// image with identical shape, layout, and format.
///
/// # Errors
///
/// Returns an error unless `input` is a nonempty FP32
/// NCHW/CHW image, `h` is finite and positive, and both
/// windows are odd and at least 3.
pub fn fast_nl_means_denoising(
	input: &Image,
	h: f32,
	template_window: u32,
	search_window: u32,
) -> Result<Image> {
	let (batch, channels, image_height, image_width) =
		image_extent(input, "image::fast_nl_means_denoising")?;
	if !h.is_finite() || h <= 0.0 {
		return Err(Error::invalid_argument(
			"image::fast_nl_means_denoising requires a finite positive h",
		));
	}
	if template_window < 3
		|| template_window.is_multiple_of(2)
		|| search_window < 3
		|| search_window.is_multiple_of(2)
	{
		return Err(Error::invalid_argument(
			"image::fast_nl_means_denoising requires odd template_window/search_window >= 3",
		));
	}
	let template_radius = template_window / 2;
	let search_radius = search_window / 2;
	let h_sqr = h * h;
	let output = allocate_like(input, "image::fast_nl_means_denoising")?;
	let attributes = [
		float("h", h),
		unsigned("template_window", template_window),
		unsigned("search_window", search_window),
	];
	input.runtime().record_image_semantic(
		ComputeDispatch {
			kernel: KernelId::ImageNlMeansDenoiseF32,
			buffers: &[
				BufferBinding::read(input.storage()),
				BufferBinding::write(output.storage()),
			],
			push_constants: &[
				PushConstant::U32(batch),
				PushConstant::U32(channels),
				PushConstant::U32(image_height),
				PushConstant::U32(image_width),
				PushConstant::U32(template_radius),
				PushConstant::U32(search_radius),
				PushConstant::F32(h_sqr),
			],
			workgroups: [
				image_width.div_ceil(16),
				image_height.div_ceil(16),
				batch * channels,
			],
			indirect: None,
		},
		ImageSemanticDispatch {
			contract: crate::core::operation::image::FAST_NL_MEANS_DENOISING,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

/// Pyramid mean-shift edge-preserving smoothing, following
/// cv::pyrMeanShiftFiltering. The image is downsampled
/// max_level times with pyr_down; each level then runs a
/// per-pixel mean-shift pass that, for up to five
/// iterations, averages the (2*sp+1)^2 window samples whose
/// channel-vector distance stays below sr and adopts that
/// mean position and color, converging when the spatial
/// shift drops under one pixel. Coarse-to-fine levels seed
/// their starting color from the parent's converged result.
/// Channels participate as one color vector per plane
/// pixel; returns an image with identical shape, layout,
/// and format.
///
/// # Errors
///
/// Returns an error unless `input` is a nonempty FP32
/// NCHW/CHW image with at most 4 channels, sp/sr are finite
/// and positive, max_level is in [1, 4], and the coarsest
/// level still fits the spatial window support.
pub fn pyr_mean_shift_filtering(input: &Image, sp: f32, sr: f32, max_level: u32) -> Result<Image> {
	let (batch, channels, image_height, image_width) =
		image_extent(input, "image::pyr_mean_shift_filtering")?;
	if !sp.is_finite() || sp <= 0.0 || !sr.is_finite() || sr <= 0.0 {
		return Err(Error::invalid_argument(
			"image::pyr_mean_shift_filtering requires finite positive sp and sr",
		));
	}
	if channels > 4 {
		return Err(Error::invalid_argument(
			"image::pyr_mean_shift_filtering supports at most 4 channels",
		));
	}
	if !(1..=4).contains(&max_level) {
		return Err(Error::invalid_argument(
			"image::pyr_mean_shift_filtering requires max_level in [1, 4]",
		));
	}
	let levels = max_level
		.checked_add(1)
		.ok_or_else(|| Error::out_of_range("image::pyr_mean_shift_filtering max_level exceeds u32"))?;
	let spatial_radius = sp.ceil() as u32;
	let range_radius_sqr = sr * sr;
	let mut level_images = Vec::with_capacity(levels as usize);
	let mut level_dims = Vec::with_capacity(levels as usize);
	level_images.push(input.clone());
	level_dims.push((image_width, image_height));
	for _ in 1..levels {
		level_images.push(crate::image::pyr_down(level_images.last().ok_or_else(
			|| Error::internal("image::pyr_mean_shift_filtering pyramid level missing"),
		)?)?);
		let (width, height) = level_dims[level_dims.len() - 1];
		level_dims.push((width.div_ceil(2), height.div_ceil(2)));
	}
	let runtime = input.runtime();
	// `converged[level]` storage: the returned Image for level 0,
	// workspaces[level - 1] for coarser levels. Workspaces are allocated
	// up front because dispatch bindings hold stable `&Storage` borrows.
	let mut workspaces = Vec::with_capacity(levels as usize - 1);
	for level in 1..levels {
		let (level_width, level_height) = level_dims[level as usize];
		let count = (batch as usize)
			.checked_mul(channels as usize)
			.and_then(|value| value.checked_mul(level_height as usize))
			.and_then(|value| value.checked_mul(level_width as usize))
			.ok_or_else(|| {
				Error::out_of_range("image::pyr_mean_shift_filtering workspace exceeds usize")
			})?;
		workspaces.push(Matrix::allocate(
			runtime,
			vec![
				batch as usize,
				channels as usize,
				level_height as usize,
				level_width as usize,
			],
			count,
			DType::F32,
		)?);
	}
	let output = allocate_like(input, "image::pyr_mean_shift_filtering")?;
	let mut stages = Vec::new();
	for level in (0..levels).rev() {
		let (level_width, level_height) = level_dims[level as usize];
		let shift_input = level_images[level as usize].as_matrix();
		let shift_output: &Matrix = if level == 0 {
			output.as_matrix()
		} else {
			&workspaces[level as usize - 1]
		};
		// Levels below the coarsest seed their starting color from the
		// parent's converged result (level + 1, stored at workspaces[level]).
		let (shift_seed, seed_width, seed_height, init_mode) = if level + 1 == levels {
			(shift_input, level_width, level_height, 0u32)
		} else {
			let (seed_width, seed_height) = level_dims[level as usize + 1];
			(&workspaces[level as usize], seed_width, seed_height, 1u32)
		};
		let pass_buffers = [
			BufferBinding::read(shift_input.storage()),
			BufferBinding::read(shift_seed.storage()),
			BufferBinding::write(shift_output.storage()),
		];
		let pass_push = [
			PushConstant::U32(batch),
			PushConstant::U32(channels),
			PushConstant::U32(level_height),
			PushConstant::U32(level_width),
			PushConstant::U32(seed_width),
			PushConstant::U32(seed_height),
			PushConstant::U32(spatial_radius),
			PushConstant::U32(5),
			PushConstant::U32(init_mode),
			PushConstant::F32(range_radius_sqr),
		];
		stages.push((
			KernelId::ImageMeanShiftPassF32,
			pass_buffers.to_vec(),
			pass_push.to_vec(),
			[level_width.div_ceil(16), level_height.div_ceil(16), batch],
		));
	}
	let attributes = [
		float("sp", sp),
		float("sr", sr),
		unsigned("max_level", max_level),
	];
	let dispatches: Vec<ComputeDispatch> = stages
		.iter()
		.map(
			|(kernel, buffers, push_constants, workgroups)| ComputeDispatch {
				kernel: *kernel,
				buffers: buffers.as_slice(),
				push_constants: push_constants.as_slice(),
				workgroups: *workgroups,
				indirect: None,
			},
		)
		.collect();
	runtime.record_image_split_semantic(
		&dispatches,
		ImageSemanticDispatch {
			contract: crate::core::operation::image::PYR_MEAN_SHIFT_FILTERING,
			inputs: &[ImageSemanticInput::Image(input)],
			outputs: &[ImageSemanticOutput::Image(&output)],
			attributes: &attributes,
		},
	)?;
	Ok(output)
}

fn image_extent(input: &Image, operation: &str) -> Result<(u32, u32, u32, u32)> {
	if input.dtype() != DType::F32 || !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw)
	{
		return Err(Error::invalid_argument(format!(
			"{operation} requires an FP32 NCHW or CHW image"
		)));
	}
	let values = [
		input.batch_size(),
		input.channels(),
		input.height(),
		input.width(),
	];
	if values.contains(&0) {
		return Err(Error::invalid_argument(format!(
			"{operation} requires a nonempty image"
		)));
	}
	Ok((
		u32::try_from(values[0]).map_err(|_| Error::out_of_range("image batch exceeds u32"))?,
		u32::try_from(values[1]).map_err(|_| Error::out_of_range("image channels exceed u32"))?,
		u32::try_from(values[2]).map_err(|_| Error::out_of_range("image height exceeds u32"))?,
		u32::try_from(values[3]).map_err(|_| Error::out_of_range("image width exceeds u32"))?,
	))
}

fn allocate_like(input: &Image, operation: &str) -> Result<Image> {
	let elements = input.as_matrix().num_elements();
	u32::try_from(elements)
		.map_err(|_| Error::out_of_range(format!("{operation} output size exceeds u32")))?;
	let matrix = Matrix::allocate(
		input.runtime(),
		input.as_matrix().shape().to_vec(),
		elements,
		DType::F32,
	)?;
	Image::new(matrix, input.layout(), input.format())
}

fn float(name: &str, value: f32) -> OpAttribute {
	OpAttribute::Float {
		name: name.into(),
		value: f64::from(value),
	}
}
fn unsigned(name: &str, value: u32) -> OpAttribute {
	OpAttribute::UnsignedInteger {
		name: name.into(),
		value: u64::from(value),
	}
}
fn enumeration(name: &str, value: &str) -> OpAttribute {
	OpAttribute::Enum {
		name: name.into(),
		value: value.into(),
	}
}

fn validate_accumulation_pair(
	first: &Image,
	second: &Image,
	operation: &str,
) -> Result<(u32, u32, u32, u32)> {
	let extent = image_extent(first, operation)?;
	if second.as_matrix().shape() != first.as_matrix().shape()
		|| second.layout() != first.layout()
		|| second.format() != first.format()
		|| second.dtype() != first.dtype()
	{
		return Err(Error::invalid_argument(format!(
			"{operation} requires identically shaped FP32 images"
		)));
	}
	Ok(extent)
}