Source file frontend.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
open Bigarray_ext
module Make (B : Backend_intf.S) = struct
module B = B
type ('a, 'b) t = ('a, 'b) B.t
type context = B.context
type float16_elt = Bigarray_ext.float16_elt
type float32_elt = Bigarray_ext.float32_elt
type float64_elt = Bigarray_ext.float64_elt
type int8_elt = Bigarray_ext.int8_signed_elt
type uint8_elt = Bigarray_ext.int8_unsigned_elt
type int16_elt = Bigarray_ext.int16_signed_elt
type uint16_elt = Bigarray_ext.int16_unsigned_elt
type int32_elt = Bigarray_ext.int32_elt
type int64_elt = Bigarray_ext.int64_elt
type int_elt = Bigarray_ext.int_elt
type nativeint_elt = Bigarray_ext.nativeint_elt
type complex32_elt = Bigarray_ext.complex32_elt
type complex64_elt = Bigarray_ext.complex64_elt
type bfloat16_elt = Bigarray_ext.bfloat16_elt
type bool_elt = Bigarray_ext.bool_elt
type int4_elt = Bigarray_ext.int4_signed_elt
type uint4_elt = Bigarray_ext.int4_unsigned_elt
type float8_e4m3_elt = Bigarray_ext.float8_e4m3_elt
type float8_e5m2_elt = Bigarray_ext.float8_e5m2_elt
type complex16_elt = Bigarray_ext.complex16_elt
type qint8_elt = Bigarray_ext.qint8_elt
type quint8_elt = Bigarray_ext.quint8_elt
type ('a, 'b) dtype = ('a, 'b) Dtype.t =
| Float16 : (float, float16_elt) dtype
| Float32 : (float, float32_elt) dtype
| Float64 : (float, float64_elt) dtype
| Int8 : (int, int8_elt) dtype
| UInt8 : (int, uint8_elt) dtype
| Int16 : (int, int16_elt) dtype
| UInt16 : (int, uint16_elt) dtype
| Int32 : (int32, int32_elt) dtype
| Int64 : (int64, int64_elt) dtype
| Int : (int, int_elt) dtype
| NativeInt : (nativeint, nativeint_elt) dtype
| Complex32 : (Complex.t, complex32_elt) dtype
| Complex64 : (Complex.t, complex64_elt) dtype
| BFloat16 : (float, bfloat16_elt) dtype
| Bool : (bool, bool_elt) dtype
| Int4 : (int, int4_elt) dtype
| UInt4 : (int, uint4_elt) dtype
| Float8_e4m3 : (float, float8_e4m3_elt) dtype
| Float8_e5m2 : (float, float8_e5m2_elt) dtype
| Complex16 : (Complex.t, complex16_elt) dtype
| QInt8 : (int, qint8_elt) dtype
| QUInt8 : (int, quint8_elt) dtype
type float16_t = (float, float16_elt) t
type float32_t = (float, float32_elt) t
type float64_t = (float, float64_elt) t
type int8_t = (int, int8_elt) t
type uint8_t = (int, uint8_elt) t
type int16_t = (int, int16_elt) t
type uint16_t = (int, uint16_elt) t
type int32_t = (int32, int32_elt) t
type int64_t = (int64, int64_elt) t
type std_int_t = (int, int_elt) t
type std_nativeint_t = (nativeint, nativeint_elt) t
type complex32_t = (Complex.t, complex32_elt) t
type complex64_t = (Complex.t, complex64_elt) t
let float16 = Float16
let float32 = Float32
let float64 = Float64
let int8 = Int8
let uint8 = UInt8
let int16 = Int16
let uint16 = UInt16
let int32 = Int32
let int64 = Int64
let int = Int
let nativeint = NativeInt
let complex32 = Complex32
let complex64 = Complex64
type index =
| I of int
| L of int list
| R of int * int
| Rs of int * int * int
| A
| M of (int, uint8_elt) t
| N
let data x = B.data x
let shape x =
let view = B.view x in
match Symbolic_shape.eval (Lazy_view.shape view) with
| Some arr -> arr
| None ->
Error.failed ~op:"shape"
~what:"cannot get shape with unbound symbolic dimensions" ()
let dtype x = B.dtype x
let itemsize x = Dtype.itemsize (B.dtype x)
let strides x =
let view = B.view x in
let itemsize = itemsize x in
match Lazy_view.strides view with
| None ->
let reason =
if not (Lazy_view.is_materializable view) then
"view has non-materializable layout"
else if not (Symbolic_shape.is_static (Lazy_view.shape view)) then
"view has symbolic shape"
else "view has complex striding pattern"
in
Error.failed ~op:"strides" ~what:reason
~hint:"call contiguous() to get a standard layout" ()
| Some elem_strides -> Array.map (fun s -> s * itemsize) elem_strides
let stride i x =
let view = B.view x in
let itemsize = itemsize x in
match Lazy_view.strides view with
| None ->
Error.failed ~op:"stride"
~what:(Printf.sprintf "stride for dimension %d" i)
~reason:"tensor does not have defined strides"
~hint:"call contiguous() first or check has_strides()" ()
| Some elem_strides ->
let ndim = Lazy_view.ndim view in
let i = if i < 0 then i + ndim else i in
if i < 0 || i >= ndim then
Error.axis_out_of_bounds ~op:"stride" ~axis:i ~ndim ()
else elem_strides.(i) * itemsize
let dims x =
let view = B.view x in
let sym_shape = Lazy_view.shape view in
match Symbolic_shape.eval sym_shape with
| Some arr -> arr
| None ->
Error.failed ~op:"dims"
~what:"cannot get dimensions with unbound symbolic values" ()
let dim i x =
let view = B.view x in
let shape = Lazy_view.shape view in
let ndim = Symbolic_shape.rank shape in
let i = if i < 0 then i + ndim else i in
if i < 0 || i >= ndim then
Error.axis_out_of_bounds ~op:"dim" ~axis:i ~ndim ()
else
match Symbolic_shape.eval_dim shape.(i) with
| Some n -> n
| None ->
Error.failed ~op:"dim"
~what:"cannot get dimension with unbound symbolic value" ()
let ndim x =
let view = B.view x in
Lazy_view.ndim view
let size x =
let view = B.view x in
match Symbolic_shape.eval_dim (Lazy_view.numel view) with
| Some n -> n
| None ->
Error.failed ~op:"size"
~what:"cannot get size of tensor with symbolic shape"
~hint:"bind symbolic dimensions first" ()
let numel x = size x
let nbytes x =
let itemsize = itemsize x in
try numel x * itemsize
with _ ->
Error.failed ~op:"nbytes" ~what:"cannot compute bytes for symbolic tensor"
()
let offset x =
let view = B.view x in
match Symbolic_shape.eval_dim (Lazy_view.offset view) with
| Some n -> n
| None ->
Error.failed ~op:"offset" ~what:"tensor has symbolic offset"
~hint:"bind symbolic variables first" ()
let is_c_contiguous x =
let view = B.view x in
Lazy_view.is_contiguous view
let power_of_two : type a b. (a, b) Dtype.t -> int -> a =
fun dtype shift_val ->
if shift_val < 0 then
Error.check_bounds ~op:"power_of_two" ~name:"shift_val" ~value:shift_val
~min:0 ();
match dtype with
| Int8 | UInt8 | Int16 | UInt16 | Int | NativeInt -> (
let power = 1 lsl shift_val in
match dtype with
| Int8 -> power
| UInt8 -> power land 0xFF
| Int16 -> power
| UInt16 -> power land 0xFFFF
| Int -> power
| NativeInt -> Nativeint.shift_left Nativeint.one shift_val
| _ -> Error.failed ~op:"power_of_two" ~what:"unreachable code path" ())
| Int32 -> Int32.shift_left Int32.one shift_val
| Int64 -> Int64.shift_left Int64.one shift_val
| _ ->
Error.invalid ~op:"power_of_two"
~what:(Printf.sprintf "dtype %s" (Dtype.to_string dtype))
~reason:"not an integer type"
~hint:
"use Int8, UInt8, Int16, UInt16, Int32, Int64, Int, or NativeInt"
()
let array_prod arr = Array.fold_left ( * ) 1 arr
(** Integer ceiling division: (a + b - 1) / b for integers a, b where b > 0.
*)
let ceildiv a b =
Error.check_bounds ~op:"ceildiv" ~name:"divisor" ~value:b ~min:1 ();
(a + b - 1) / b
let ensure_float_dtype fname x =
if not (Dtype.is_float (dtype x)) then
Error.invalid ~op:fname
~what:(Printf.sprintf "dtype %s" (Dtype.to_string (dtype x)))
~reason:"expected float type (Float16, Float32, or Float64)" ()
let ensure_int_dtype fname x =
if not (Dtype.is_int (dtype x)) then
Error.invalid ~op:fname ~what:"dtype" ~reason:"must be an integer type" ()
let pair_to_array (a, b) = [| a; b |]
let resolve_axis ?ndim_opt x (axis_opt : int option) =
let ndim = match ndim_opt with Some n -> n | None -> ndim x in
match axis_opt with
| None -> Array.init ndim Fun.id
| Some a ->
let resolved_a = if a < 0 then a + ndim else a in
[| resolved_a |]
let resolve_single_axis ?ndim_opt x axis : int =
let ndim = match ndim_opt with Some n -> n | None -> ndim x in
if axis < 0 then axis + ndim else axis
let reshape shape_spec x =
let new_shape = Shape.resolve_neg_one (shape x) shape_spec in
if shape x = new_shape then x
else B.op_reshape x (Symbolic_shape.of_ints new_shape)
let broadcast_to new_shape x =
let current_shape = shape x in
if current_shape = new_shape then x
else
let rank_current = Array.length current_shape in
let rank_new = Array.length new_shape in
if rank_current > rank_new then
Error.cannot ~op:"broadcast_to" ~what:"broadcast"
~from:
(Printf.sprintf "%s (rank %d)"
(Shape.to_string current_shape)
rank_current)
~to_:
(Printf.sprintf "%s (rank %d)" (Shape.to_string new_shape) rank_new)
~reason:(Printf.sprintf "rank mismatch: %d>%d" rank_current rank_new)
~hint:"target shape must have at least as many dimensions as source"
()
else
let padded_shape =
if rank_current < rank_new then
Array.append (Array.make (rank_new - rank_current) 1) current_shape
else current_shape
in
let compatible = ref true in
let first_incompatible = ref None in
for i = 0 to rank_new - 1 do
if not (padded_shape.(i) = new_shape.(i) || padded_shape.(i) = 1) then (
compatible := false;
if !first_incompatible = None then first_incompatible := Some i)
done;
if not !compatible then
match !first_incompatible with
| Some _ ->
Error.broadcast_incompatible ~op:"broadcast_to"
~shape1:current_shape ~shape2:new_shape ()
| None -> assert false
else
let x_reshaped =
if padded_shape <> current_shape then reshape padded_shape x else x
in
B.op_expand x_reshaped (Symbolic_shape.of_ints new_shape)
let broadcasted ?(reverse = false) x y =
let a, b = if reverse then (y, x) else (x, y) in
let broadcast_shape = Shape.broadcast (shape a) (shape b) in
let a_broad = broadcast_to broadcast_shape a in
let b_broad = broadcast_to broadcast_shape b in
(a_broad, b_broad)
let expand shape_spec x =
let current_shape = shape x in
let rank_current = Array.length current_shape in
let rank_spec = Array.length shape_spec in
let rank_new = max rank_current rank_spec in
let current_aligned =
if rank_current < rank_new then
Array.append (Array.make (rank_new - rank_current) 1) current_shape
else current_shape
in
let spec_aligned =
if rank_spec < rank_new then
Array.append (Array.make (rank_new - rank_spec) (-1)) shape_spec
else shape_spec
in
let new_shape =
Array.mapi
(fun i spec_dim ->
if spec_dim = -1 then current_aligned.(i) else spec_dim)
spec_aligned
in
broadcast_to new_shape x
let cast (type a b c d) (dt : (c, d) Dtype.t) (x : (a, b) t) : (c, d) t =
match Dtype.equal_witness (dtype x) dt with
| Some Equal ->
B.op_copy x
| None -> B.op_cast x dt
let astype dt x = cast dt x
let contiguous x = B.op_contiguous x
let copy x = B.op_copy x
let blit src dst =
if shape src <> shape dst then
Error.shape_mismatch ~op:"blit" ~expected:(shape dst) ~actual:(shape src)
~hint:"source and destination must have identical shapes" ();
B.op_assign dst src
let create ctx dtype shape arr =
let n = Array.fold_left ( * ) 1 shape in
if Array.length arr <> n then
Error.invalid ~op:"create" ~what:"array size"
~reason:
(Printf.sprintf "got %d elements, expected %d" (Array.length arr) n)
();
let kind = Dtype.to_bigarray_ext_kind dtype in
let bigarray = Bigarray_ext.Array1.create kind c_layout n in
for i = 0 to n - 1 do
Bigarray_ext.Array1.unsafe_set bigarray i arr.(i)
done;
let tensor_1d = B.op_const_array ctx bigarray in
if Array.length shape = 1 && shape.(0) = n then tensor_1d
else B.op_reshape tensor_1d (Symbolic_shape.of_ints shape)
let init ctx dtype shape f =
let size = Array.fold_left ( * ) 1 shape in
let unravel_index idx shape =
let ndim = Array.length shape in
let indices = Array.make ndim 0 in
let remaining = ref idx in
for i = 0 to ndim - 1 do
let stride =
Array.fold_left ( * ) 1 (Array.sub shape (i + 1) (ndim - i - 1))
in
indices.(i) <- !remaining / stride;
remaining := !remaining mod stride
done;
indices
in
let arr = Array.init size (fun i -> f (unravel_index i shape)) in
create ctx dtype shape arr
let scalar ctx dt value = B.op_const_scalar ctx value dt
let scalar_like x_ref value = scalar (B.context x_ref) (B.dtype x_ref) value
let fill value x =
let value_tensor = scalar_like x value in
let value_broadcasted = broadcast_to (shape x) value_tensor in
B.op_assign x value_broadcasted;
x
let empty ctx dtype shape_arr =
let numel = array_prod shape_arr in
let buf = B.op_buffer ctx dtype numel in
reshape shape_arr buf
let zeros ctx dtype shape_arr =
let numel = array_prod shape_arr in
let buf = B.op_buffer ctx dtype numel in
let t = reshape shape_arr buf in
fill (Dtype.zero dtype) t
let ones ctx dtype shape_arr =
let numel = array_prod shape_arr in
let buf = B.op_buffer ctx dtype numel in
let t = reshape shape_arr buf in
fill (Dtype.one dtype) t
let full ctx dt target_shape fill_value =
let numel = array_prod target_shape in
let buf = B.op_buffer ctx dt numel in
let t = reshape target_shape buf in
fill fill_value t
let create_like x_ref fill_fn =
let dtype = B.dtype x_ref in
let shape = shape x_ref in
fill_fn (B.context x_ref) dtype shape
let empty_like x_ref = create_like x_ref empty
let full_like x_ref fill_value =
create_like x_ref (fun ctx dt sh -> full ctx dt sh fill_value)
let zeros_like x = full_like x (Dtype.zero (B.dtype x))
let ones_like x = full_like x (Dtype.one (B.dtype x))
let to_bigarray_ext x =
let ensure_contiguous_size t =
let t = if is_c_contiguous t && offset t = 0 then t else contiguous t in
let buffer = data t in
let buffer_elems = Bigarray_ext.Array1.dim buffer in
if buffer_elems = numel t then t else copy t
in
let t_to_use = ensure_contiguous_size x in
let array1 = data t_to_use in
Bigarray_ext.reshape
(Bigarray_ext.genarray_of_array1 array1)
(shape t_to_use)
let to_bigarray x =
let ba_ext = to_bigarray_ext x in
let _ = Dtype.to_bigarray_kind (B.dtype x) in
(Obj.magic ba_ext : ('a, 'b, Bigarray.c_layout) Bigarray.Genarray.t)
let of_bigarray_ext ctx ba =
let size = Array.fold_left ( * ) 1 (Bigarray_ext.Genarray.dims ba) in
let arr = Bigarray_ext.reshape_1 ba size in
let shape = Bigarray_ext.Genarray.dims ba in
let flat_xensor = B.op_const_array ctx arr in
reshape shape flat_xensor
let of_bigarray ctx ba =
let ba_ext : ('a, 'b, Bigarray_ext.c_layout) Bigarray_ext.Genarray.t =
Obj.magic ba
in
of_bigarray_ext ctx ba_ext
let to_array x =
let t_contiguous = contiguous x in
let ba = data t_contiguous in
let n = numel t_contiguous in
Array.init n (fun i -> Bigarray_ext.Array1.get ba i)
let binop op a b =
let a', b' = broadcasted a b in
op a' b'
let scalar_op op tensor scalar_val =
let scalar_tensor = scalar_like tensor scalar_val in
op tensor scalar_tensor
let scalar_binop op tensor scalar_val =
let scalar_tensor = scalar_like tensor scalar_val in
op tensor scalar_tensor
let reverse_scalar_op op scalar_val tensor =
let scalar_tensor = scalar_like tensor scalar_val in
op scalar_tensor tensor
let inplace_op op target value =
let value_broadcasted = broadcast_to (shape target) value in
let result = op target value_broadcasted in
B.op_assign target result;
target
let inplace_scalar_op op target scalar_val =
let scalar_tensor = scalar_like target scalar_val in
inplace_op op target scalar_tensor
let add a b = binop B.op_add a b
let add_s tensor scalar = scalar_op add tensor scalar
let iadd target value = inplace_op B.op_add target value
let radd_s tensor value = reverse_scalar_op add tensor value
let iadd_s tensor value = inplace_scalar_op B.op_add tensor value
let sub a b =
let a', b' = broadcasted a b in
let neg_b = B.op_neg b' in
B.op_add a' neg_b
let sub_s tensor_a scalar_b_val = scalar_binop sub tensor_a scalar_b_val
let rsub_s tensor value = reverse_scalar_op sub tensor value
let isub target_tensor value_tensor =
let value_tensor_broadcasted =
broadcast_to (shape target_tensor) value_tensor
in
let neg_value_tensor = B.op_neg value_tensor_broadcasted in
let result = B.op_add target_tensor neg_value_tensor in
B.op_assign target_tensor result;
target_tensor
let isub_s target_tensor scalar_val =
let scalar_tensor = scalar_like target_tensor scalar_val in
let neg_scalar = B.op_neg scalar_tensor in
inplace_op B.op_add target_tensor neg_scalar
let mul a b =
let a', b' = broadcasted a b in
B.op_mul a' b'
let mul_s tensor_a scalar_b_val = scalar_binop mul tensor_a scalar_b_val
let rmul_s tensor value = reverse_scalar_op mul tensor value
let imul target_tensor value_tensor =
let value_tensor_broadcasted =
broadcast_to (shape target_tensor) value_tensor
in
let result = B.op_mul target_tensor value_tensor_broadcasted in
B.op_assign target_tensor result;
target_tensor
let imul_s tensor value = inplace_scalar_op B.op_mul tensor value
let div a b =
let dt = dtype a in
let a_b, b_b = broadcasted a b in
match dt with
| dt when Dtype.is_float dt || Dtype.is_complex dt ->
B.op_fdiv a_b b_b
| dt when Dtype.is_int dt || Dtype.is_uint dt ->
B.op_idiv a_b b_b
| _ ->
failwith "Unsupported dtype for division"
let div_s tensor_a scalar_b_val = scalar_binop div tensor_a scalar_b_val
let rdiv_s tensor value = reverse_scalar_op div tensor value
let idiv target value =
let value_broadcasted = broadcast_to (shape target) value in
let dt = dtype target in
let result =
match dt with
| dt when Dtype.is_float dt || Dtype.is_complex dt ->
B.op_fdiv target value_broadcasted
| dt when Dtype.is_int dt || Dtype.is_uint dt ->
B.op_idiv target value_broadcasted
| _ ->
Error.invalid ~op:"idiv"
~what:("dtype " ^ Dtype.to_string dt)
~reason:"not supported" ()
in
B.op_assign target result;
target
let idiv_s target scalar_val =
let scalar_tensor = scalar_like target scalar_val in
idiv target scalar_tensor
let pow a b =
let a', b' = broadcasted a b in
B.op_pow a' b'
let pow_s tensor_a scalar_b_val = scalar_binop pow tensor_a scalar_b_val
let rpow_s tensor value = reverse_scalar_op pow tensor value
let ipow target_tensor value_tensor =
let value_tensor_broadcasted =
broadcast_to (shape target_tensor) value_tensor
in
let result = B.op_pow target_tensor value_tensor_broadcasted in
B.op_assign target_tensor result;
target_tensor
let ipow_s tensor value = inplace_scalar_op B.op_pow tensor value
let maximum a b =
let a', b' = broadcasted a b in
B.op_max a' b'
let maximum_s tensor_a scalar_b_val =
scalar_binop maximum tensor_a scalar_b_val
let rmaximum_s tensor value = reverse_scalar_op maximum tensor value
let imaximum target_tensor value_tensor =
let value_tensor_broadcasted =
broadcast_to (shape target_tensor) value_tensor
in
let result = B.op_max target_tensor value_tensor_broadcasted in
B.op_assign target_tensor result;
target_tensor
let imaximum_s tensor value = inplace_scalar_op B.op_max tensor value
let minimum a b =
let a', b' = broadcasted a b in
let mask = B.op_cmplt a' b' in
B.op_where mask a' b'
let minimum_s tensor_a scalar_b_val =
scalar_binop minimum tensor_a scalar_b_val
let rminimum_s tensor value = reverse_scalar_op minimum tensor value
let iminimum target_tensor value_tensor =
let value_tensor_broadcasted =
broadcast_to (shape target_tensor) value_tensor
in
let target_neg = B.op_neg target_tensor in
let value_b_neg = B.op_neg value_tensor_broadcasted in
let max_of_negs = B.op_max target_neg value_b_neg in
let result = B.op_neg max_of_negs in
B.op_assign target_tensor result;
target_tensor
let iminimum_s target_tensor scalar_val =
let scalar_value_tensor = scalar_like target_tensor scalar_val in
let scalar_broadcasted =
broadcast_to (shape target_tensor) scalar_value_tensor
in
let target_neg = B.op_neg target_tensor in
let scalar_b_neg = B.op_neg scalar_broadcasted in
let max_of_negs = B.op_max target_neg scalar_b_neg in
let result = B.op_neg max_of_negs in
B.op_assign target_tensor result;
target_tensor
let mod_ a b =
let a', b' = broadcasted a b in
B.op_mod a' b'
let mod_s tensor_a scalar_b_val = scalar_binop mod_ tensor_a scalar_b_val
let rmod_s tensor value = reverse_scalar_op mod_ tensor value
let imod target value = inplace_op B.op_mod target value
let imod_s tensor value = inplace_scalar_op B.op_mod tensor value
let bitwise_xor a b =
let a', b' = broadcasted a b in
B.op_xor a' b'
let bitwise_or a b =
let a', b' = broadcasted a b in
B.op_or a' b'
let bitwise_and a b =
let a', b' = broadcasted a b in
B.op_and a' b'
let logical_and a b =
let a_b, b_b = broadcasted a b in
B.op_and a_b b_b
let logical_or a b =
let a_b, b_b = broadcasted a b in
B.op_or a_b b_b
let logical_xor a b =
let a_b, b_b = broadcasted a b in
B.op_xor a_b b_b
let logical_not (type a b) (a : (a, b) t) =
let dt = dtype a in
match dt with
| Dtype.UInt8 | Dtype.Bool | Dtype.UInt4 | Dtype.QUInt8 ->
let one_val = Dtype.one dt in
let one_tensor = full (B.context a) dt (shape a) one_val in
B.op_xor a one_tensor
| Dtype.Float16 | Dtype.Float32 | Dtype.Float64 | Dtype.Int32 | Dtype.Int64
| Dtype.Int8 | Dtype.Int16 | Dtype.UInt16 | Dtype.Int | Dtype.NativeInt
| Dtype.Complex32 | Dtype.Complex64 | Dtype.BFloat16 | Dtype.Int4
| Dtype.Float8_e4m3 | Dtype.Float8_e5m2 | Dtype.Complex16 | Dtype.QInt8 ->
let one_val = Dtype.one dt in
let one_tensor = full (B.context a) dt (shape a) one_val in
sub one_tensor a
let cmplt a b =
let a', b' = broadcasted a b in
B.op_cmplt a' b'
let less a b = cmplt a b
let cmpne a b =
let a', b' = broadcasted a b in
B.op_cmpne a' b'
let not_equal a b = cmpne a b
let cmpeq a b =
let ne_result = cmpne a b in
logical_not ne_result
let equal a b = cmpeq a b
let cmpgt a b = cmplt b a
let greater a b = cmpgt a b
let cmple a b = logical_not (cmpgt a b)
let less_equal a b = cmple a b
let cmpge a b = logical_not (cmplt a b)
let greater_equal a b = cmpge a b
let equal_s a s =
let s_tensor = scalar (B.context a) (dtype a) s in
equal a s_tensor
let not_equal_s a s =
let s_tensor = scalar (B.context a) (dtype a) s in
not_equal a s_tensor
let less_s a s =
let s_tensor = scalar (B.context a) (dtype a) s in
less a s_tensor
let greater_s a s =
let s_tensor = scalar (B.context a) (dtype a) s in
greater a s_tensor
let less_equal_s a s =
let s_tensor = scalar (B.context a) (dtype a) s in
less_equal a s_tensor
let greater_equal_s a s =
let s_tensor = scalar (B.context a) (dtype a) s in
greater_equal a s_tensor
let neg x = B.op_neg x
let bitwise_not x =
let dt = dtype x in
let minus_one_val = Dtype.minus_one dt in
let minus_one_tensor = B.op_const_scalar (B.context x) minus_one_val dt in
let minus_one_b = broadcast_to (shape x) minus_one_tensor in
B.op_xor x minus_one_b
let invert x = bitwise_not x
let log2 x = B.op_log2 x
let exp2 x = B.op_exp2 x
let sin x = B.op_sin x
let sqrt x = B.op_sqrt x
let recip x = B.op_recip x
let log x =
let log2_x = log2 x in
let ln_2_val = Stdlib.log 2.0 in
let dt = dtype x in
let ln_2_tensor = B.op_const_scalar (B.context x) ln_2_val dt in
let ln_2_b = broadcast_to (shape log2_x) ln_2_tensor in
B.op_mul log2_x ln_2_b
let exp x =
let one_over_ln_2_val = 1.0 /. Stdlib.log 2.0 in
let dt = dtype x in
let factor_tensor = B.op_const_scalar (B.context x) one_over_ln_2_val dt in
let factor_b = broadcast_to (shape x) factor_tensor in
let x_scaled = B.op_mul x factor_b in
B.op_exp2 x_scaled
let cos x =
let pi_half_val = Stdlib.acos 0.0 in
let dt = dtype x in
let pi_half_tensor = B.op_const_scalar (B.context x) pi_half_val dt in
let pi_half_b = broadcast_to (shape x) pi_half_tensor in
let arg_to_sin = sub pi_half_b x in
B.op_sin arg_to_sin
let tan x =
let sin_x = sin x in
let cos_x = cos x in
B.op_fdiv sin_x cos_x
let square x = mul x x
let abs x =
let dt = dtype x in
if Dtype.is_uint dt then x
else
let zero_val = Dtype.zero dt in
let zero_tensor = B.op_const_scalar (B.context x) zero_val dt in
let zero_b = broadcast_to (shape x) zero_tensor in
let cond = cmplt x zero_b in
let neg_x = neg x in
B.op_where cond neg_x x
let sign x =
let dt = dtype x in
let zero_val = Dtype.zero dt in
let one_val = Dtype.one dt in
if Dtype.is_uint dt then full_like x one_val
else
let zero_x = full_like x zero_val in
let one_x = full_like x one_val in
let minus_one_val = Dtype.minus_one dt in
let minus_one_x = full_like x minus_one_val in
let is_positive = cmpgt x zero_x in
let is_negative = cmplt x zero_x in
let result = B.op_where is_positive one_x zero_x in
B.op_where is_negative minus_one_x result
let relu x = maximum x (zeros_like x)
let sigmoid x =
let dt = dtype x in
let neg_one_over_log2 =
B.op_const_scalar (B.context x) (-1.0 /. Stdlib.log 2.0) dt
in
let one_x = ones_like x in
let exp_term = exp2 (mul x neg_one_over_log2) in
recip (add one_x exp_term)
let rsqrt x = recip (sqrt x)
let poly_n_horner_coeffs_first x_tensor coeffs =
match coeffs with
| [] ->
Error.invalid ~op:"poly_n_horner_coeffs_first" ~what:"coefficients"
~reason:"list is empty" ()
| p_n :: ps_from_n_minus_1_to_0 ->
let dt = dtype x_tensor in
let acc = full (B.context x_tensor) dt (shape x_tensor) p_n in
List.fold_left
(fun current_acc p_i_val ->
let p_i_tensor =
full (B.context x_tensor) dt (shape x_tensor) p_i_val
in
add (mul current_acc x_tensor) p_i_tensor)
acc ps_from_n_minus_1_to_0
let asin x =
let coeffs =
[
-0.0012624911;
0.0066700901;
-0.0170881256;
0.0308918810;
-0.0501743046;
0.0889789874;
-0.2145988016;
1.5707963050;
]
in
let dt = dtype x in
let pi_half_x = full (B.context x) dt (shape x) (Stdlib.Float.pi /. 2.0) in
let one_x = full (B.context x) dt (shape x) 1.0 in
let abs_x = abs x in
let term_sqrt = sqrt (sub one_x abs_x) in
let poly_val = poly_n_horner_coeffs_first abs_x coeffs in
let val_before_sign = sub pi_half_x (mul term_sqrt poly_val) in
mul (sign x) val_before_sign
let acos x =
let dt = dtype x in
let pi_half_x = full (B.context x) dt (shape x) (Stdlib.Float.pi /. 2.0) in
sub pi_half_x (asin x)
let atan x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let x_squared = square x in
let denominator = sqrt (add one_x x_squared) in
asin (div x denominator)
let sinh x =
let dt = dtype x in
let two_x = full (B.context x) dt (shape x) 2.0 in
let exp_x = exp x in
let exp_neg_x = exp (neg x) in
div (sub exp_x exp_neg_x) two_x
let cosh x =
let dt = dtype x in
let two_x = full (B.context x) dt (shape x) 2.0 in
let exp_x = exp x in
let exp_neg_x = exp (neg x) in
div (add exp_x exp_neg_x) two_x
let tanh x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let two_x = full (B.context x) dt (shape x) 2.0 in
let sigmoid_arg = mul two_x x in
let sigmoid_val = sigmoid sigmoid_arg in
sub (mul two_x sigmoid_val) one_x
let asinh x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let x_squared = square x in
let sqrt_term = sqrt (add x_squared one_x) in
log (add x sqrt_term)
let acosh x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let x_squared = square x in
let sqrt_term = sqrt (sub x_squared one_x) in
log (add x sqrt_term)
let atanh x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let two_x = full (B.context x) dt (shape x) 2.0 in
let term_plus = add one_x x in
let term_minus = sub one_x x in
div (log (div term_plus term_minus)) two_x
let trunc x =
let original_dt = dtype x in
cast original_dt (cast Dtype.int32 x)
let ceil x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let trunc_x = trunc x in
let cond = cmpgt x trunc_x in
B.op_where cond (add trunc_x one_x) trunc_x
let floor x =
let dt = dtype x in
let one_x = full (B.context x) dt (shape x) 1.0 in
let trunc_x = trunc x in
let cond = cmplt x trunc_x in
B.op_where cond (sub trunc_x one_x) trunc_x
let round x =
let dt = dtype x in
let half_x = full (B.context x) dt (shape x) 0.5 in
let abs_x = abs x in
let floor_term = floor (add abs_x half_x) in
mul (sign x) floor_term
let isinf x =
let dt = dtype x in
if not (Dtype.is_float dt) then zeros (B.context x) Dtype.uint8 (shape x)
else
let pos_inf_const = B.op_const_scalar (B.context x) Float.infinity dt in
let neg_inf_const =
B.op_const_scalar (B.context x) Float.neg_infinity dt
in
let is_pos_inf = cmpeq x (broadcast_to (shape x) pos_inf_const) in
let is_neg_inf = cmpeq x (broadcast_to (shape x) neg_inf_const) in
logical_or is_pos_inf is_neg_inf
let isnan x =
let dt = dtype x in
if not (Dtype.is_float dt) then zeros (B.context x) Dtype.uint8 (shape x)
else cmpne x x
let isfinite x =
let dt = dtype x in
if not (Dtype.is_float dt) then ones (B.context x) Dtype.uint8 (shape x)
else logical_not (logical_or (isinf x) (isnan x))
let lerp start_tensor end_tensor weight =
let end_minus_start = sub end_tensor start_tensor in
let weighted_diff = mul end_minus_start weight in
add start_tensor weighted_diff
let lerp_scalar_weight start_tensor end_tensor weight_val =
let dt = dtype start_tensor in
let weight_tensor =
full (B.context start_tensor) dt (shape start_tensor) weight_val
in
lerp start_tensor end_tensor weight_tensor
let lshift x shift_val =
let dt = dtype x in
if not (Dtype.is_int dt) then
Error.invalid ~op:"lshift"
~what:("dtype " ^ Dtype.to_string dt)
~reason:"expected integer type" ();
if shift_val < 0 then
Error.check_bounds ~op:"lshift" ~name:"shift_val" ~value:shift_val ~min:0
();
if shift_val = 0 then x
else
let factor_val = power_of_two dt shift_val in
let factor_tensor = B.op_const_scalar (B.context x) factor_val dt in
let factor_b = broadcast_to (shape x) factor_tensor in
B.op_mul x factor_b
let rshift x shift_val =
let dt = dtype x in
if not (Dtype.is_int dt) then
Error.invalid ~op:"rshift"
~what:("dtype " ^ Dtype.to_string dt)
~reason:"expected integer type" ();
if shift_val < 0 then
Error.check_bounds ~op:"rshift" ~name:"shift_val" ~value:shift_val ~min:0
();
if shift_val = 0 then x
else
let divisor_val = power_of_two dt shift_val in
let divisor_tensor = B.op_const_scalar (B.context x) divisor_val dt in
let divisor_b = broadcast_to (shape x) divisor_tensor in
B.op_idiv x divisor_b
let clamp ?min ?max x =
let x_clamped_min =
match min with
| None -> x
| Some min_v ->
let min_x = full_like x min_v in
maximum x min_x
in
match max with
| None -> x_clamped_min
| Some max_v ->
let max_x = full_like x_clamped_min max_v in
minimum x_clamped_min max_x
let clip = clamp
let where cond if_true if_false =
let s_true = shape if_true in
let s_false = shape if_false in
let s_cond = shape cond in
let target_data_shape = Shape.broadcast s_true s_false in
let final_target_shape = Shape.broadcast target_data_shape s_cond in
let cond_b = broadcast_to final_target_shape cond in
let if_true_b = broadcast_to final_target_shape if_true in
let if_false_b = broadcast_to final_target_shape if_false in
B.op_where cond_b if_true_b if_false_b
let atan2 y x =
let y', x' = broadcasted y x in
let dt = dtype y' in
let zero = zeros_like y' in
let pi = full (B.context y') dt (shape y') Float.pi in
let pi_half = full (B.context y') dt (shape y') (Float.pi /. 2.0) in
let neg_pi_half = full (B.context y') dt (shape y') (-.Float.pi /. 2.0) in
let x_pos = cmpgt x' zero in
let x_zero = cmpeq x' zero in
let y_pos = cmpgt y' zero in
let y_zero = cmpeq y' zero in
let y_neg = cmplt y' zero in
let ratio = div y' x' in
let base_angle = atan ratio in
let result_1 = where x_pos base_angle zero in
let x_neg_y_nonneg = logical_and (logical_not x_pos) (logical_not y_neg) in
let x_neg_y_nonneg = logical_and x_neg_y_nonneg (logical_not x_zero) in
let result_2 = where x_neg_y_nonneg (add base_angle pi) result_1 in
let x_neg_y_neg = logical_and (logical_not x_pos) y_neg in
let x_neg_y_neg = logical_and x_neg_y_neg (logical_not x_zero) in
let result_3 = where x_neg_y_neg (sub base_angle pi) result_2 in
let x_zero_y_pos = logical_and x_zero y_pos in
let result_4 = where x_zero_y_pos pi_half result_3 in
let x_zero_y_neg = logical_and x_zero y_neg in
let result_5 = where x_zero_y_neg neg_pi_half result_4 in
let both_zero = logical_and x_zero y_zero in
where both_zero zero result_5
let hypot x y =
let x', y' = broadcasted x y in
let x_abs = abs x' in
let y_abs = abs y' in
let max_val = maximum x_abs y_abs in
let min_val = minimum x_abs y_abs in
let both_zero =
logical_and
(cmpeq x_abs (zeros_like x_abs))
(cmpeq y_abs (zeros_like y_abs))
in
let ratio = where both_zero (zeros_like min_val) (div min_val max_val) in
let ratio_sq = square ratio in
let one = ones_like ratio_sq in
let sqrt_term = sqrt (add one ratio_sq) in
let result = mul max_val sqrt_term in
where both_zero (zeros_like result) result
let reduce_op backend_op ?axes ?(keepdims = false) x =
let rank = Array.length (shape x) in
let axes_to_reduce =
match axes with
| None -> Array.init rank Fun.id
| Some ax_list ->
Array.of_list
(List.map (fun ax -> if ax < 0 then ax + rank else ax) ax_list)
in
Array.iter
(fun ax ->
if ax < 0 || ax >= rank then
Error.invalid ~op:"reduce" ~what:"axis"
~reason:
(Printf.sprintf "axis %d out of bounds for tensor of rank %d" ax
rank)
())
axes_to_reduce;
backend_op ~axes:axes_to_reduce ~keepdims x
let sum ?axes ?(keepdims = false) x =
reduce_op B.op_reduce_sum ?axes ~keepdims x
let max ?axes ?(keepdims = false) x =
reduce_op B.op_reduce_max ?axes ~keepdims x
let min ?axes ?(keepdims = false) x =
neg (reduce_op B.op_reduce_max ?axes ~keepdims (neg x))
let prod ?axes ?(keepdims = false) x =
reduce_op B.op_reduce_prod ?axes ~keepdims x
let associative_scan ~axis op x =
let x_shape = shape x in
let rank = Array.length x_shape in
if rank = 0 then
let normalized_axis = if axis < 0 then axis + 1 else axis in
if normalized_axis = 0 then x
else
Error.invalid ~op:"associative_scan" ~what:"axis"
~reason:
(Printf.sprintf
"axis %d out of bounds for rank 0 tensor (only axis 0 valid)"
axis)
()
else
let normalized_axis = if axis < 0 then axis + rank else axis in
if normalized_axis < 0 || normalized_axis >= rank then
Error.invalid ~op:"associative_scan" ~what:"axis"
~reason:(Printf.sprintf "axis %d out of bounds for rank %d" axis rank)
()
else B.op_associative_scan ~axis:normalized_axis ~op x
let cumulative_scan ?axis op x =
let orig_shape = shape x in
match axis with
| Some axis -> associative_scan ~axis op x
| None ->
let numel = array_prod orig_shape in
let flattened = reshape [| numel |] x in
let scanned = associative_scan ~axis:0 op flattened in
if Array.length orig_shape = 0 then
reshape [||] scanned
else reshape orig_shape scanned
let cumsum ?axis x = cumulative_scan ?axis `Sum x
let cumprod ?axis x = cumulative_scan ?axis `Prod x
let cummax ?axis x = cumulative_scan ?axis `Max x
let cummin ?axis x = cumulative_scan ?axis `Min x
let mean ?axes ?(keepdims = false) x =
let x_dtype = B.dtype x in
let num_for_sum = sum ?axes ~keepdims x in
let s_orig = shape x in
let r_orig = Array.length s_orig in
let actual_axes_to_reduce =
match axes with
| None -> Array.init r_orig Fun.id
| Some ax_list ->
Array.of_list
(List.map (fun ax -> if ax < 0 then ax + r_orig else ax) ax_list)
in
let num_elements_in_reduced_dims =
if Array.length actual_axes_to_reduce = 0 then 1
else
array_prod
(Array.map (fun ax_idx -> s_orig.(ax_idx)) actual_axes_to_reduce)
in
let num_elements_divisor_float =
float_of_int
(if num_elements_in_reduced_dims = 0 then 1
else num_elements_in_reduced_dims)
in
let divisor_val_ocaml = Dtype.of_float x_dtype num_elements_divisor_float in
let divisor_scalar = scalar (B.context x) x_dtype divisor_val_ocaml in
let divisor_tensor = broadcast_to (shape num_for_sum) divisor_scalar in
B.op_fdiv num_for_sum divisor_tensor
let var ?axes ?(keepdims = false) ?(ddof = 0) x =
let x_dtype = B.dtype x in
let mean_x_keepdim_true = mean ?axes ~keepdims:true x in
let diff = sub x mean_x_keepdim_true in
let diff_sq = square diff in
let sum_diff_sq = sum ?axes ~keepdims diff_sq in
let s_orig = shape x in
let r_orig = Array.length s_orig in
let actual_axes_to_reduce =
match axes with
| None -> Array.init r_orig Fun.id
| Some ax_list ->
Array.of_list
(List.map (fun ax -> if ax < 0 then ax + r_orig else ax) ax_list)
in
let num_elements_in_reduced_dims =
if Array.length actual_axes_to_reduce = 0 then 1
else
array_prod
(Array.map (fun ax_idx -> s_orig.(ax_idx)) actual_axes_to_reduce)
in
let n_corrected_val = num_elements_in_reduced_dims - ddof in
let n_corrected_float = float_of_int (Stdlib.max 0 n_corrected_val) in
let divisor_val_ocaml = Dtype.of_float x_dtype n_corrected_float in
let divisor_scalar = scalar (B.context x) x_dtype divisor_val_ocaml in
let divisor_tensor = broadcast_to (shape sum_diff_sq) divisor_scalar in
B.op_fdiv sum_diff_sq divisor_tensor
let std ?axes ?(keepdims = false) ?(ddof = 0) x =
let variance = var ?axes ~keepdims ~ddof x in
sqrt variance
let all ?axes ?(keepdims = false) x =
let zero_val = Dtype.zero (dtype x) in
let zero_tensor = full_like x zero_val in
let bool_tensor = cmpne x zero_tensor in
let prod_val = prod ?axes ~keepdims bool_tensor in
prod_val
let any ?axes ?(keepdims = false) x =
let zero_val = Dtype.zero (dtype x) in
let zero_tensor = full_like x zero_val in
let bool_tensor = cmpne x zero_tensor in
let max_val = max ?axes ~keepdims bool_tensor in
max_val
let array_equal x y =
let can_broadcast =
try
let _ = Shape.broadcast (shape x) (shape y) in
true
with _ -> false
in
if not can_broadcast then
zeros (B.context x) Dtype.uint8 [||]
else
let eq_result = equal x y in
all eq_result
let pad padding_config fill_value x =
Array.iter
(fun (before, after) ->
if before < 0 || after < 0 then
Error.invalid ~op:"pad" ~what:"padding values"
~reason:"negative values not allowed"
~hint:"use shrink or slice to remove elements" ())
padding_config;
B.op_pad x padding_config fill_value
let shrink shrink_args x = B.op_shrink x shrink_args
let flatten ?(start_dim = 0) ?(end_dim = -1) x =
let sh = shape x in
let r = Array.length sh in
let s_orig = start_dim in
let e_orig = end_dim in
let s = if s_orig < 0 then s_orig + r else s_orig in
let e = if e_orig < 0 then e_orig + r else e_orig in
if
not
((s >= 0 && s < r && e >= 0 && e < r)
|| (r = 0 && (s = 0 || s_orig = 0) && (e = -1 || e_orig = -1)))
then
Error.invalid ~op:"flatten"
~what:(Printf.sprintf "start_dim %d or end_dim %d" start_dim end_dim)
~reason:(Printf.sprintf "out of bounds for rank %d" r)
();
if s > e then
Error.invalid ~op:"flatten" ~what:"dimensions"
~reason:"start_dim must be <= end_dim" ();
let new_shape_list =
if r = 0 then [ 1 ]
else if s = 0 && e = r - 1 then [ array_prod sh ]
else
let pre = Array.to_list (Array.sub sh 0 s) in
let mid_slice = Array.sub sh s (e - s + 1) in
let mid_prod =
if Array.length mid_slice = 0 then 1 else array_prod mid_slice
in
let post = Array.to_list (Array.sub sh (e + 1) (r - (e + 1))) in
pre @ [ mid_prod ] @ post
in
reshape (Array.of_list new_shape_list) x
let unflatten dim sizes x =
let dim = resolve_single_axis x dim in
let current_shape = shape x in
let dim_size = current_shape.(dim) in
let sizes = Array.copy sizes in
let neg_one_count =
Array.fold_left (fun acc s -> if s = -1 then acc + 1 else acc) 0 sizes
in
if neg_one_count > 1 then
Error.invalid ~op:"unflatten" ~what:"sizes"
~reason:"can only specify one unknown dimension (using -1)" ();
if neg_one_count = 1 then (
let known_product =
Array.fold_left (fun acc s -> if s = -1 then acc else acc * s) 1 sizes
in
if known_product = 0 || dim_size mod known_product <> 0 then
Error.cannot ~op:"unflatten" ~what:"infer dimension"
~from:(Printf.sprintf "total size %d" dim_size)
~to_:(Printf.sprintf "known product %d" known_product)
~reason:
(Printf.sprintf "%d not divisible by %d" dim_size known_product)
~hint:"ensure total size is divisible by product of known dimensions"
();
let inferred_size = dim_size / known_product in
Array.iteri (fun i s -> if s = -1 then sizes.(i) <- inferred_size) sizes);
let sizes_product = Array.fold_left ( * ) 1 sizes in
if sizes_product <> dim_size then
Error.invalid ~op:"unflatten" ~what:"sizes"
~reason:
(Printf.sprintf "product %d does not match dimension size %d"
sizes_product dim_size)
();
let new_shape =
Array.concat
[
Array.sub current_shape 0 dim;
sizes;
Array.sub current_shape (dim + 1)
(Array.length current_shape - dim - 1);
]
in
reshape new_shape x
let ravel x = flatten x
module IntSet = Set.Make (Int)
let squeeze ?axes x =
let sh = shape x in
let r = Array.length sh in
match axes with
| None ->
let new_shape_list = List.filter (( <> ) 1) (Array.to_list sh) in
let new_shape = Array.of_list new_shape_list in
if Array.length new_shape = 0 && Array.length sh > 0 then
reshape [||] x
else if Array.length new_shape = 0 && Array.length sh = 0 then x
else reshape new_shape x
| Some axes_list ->
if r = 0 then x
else
let normalized_axes =
List.map (fun ax -> if ax < 0 then ax + r else ax) axes_list
in
let seen = Array.make r false in
List.iter
(fun ax ->
if ax < 0 || ax >= r then
Error.axis_out_of_bounds ~op:"squeeze" ~axis:ax ~ndim:r ();
if seen.(ax) then
Error.invalid ~op:"squeeze"
~what:(Printf.sprintf "axis %d" ax)
~reason:"duplicate axis" ();
seen.(ax) <- true)
normalized_axes;
List.iter
(fun ax ->
if sh.(ax) <> 1 then
Error.cannot ~op:"squeeze" ~what:"remove dimension"
~from:(Printf.sprintf "axis %d (size %d)" ax sh.(ax))
~to_:"squeezed"
~reason:(Printf.sprintf "size %d≠1" sh.(ax))
())
normalized_axes;
let axes_set =
List.fold_left
(fun set ax -> IntSet.add ax set)
IntSet.empty normalized_axes
in
let new_shape_list =
List.filteri
(fun i _ -> not (IntSet.mem i axes_set))
(Array.to_list sh)
in
let new_shape = Array.of_list new_shape_list in
if Array.length new_shape = 0 && Array.length sh > 0 then
reshape [||] x
else if Array.length new_shape = 0 && Array.length sh = 0 then x
else reshape new_shape x
let unsqueeze ?axes x =
let sh = shape x in
let r = Array.length sh in
let axes_list =
match axes with
| None ->
Error.invalid ~op:"unsqueeze" ~what:"axes" ~reason:"must be specified"
()
| Some lst -> lst
in
if List.length axes_list = 0 then x
else
let output_rank = r + List.length axes_list in
let normalized_axes =
List.map (fun ax -> if ax < 0 then ax + output_rank else ax) axes_list
in
let seen = Array.make output_rank false in
List.iter
(fun ax ->
if ax < 0 || ax >= output_rank then
Error.invalid ~op:"unsqueeze"
~what:(Printf.sprintf "axis %d" ax)
~reason:
(Printf.sprintf "out of bounds for output rank %d" output_rank)
~hint:
(Printf.sprintf "valid range is [%d, %d)" (-output_rank)
output_rank)
();
if seen.(ax) then
Error.invalid ~op:"unsqueeze"
~what:(Printf.sprintf "axis %d" ax)
~reason:"duplicate axis" ();
seen.(ax) <- true)
normalized_axes;
let axes_set =
List.fold_left
(fun set ax -> IntSet.add ax set)
IntSet.empty normalized_axes
in
let new_shape_list = ref [] in
let input_idx = ref 0 in
for output_idx = 0 to output_rank - 1 do
if IntSet.mem output_idx axes_set then
new_shape_list :=
1 :: !new_shape_list
else if !input_idx < r then (
new_shape_list := sh.(!input_idx) :: !new_shape_list;
incr input_idx)
done;
let new_shape = Array.of_list (List.rev !new_shape_list) in
reshape new_shape x
let squeeze_axis axis x = squeeze ~axes:[ axis ] x
let unsqueeze_axis axis x = unsqueeze ~axes:[ axis ] x
let expand_dims axes x = unsqueeze ~axes x
let transpose ?axes x =
let r = ndim x in
let resolved_axes =
match axes with
| None -> Array.init r (fun i -> r - 1 - i)
| Some ax_list ->
if List.length ax_list <> r then
Error.invalid ~op:"transpose"
~what:(Printf.sprintf "axes (length %d)" (List.length ax_list))
~reason:
(Printf.sprintf "expected rank %d, got %d" r
(List.length ax_list))
~hint:"provide exactly one axis per dimension" ();
let seen = Array.make r false in
List.iter
(fun ax_val ->
let ax = if ax_val < 0 then ax_val + r else ax_val in
if ax < 0 || ax >= r then
Error.axis_out_of_bounds ~op:"transpose" ~axis:ax_val ~ndim:r ();
if seen.(ax) then
Error.invalid ~op:"transpose"
~what:(Printf.sprintf "axis %d" ax_val)
~reason:"repeated" ();
seen.(ax) <- true)
ax_list;
if not (Array.for_all Fun.id seen) then
Error.invalid ~op:"transpose" ~what:"axes"
~reason:"do not form a permutation" ();
Array.of_list
(List.map
(fun ax_val -> if ax_val < 0 then ax_val + r else ax_val)
ax_list)
in
let result = B.op_permute x resolved_axes in
result
let flip ?axes x =
let r = ndim x in
let flip_bools = Array.make r false in
(match axes with
| None -> Array.fill flip_bools 0 r true
| Some ax_list ->
List.iter
(fun ax_val ->
let ax = if ax_val < 0 then ax_val + r else ax_val in
if ax < 0 || ax >= r then
Error.axis_out_of_bounds ~op:"flip" ~axis:ax_val ~ndim:r ();
flip_bools.(ax) <- true)
ax_list);
B.op_flip x flip_bools
let as_strided shape strides ~offset x =
let shape_sym = Symbolic_shape.of_ints shape in
B.op_as_strided x shape_sym strides offset
let moveaxis src dst x =
let r = ndim x in
let norm_src = if src < 0 then src + r else src in
let norm_dst = if dst < 0 then dst + r else dst in
if norm_src < 0 || norm_src >= r || norm_dst < 0 || norm_dst >= r then
Error.invalid ~op:"moveaxis"
~what:(Printf.sprintf "source %d or destination %d" src dst)
~reason:
(Format.asprintf "out of bounds for shape %a" Shape.pp (shape x))
();
if norm_src = norm_dst then x
else
let axes_list = Array.to_list (Array.init r Fun.id) in
let item_to_move = List.nth axes_list norm_src in
let list_without_item = List.filter (( <> ) item_to_move) axes_list in
let rec insert_at idx item lst acc =
match lst with
| [] -> List.rev (item :: acc)
| hd :: tl ->
if idx = 0 then List.rev_append acc (item :: hd :: tl)
else insert_at (idx - 1) item tl (hd :: acc)
in
let final_axes_list =
insert_at norm_dst item_to_move list_without_item []
in
B.op_permute x (Array.of_list final_axes_list)
let swapaxes axis1 axis2 x =
let r = ndim x in
let norm_axis1 = if axis1 < 0 then axis1 + r else axis1 in
let norm_axis2 = if axis2 < 0 then axis2 + r else axis2 in
if norm_axis1 < 0 || norm_axis1 >= r || norm_axis2 < 0 || norm_axis2 >= r
then
Error.invalid ~op:"swapaxes"
~what:(Printf.sprintf "axes (%d, %d)" axis1 axis2)
~reason:
(Format.asprintf "out of bounds for shape %a" Shape.pp (shape x))
();
if norm_axis1 = norm_axis2 then x
else
let axes = Array.init r Fun.id in
let temp = axes.(norm_axis1) in
axes.(norm_axis1) <- axes.(norm_axis2);
axes.(norm_axis2) <- temp;
B.op_permute x axes
let roll ?axis shift x =
let original_shape = shape x in
let x, ax_idx =
match axis with
| None ->
let flat_x = flatten x in
(flat_x, 0)
| Some specified_axis ->
let r = ndim x in
let norm_axis =
if specified_axis < 0 then specified_axis + r else specified_axis
in
if norm_axis < 0 || norm_axis >= r then
Error.axis_out_of_bounds ~op:"roll" ~axis:specified_axis ~ndim:r ();
(x, norm_axis)
in
let current_shape = shape x in
let r = ndim x in
if r = 0 then x
else
let dim_size = current_shape.(ax_idx) in
if dim_size = 0 then x
else
let s = shift mod dim_size in
let actual_shift = if s < 0 then s + dim_size else s in
if actual_shift = 0 then
if axis = None then reshape (shape x) x
else x
else
let ranges_part1 =
Array.mapi
(fun i cur_dim ->
if i = ax_idx then (dim_size - actual_shift, cur_dim)
else (0, cur_dim))
current_shape
in
let ranges_part2 =
Array.mapi
(fun i cur_dim ->
if i = ax_idx then (0, dim_size - actual_shift) else (0, cur_dim))
current_shape
in
let part1 = shrink ranges_part1 x in
let part2 = shrink ranges_part2 x in
let rolled_x = B.op_cat [ part1; part2 ] ax_idx in
if axis = None then reshape original_shape rolled_x else rolled_x
let tile reps x =
let t_shape = shape x in
let t_ndim = ndim x in
let reps_len = Array.length reps in
if reps_len < t_ndim then
Error.invalid ~op:"tile" ~what:"reps length"
~reason:"must be >= tensor rank" ();
let x_promoted, promoted_shape =
if reps_len > t_ndim then (
let new_shape = Array.make reps_len 1 in
Array.blit t_shape 0 new_shape (reps_len - t_ndim) t_ndim;
(reshape new_shape x, new_shape))
else (x, t_shape)
in
Array.iteri
(fun i r ->
if r < 0 then
Error.invalid ~op:"tile"
~what:(Printf.sprintf "reps[%d]" i)
~reason:(Printf.sprintf "negative (%d<0)" r)
~hint:"use positive integers (or 0 for empty result)" ())
reps;
if Array.for_all (( = ) 1) reps then
B.op_copy x_promoted
else if Array.exists (( = ) 0) reps || Array.exists (( = ) 0) promoted_shape
then
let tiled_shape =
Array.mapi (fun i s_i -> s_i * reps.(i)) promoted_shape
in
empty (B.context x) (dtype x) tiled_shape
else
let rec tile_axis curr_x axis =
if axis >= reps_len then curr_x
else if reps.(axis) = 1 then tile_axis curr_x (axis + 1)
else
let copies = List.init reps.(axis) (fun _ -> curr_x) in
let concatenated = B.op_cat copies axis in
tile_axis concatenated (axis + 1)
in
tile_axis x_promoted 0
let repeat ?axis count x =
if count < 0 then
Error.check_bounds ~op:"repeat" ~name:"count" ~value:count ~min:0 ();
let x, ax_idx_eff =
match axis with
| None ->
let flat_x = flatten x in
(flat_x, 0)
| Some specified_axis ->
let r = ndim x in
let norm_axis =
if specified_axis < 0 then specified_axis + r else specified_axis
in
if norm_axis < 0 || norm_axis >= r then
Error.axis_out_of_bounds ~op:"repeat" ~axis:specified_axis ~ndim:r
();
(x, norm_axis)
in
let t_shape = shape x in
let t_ndim = ndim x in
if count = 0 then (
let new_s = Array.copy t_shape in
if t_ndim > 0 then new_s.(ax_idx_eff) <- 0;
let final_shape_if_flattened = if axis = None then [| 0 |] else new_s in
empty (B.context x) (dtype x) final_shape_if_flattened)
else if count = 1 then B.op_copy x
else if t_ndim = 0 then
let scalar_reshaped = reshape [| 1 |] x in
let repeated = expand [| count |] scalar_reshaped in
if axis = None then repeated else reshape (shape x) repeated
else
let axis_size = t_shape.(ax_idx_eff) in
let slices = ref [] in
for i = axis_size - 1 downto 0 do
let slice =
Array.init t_ndim (fun dim ->
if dim = ax_idx_eff then (i, i + 1) else (0, t_shape.(dim)))
in
let slice_view = B.op_shrink x slice in
for _ = 1 to count do
slices := slice_view :: !slices
done
done;
let result = B.op_cat !slices ax_idx_eff in
if axis = None then result else result
let concatenate ?axis ts =
match ts with
| [] ->
Error.invalid ~op:"concatenate" ~what:"tensor list" ~reason:"empty"
~hint:"provide at least one tensor" ()
| [ x ] -> copy x
| _ ->
let axis =
match axis with
| None ->
let first_dtype = dtype (List.hd ts) in
List.iter
(fun x ->
let x_dtype = dtype x in
if not (Dtype.equal first_dtype x_dtype) then
Error.dtype_mismatch ~op:"concatenate"
~expected:(Dtype.to_string first_dtype)
~actual:(Dtype.to_string x_dtype) ())
(List.tl ts);
let flattened = List.map flatten ts in
B.op_cat flattened 0
| Some a ->
let first = List.hd ts in
let first_ndim = ndim first in
let axis = resolve_single_axis ~ndim_opt:first_ndim first a in
let first_dtype = dtype first in
List.iter
(fun x ->
let x_dtype = dtype x in
if not (Dtype.equal first_dtype x_dtype) then
Error.dtype_mismatch ~op:"concatenate"
~expected:(Dtype.to_string first_dtype)
~actual:(Dtype.to_string x_dtype) ())
(List.tl ts);
if not (List.for_all (fun x -> ndim x = first_ndim) ts) then
Error.invalid ~op:"concatenate" ~what:"arrays"
~reason:"must have same number of dimensions" ();
let first_shape = shape (List.hd ts) in
List.iter
(fun x ->
let t_shape = shape x in
Array.iteri
(fun i s ->
if i <> axis && s <> first_shape.(i) then
Error.invalid ~op:"concatenate"
~what:(Printf.sprintf "dimension %d" i)
~reason:
(Printf.sprintf "size %d≠%d" s first_shape.(i))
())
t_shape)
(List.tl ts);
B.op_cat ts axis
in
axis
let stack ?axis ts =
match ts with
| [] -> Error.empty_input ~op:"stack" ~what:"tensor list"
| _ ->
let first_shape = shape (List.hd ts) in
let first_ndim = Array.length first_shape in
let axis =
match axis with
| None -> 0
| Some a ->
let a = if a < 0 then a + first_ndim + 1 else a in
if a < 0 || a > first_ndim then
Error.axis_out_of_bounds ~op:"stack" ~axis:a ~ndim:first_ndim ();
a
in
let expanded = List.map (fun x -> unsqueeze ~axes:[ axis ] x) ts in
concatenate ~axis expanded
let ensure_ndim n x =
let s = shape x in
let nd = Array.length s in
if nd >= n then x
else
let new_shape = Array.make n 1 in
Array.blit s 0 new_shape 0 nd;
reshape new_shape x
let vstack ts =
match ts with
| [] -> Error.empty_input ~op:"vstack" ~what:"tensor list"
| _ ->
let arrays_2d =
List.map
(fun x ->
let nd = ndim x in
if nd = 0 then reshape [| 1; 1 |] x
else if nd = 1 then reshape [| 1; numel x |] x
else x)
ts
in
concatenate ~axis:0 arrays_2d
let hstack ts =
match ts with
| [] -> Error.empty_input ~op:"hstack" ~what:"tensor list"
| _ ->
let all_1d = List.for_all (fun x -> ndim x <= 1) ts in
if all_1d then
let arrays_1d =
List.map (fun x -> if ndim x = 0 then reshape [| 1 |] x else x) ts
in
concatenate ~axis:0 arrays_1d
else
let arrays_2d =
List.map
(fun x ->
let nd = ndim x in
if nd = 0 then reshape [| 1; 1 |] x
else if nd = 1 then reshape [| numel x; 1 |] x
else x)
ts
in
concatenate ~axis:1 arrays_2d
let dstack ts =
match ts with
| [] -> Error.empty_input ~op:"dstack" ~what:"tensor list"
| _ ->
let arrays_3d =
List.map
(fun x ->
let s = shape x in
let nd = Array.length s in
if nd = 0 then reshape [| 1; 1; 1 |] x
else if nd = 1 then reshape [| 1; s.(0); 1 |] x
else if nd = 2 then reshape [| s.(0); s.(1); 1 |] x
else x)
ts
in
concatenate ~axis:2 arrays_3d
let broadcast_arrays ts =
match ts with
| [] -> []
| [ x ] -> [ x ]
| _ ->
let broadcast_shape =
List.fold_left
(fun acc_shape x -> Shape.broadcast acc_shape (shape x))
(shape (List.hd ts))
(List.tl ts)
in
List.map (fun x -> broadcast_to broadcast_shape x) ts
let eye ctx ?m ?k dtype n =
let rows = match m with Some v -> v | None -> n in
let cols = n in
let k_val = match k with Some v -> v | None -> 0 in
let final_shape = [| rows; cols |] in
if rows <= 0 || cols <= 0 || k_val >= cols || k_val <= -rows then
zeros ctx dtype final_shape
else
let arr = Array.make (rows * cols) (Dtype.zero dtype) in
let one = Dtype.one dtype in
for i = 0 to (if rows < cols then rows else cols) - 1 do
let row = i in
let col = i + k_val in
if col >= 0 && col < cols then arr.((row * cols) + col) <- one
done;
create ctx dtype final_shape arr
let identity ctx dtype n = eye ctx ~m:n ~k:0 dtype n
let diag ?(k = 0) v =
let v_shape = shape v in
let v_ndim = Array.length v_shape in
if v_ndim = 1 then
let n = v_shape.(0) in
let size = n + Int.abs k in
let v_arr = to_array v in
init (B.context v) (dtype v) [| size; size |] (fun indices ->
let row = indices.(0) in
let col = indices.(1) in
let diag_idx =
if k >= 0 then
if col = row + k && row >= 0 && row < n then row else -1
else if
row = col - k && col >= 0 && col < n
then col
else -1
in
if diag_idx >= 0 && diag_idx < n then v_arr.(diag_idx)
else Dtype.zero (dtype v))
else if v_ndim >= 2 then
let rows = v_shape.(0) in
let cols = v_shape.(1) in
let diag_len =
if k >= 0 then Int.min rows (cols - k) else Int.min (rows + k) cols
in
let diag_len = Int.max 0 diag_len in
if diag_len = 0 then empty (B.context v) (dtype v) [| 0 |]
else
let v_arr = to_array v in
init (B.context v) (dtype v) [| diag_len |] (fun indices ->
let i = indices.(0) in
let row = if k >= 0 then i else i - k in
let col = if k >= 0 then i + k else i in
let linear_idx = (row * cols) + col in
v_arr.(linear_idx))
else
Error.invalid ~op:"diag" ~what:"input"
~reason:(Printf.sprintf "expected 1D or 2D array, got %dD" v_ndim)
()
let arange (type a b) ctx (dtype : (a, b) Dtype.t) start stop step =
if start >= stop && step > 0 then
Error.invalid ~op:"arange"
~what:(Printf.sprintf "range [%d, %d)" start stop)
~reason:(Printf.sprintf "empty with step=%d" step)
~hint:
"ensure start < stop for positive step, or start > stop for negative \
step"
();
if step = 0 then
Error.invalid ~op:"arange" ~what:"step" ~reason:"cannot be zero" ();
let num_elements =
if step > 0 then
if start >= stop then 0
else
(stop - start + step - 1)
/ step
else if
start <= stop
then 0
else (start - stop + -step - 1) / -step
in
if num_elements <= 0 then empty ctx dtype [| 0 |]
else
let f_init idx_arr : a =
let i = idx_arr.(0) in
match dtype with
| Dtype.Float16 ->
float_of_int start +. (float_of_int i *. float_of_int step)
| Dtype.Float32 ->
float_of_int start +. (float_of_int i *. float_of_int step)
| Dtype.Float64 ->
float_of_int start +. (float_of_int i *. float_of_int step)
| Dtype.BFloat16 ->
float_of_int start +. (float_of_int i *. float_of_int step)
| Dtype.Float8_e4m3 ->
float_of_int start +. (float_of_int i *. float_of_int step)
| Dtype.Float8_e5m2 ->
float_of_int start +. (float_of_int i *. float_of_int step)
| Dtype.Int8 -> start + (i * step)
| Dtype.UInt8 -> start + (i * step)
| Dtype.Int16 -> start + (i * step)
| Dtype.UInt16 -> start + (i * step)
| Dtype.Int -> start + (i * step)
| Dtype.Int4 -> start + (i * step)
| Dtype.UInt4 -> start + (i * step)
| Dtype.QInt8 -> start + (i * step)
| Dtype.QUInt8 -> start + (i * step)
| Dtype.Bool -> if i = 0 then false else true
| Dtype.Int32 ->
Int32.(add (of_int start) (mul (of_int i) (of_int step)))
| Dtype.Int64 ->
Int64.(add (of_int start) (mul (of_int i) (of_int step)))
| Dtype.NativeInt ->
Nativeint.(add (of_int start) (mul (of_int i) (of_int step)))
| Dtype.Complex32 ->
{
Complex.re =
float_of_int start +. (float_of_int i *. float_of_int step);
im = 0.;
}
| Dtype.Complex64 ->
{
Complex.re =
float_of_int start +. (float_of_int i *. float_of_int step);
im = 0.;
}
| Dtype.Complex16 ->
{
Complex.re =
float_of_int start +. (float_of_int i *. float_of_int step);
im = 0.;
}
in
init ctx dtype [| num_elements |] f_init
let arange_f ctx dtype start_f stop_f step_f =
if step_f = 0. then
Error.invalid ~op:"arange_f" ~what:"step" ~reason:"cannot be zero" ();
let num_exact_steps = (stop_f -. start_f) /. step_f in
let eps_factor = 1e-9 in
let num_elements =
if
(step_f > 0. && stop_f <= start_f +. (eps_factor *. Float.abs step_f))
|| (step_f < 0. && stop_f >= start_f +. (eps_factor *. Float.abs step_f))
|| (Float.abs num_exact_steps < eps_factor && num_exact_steps <= 0.)
then 0
else
let corrected_num_steps =
num_exact_steps -. Float.copy_sign eps_factor num_exact_steps
in
int_of_float (Float.floor corrected_num_steps +. 1.)
in
let num_elements = Stdlib.max 0 num_elements in
if num_elements <= 0 then empty ctx dtype [| 0 |]
else
let f_init idx_arr =
start_f +. (float_of_int idx_arr.(0) *. step_f)
in
init ctx dtype [| num_elements |] f_init
let linspace ctx dtype ?(endpoint = true) start_f stop_f count =
if count < 0 then
Error.invalid ~op:"linspace"
~what:(Printf.sprintf "count %d" count)
~reason:"negative count" ~hint:"use count >= 0" ();
if count = 0 then empty ctx dtype [| 0 |]
else if count = 1 then full ctx dtype [| 1 |] (Dtype.of_float dtype start_f)
else
let div_factor = float_of_int (if endpoint then count - 1 else count) in
let step_f = (stop_f -. start_f) /. div_factor in
let f_init idx_arr =
let i_f = float_of_int idx_arr.(0) in
Dtype.of_float dtype (start_f +. (i_f *. step_f))
in
init ctx dtype [| count |] f_init
let logspace ctx dtype ?(endpoint = true) ?(base = 10.0) start_exp_f
stop_exp_f count =
if count < 0 then
Error.check_bounds ~op:"logspace" ~name:"count" ~value:count ~min:0 ();
if count = 0 then empty ctx dtype [| 0 |]
else
let exponents_tensor =
linspace ctx dtype ~endpoint start_exp_f stop_exp_f count
in
if base = Float.exp 1.0 then
exp exponents_tensor
else if base = 2.0 then exp2 exponents_tensor
else
let log2_base = Stdlib.log base /. Stdlib.log 2.0 in
let log2_base_tensor = scalar ctx dtype log2_base in
let broadcasted_log2_base =
broadcast_to (shape exponents_tensor) log2_base_tensor
in
let scaled_exponents = mul exponents_tensor broadcasted_log2_base in
exp2 scaled_exponents
let geomspace ctx dtype ?(endpoint = true) start_val_f stop_val_f count =
if start_val_f <= 0. || stop_val_f <= 0. then
Error.invalid ~op:"geomspace"
~what:
(if start_val_f <= 0. then Printf.sprintf "start %g" start_val_f
else Printf.sprintf "stop %g" stop_val_f)
~reason:"must be positive (>0)"
~hint:"geomspace requires positive values for logarithmic spacing" ();
if count < 0 then
Error.check_bounds ~op:"geomspace" ~name:"count" ~value:count ~min:0 ();
if count = 0 then empty ctx dtype [| 0 |]
else if count = 1 then
full ctx dtype [| 1 |] start_val_f
else
let log_start_f = Stdlib.log start_val_f in
let log_stop_f = Stdlib.log stop_val_f in
let log_points_tensor =
linspace ctx dtype ~endpoint log_start_f log_stop_f count
in
exp log_points_tensor
let meshgrid ?(indexing = `xy) x y =
let x_shape = shape x in
let y_shape = shape y in
if Array.length x_shape <> 1 then invalid_arg "meshgrid: x must be 1D";
if Array.length y_shape <> 1 then invalid_arg "meshgrid: y must be 1D";
let nx = x_shape.(0) in
let ny = y_shape.(0) in
match indexing with
| `xy ->
let x_grid = reshape [| 1; nx |] x in
let x_grid = broadcast_to [| ny; nx |] x_grid in
let y_grid = reshape [| ny; 1 |] y in
let y_grid = broadcast_to [| ny; nx |] y_grid in
(x_grid, y_grid)
| `ij ->
let x_grid = reshape [| nx; 1 |] x in
let x_grid = broadcast_to [| nx; ny |] x_grid in
let y_grid = reshape [| 1; ny |] y in
let y_grid = broadcast_to [| nx; ny |] y_grid in
(x_grid, y_grid)
let tril ?k x =
let k_val = match k with Some v -> v | None -> 0 in
let shape = shape x in
let ndim = Array.length shape in
if ndim < 2 then
Error.invalid ~op:"tril" ~what:"input"
~reason:"requires at least 2D tensor" ()
else
let rows = shape.(ndim - 2) in
let cols = shape.(ndim - 1) in
let row_idx = arange (B.context x) int32 0 rows 1 in
let col_idx = arange (B.context x) int32 0 cols 1 in
let row_idx = reshape [| rows; 1 |] row_idx in
let col_idx = reshape [| 1; cols |] col_idx in
let mask =
greater_equal row_idx
(sub col_idx (scalar (B.context x) int32 (Int32.of_int k_val)))
in
let mask =
if ndim > 2 then
let batch_shape = Array.sub shape 0 (ndim - 2) in
let full_shape = Array.concat [ batch_shape; [| rows; cols |] ] in
broadcast_to full_shape mask
else mask
in
where mask x (zeros_like x)
let triu ?k x =
let k_val = match k with Some v -> v | None -> 0 in
let shape = shape x in
let ndim = Array.length shape in
if ndim < 2 then
Error.invalid ~op:"triu" ~what:"input"
~reason:"requires at least 2D tensor" ()
else
let rows = shape.(ndim - 2) in
let cols = shape.(ndim - 1) in
let row_idx = arange (B.context x) int32 0 rows 1 in
let col_idx = arange (B.context x) int32 0 cols 1 in
let row_idx = reshape [| rows; 1 |] row_idx in
let col_idx = reshape [| 1; cols |] col_idx in
let mask =
less_equal row_idx
(sub col_idx (scalar (B.context x) int32 (Int32.of_int k_val)))
in
let mask =
if ndim > 2 then
let batch_shape = Array.sub shape 0 (ndim - 2) in
let full_shape = Array.concat [ batch_shape; [| rows; cols |] ] in
broadcast_to full_shape mask
else mask
in
where mask x (zeros_like x)
let normalize_index dim_size idx = if idx < 0 then dim_size + idx else idx
let indices_of_spec dim_size = function
| I idx ->
let idx' = normalize_index dim_size idx in
if idx' < 0 || idx' >= dim_size then
Error.invalid ~op:"slice"
~what:(Printf.sprintf "index %d" idx)
~reason:
(Printf.sprintf "out of bounds [%d, %d)"
(if idx < 0 then -dim_size else 0)
dim_size)
()
else [ idx' ]
| L indices ->
List.map
(fun idx ->
let idx' = normalize_index dim_size idx in
if idx' < 0 || idx' >= dim_size then
Error.invalid ~op:"slice"
~what:(Printf.sprintf "index %d" idx)
~reason:
(Printf.sprintf "out of bounds [%d, %d)"
(if idx < 0 then -dim_size else 0)
dim_size)
()
else idx')
indices
| A ->
List.init dim_size (fun i -> i)
| R (start_idx, stop_idx) ->
let start = if start_idx < 0 then dim_size + start_idx else start_idx in
let stop = if stop_idx < 0 then dim_size + stop_idx else stop_idx in
let stop = stop - 1 in
let step = 1 in
let rec collect acc i =
if step > 0 then
if i > stop then List.rev acc
else if i >= dim_size then List.rev acc
else collect (i :: acc) (i + step)
else if i < stop then List.rev acc
else if i < 0 then List.rev acc
else collect (i :: acc) (i + step)
in
collect [] start
| Rs (start_idx, stop_idx, step_val) ->
if step_val = 0 then
Error.invalid ~op:"slice" ~what:"step" ~reason:"cannot be zero"
~hint:
"use positive step for forward slicing or negative for reverse"
();
let start = if start_idx < 0 then dim_size + start_idx else start_idx in
let stop = if stop_idx < 0 then dim_size + stop_idx else stop_idx in
let stop =
if step_val > 0 then
stop - 1
else stop + 1
in
let step = step_val in
let rec collect acc i =
if step > 0 then
if i > stop then List.rev acc
else if i >= dim_size then List.rev acc
else if i < 0 then collect acc (i + step)
else collect (i :: acc) (i + step)
else if
i < stop
then List.rev acc
else if i < 0 then List.rev acc
else if i >= dim_size then collect acc (i + step)
else collect (i :: acc) (i + step)
in
collect [] start
| N ->
Error.invalid ~op:"indices_of_spec" ~what:"spec"
~reason:"new axis not supported in this context" ()
| M _ ->
Error.invalid ~op:"indices_of_spec" ~what:"spec"
~reason:"mask indexing not supported in this context" ()
let slice_internal slice_def x =
let x_shape = shape x in
let ndim = Array.length x_shape in
let new_axis_positions = ref [] in
let regular_specs = ref [] in
let output_dim = ref 0 in
List.iter
(fun spec ->
match spec with
| N ->
new_axis_positions := !output_dim :: !new_axis_positions;
output_dim := !output_dim + 1
| I _ ->
regular_specs := spec :: !regular_specs
| _ ->
regular_specs := spec :: !regular_specs;
output_dim := !output_dim + 1 )
slice_def;
let new_axis_positions = List.rev !new_axis_positions in
let regular_specs = List.rev !regular_specs in
let full_slice =
let n = List.length regular_specs in
if n > ndim then
Error.invalid ~op:"slice" ~what:"indices"
~reason:(Printf.sprintf "too many (%d > %d)" n ndim)
()
else regular_specs @ List.init (ndim - n) (fun _ -> A)
in
let analyze_pattern slice =
match slice with
| [] -> `Empty
| I _ :: rest when List.for_all (function I _ -> true | _ -> false) rest
->
`AllSingles
| _ ->
let is_c_contiguous =
List.for_all
(function
| I _ -> true
| A -> true
| R (s, e) -> s <= e
| Rs (s, e, 1) -> s <= e
| Rs (s, e, -1) -> s >= e
| Rs (_, _, _) ->
false
| _ -> false)
slice
in
if is_c_contiguous then `ContiguousRanges else `Mixed
in
let sliced_result =
match analyze_pattern full_slice with
| `Empty -> x
| `AllSingles ->
let indices =
List.mapi
(fun i spec ->
match spec with
| I idx -> normalize_index x_shape.(i) idx
| _ -> assert false)
full_slice
in
let shrink_config =
Array.of_list (List.mapi (fun _i idx -> (idx, idx + 1)) indices)
in
reshape [||] (shrink shrink_config x)
| `ContiguousRanges ->
let rec apply_slices tensor dim = function
| [] -> tensor
| spec :: rest ->
let tensor_ndim = Array.length (shape tensor) in
if dim >= tensor_ndim then tensor
else
let dim_size = (shape tensor).(dim) in
let tensor', next_dim =
match spec with
| I idx ->
let idx' = normalize_index dim_size idx in
let config =
Array.init tensor_ndim (fun i ->
if i = dim then (idx', idx' + 1)
else (0, (shape tensor).(i)))
in
(squeeze ~axes:[ dim ] (shrink config tensor), dim)
| A -> (tensor, dim + 1)
| R (start_idx, stop_idx) ->
let start =
if start_idx < 0 then dim_size + start_idx
else start_idx
in
let stop =
if stop_idx < 0 then dim_size + stop_idx else stop_idx
in
let stop = stop - 1 in
let step = 1 in
let is_empty =
if step > 0 then start > stop else start < stop
in
if is_empty then (
let new_shape = Array.copy (shape tensor) in
new_shape.(dim) <- 0;
( empty (B.context tensor) (dtype tensor) new_shape,
dim + 1 ))
else
let s, e =
if step > 0 then (start, stop + 1)
else (stop, start + 1)
in
let s_clamped = Int.max 0 (Int.min s dim_size) in
let e_clamped = Int.max 0 (Int.min e dim_size) in
let config =
Array.init tensor_ndim (fun i ->
if i = dim then (s_clamped, e_clamped)
else (0, (shape tensor).(i)))
in
let sliced = shrink config tensor in
( (if step < 0 then flip ~axes:[ dim ] sliced
else sliced),
dim + 1 )
| Rs (start_idx, stop_idx, step_val) ->
let start =
if start_idx < 0 then dim_size + start_idx
else start_idx
in
let stop =
if stop_idx < 0 then dim_size + stop_idx else stop_idx
in
let stop =
if step_val > 0 then stop - 1
else stop + 1
in
let step = step_val in
let is_empty =
if step > 0 then start > stop else start < stop
in
if is_empty then (
let new_shape = Array.copy (shape tensor) in
new_shape.(dim) <- 0;
( empty (B.context tensor) (dtype tensor) new_shape,
dim + 1 ))
else
let s, e =
if step > 0 then (start, stop + 1)
else (stop, start + 1)
in
let s_clamped = Int.max 0 (Int.min s dim_size) in
let e_clamped = Int.max 0 (Int.min e dim_size) in
let config =
Array.init tensor_ndim (fun i ->
if i = dim then (s_clamped, e_clamped)
else (0, (shape tensor).(i)))
in
let sliced = shrink config tensor in
( (if step < 0 then flip ~axes:[ dim ] sliced
else sliced),
dim + 1 )
| _ -> assert false
in
apply_slices tensor' next_dim rest
in
apply_slices x 0 full_slice
| `Mixed ->
let batch_process tensor processed_dims = function
| [] -> tensor
| specs ->
let groups = List.map (fun spec -> [ spec ]) specs in
let _, _, result =
List.fold_left
(fun (current_dim, dims_squeezed, tensor) group ->
match group with
| [] -> (current_dim, dims_squeezed, tensor)
| [ spec ] ->
let working_dim = current_dim - dims_squeezed in
let dim_size = (shape tensor).(working_dim) in
let indices = indices_of_spec dim_size spec in
let tensor' =
if List.length indices = dim_size then tensor
else if List.length indices = 0 then (
let new_shape = Array.copy (shape tensor) in
new_shape.(working_dim) <- 0;
empty (B.context tensor) (dtype tensor) new_shape)
else if List.length indices = 1 then
squeeze ~axes:[ working_dim ]
(shrink
(Array.init
(Array.length (shape tensor))
(fun i ->
if i = working_dim then
(List.hd indices, List.hd indices + 1)
else (0, (shape tensor).(i))))
tensor)
else
let data_shape = shape tensor in
let idx_shape = Array.copy data_shape in
idx_shape.(working_dim) <- List.length indices;
let idx_tensor =
init (B.context x) Dtype.int32 idx_shape
(fun idx_arr ->
Int32.of_int
(List.nth indices idx_arr.(working_dim)))
in
B.op_gather tensor idx_tensor working_dim
in
let dims_squeezed' =
if List.length indices = 1 then dims_squeezed + 1
else dims_squeezed
in
(current_dim + 1, dims_squeezed', tensor')
| _ ->
assert false)
(processed_dims, 0, tensor)
groups
in
result
in
batch_process x 0 full_slice
in
List.fold_left
(fun tensor axis_pos -> expand_dims [ axis_pos ] tensor)
sliced_result new_axis_positions
let set_slice_internal slice_def x y =
let x_shape = shape x in
let y_shape = shape y in
let ndim = Array.length x_shape in
let full_slice =
let n = List.length slice_def in
if n > ndim then
Error.invalid ~op:"slice" ~what:"indices"
~reason:(Printf.sprintf "too many (%d > %d)" n ndim)
()
else slice_def @ List.init (ndim - n) (fun _ -> A)
in
let indices_per_dim =
List.mapi (fun i spec -> indices_of_spec x_shape.(i) spec) full_slice
in
let is_scalar_setting =
List.length slice_def = ndim
&& List.for_all (function I _ -> true | _ -> false) slice_def
in
if is_scalar_setting then (
let indices =
List.mapi
(fun i spec ->
match spec with
| I idx -> normalize_index x_shape.(i) idx
| _ -> assert false)
slice_def
in
if y_shape <> [||] then
Error.cannot ~op:"set_slice" ~what:"assign"
~from:(Shape.to_string y_shape) ~to_:"scalar position"
~reason:"value must be scalar (shape [])"
~hint:"use a scalar tensor or reshape to []" ();
let linear_idx = ref 0 in
let stride = ref 1 in
for i = ndim - 1 downto 0 do
let idx = if i < List.length indices then List.nth indices i else 0 in
linear_idx := !linear_idx + (idx * !stride);
stride := !stride * x_shape.(i)
done;
let scatter_indices =
init (B.context x) Dtype.int32 [| 1 |] (fun _ ->
Int32.of_int !linear_idx)
in
let x_flat = reshape [| Array.fold_left ( * ) 1 x_shape |] x in
let y_flat = reshape [| 1 |] y in
let result_flat =
B.op_scatter ~mode:`Set ~unique_indices:false x_flat scatter_indices
y_flat 0
in
let result = reshape x_shape result_flat in
blit result x)
else
let expected_shape_list =
List.mapi
(fun i indices ->
match List.nth full_slice i with
| I _ -> None
| _ -> Some (List.length indices))
indices_per_dim
|> List.filter_map (fun x -> x)
in
let expected_shape = Array.of_list expected_shape_list in
let can_broadcast =
try
let _ = broadcast_to expected_shape y in
true
with _ -> false
in
if (not can_broadcast) && expected_shape <> y_shape then
Error.shape_mismatch ~op:"set_slice" ~expected:expected_shape
~actual:y_shape ();
let all_contiguous =
List.for_all2
(fun (i, spec) indices ->
match spec with
| I idx ->
List.length indices = 1
&& List.hd indices = normalize_index x_shape.(i) idx
| R (s, e) ->
let s' = normalize_index x_shape.(i) s in
let e' = normalize_index x_shape.(i) e - 1 in
List.length indices = Stdlib.abs (e' - s') + 1
| Rs (s, e, step) ->
let s' = normalize_index x_shape.(i) s in
let e' = normalize_index x_shape.(i) e in
let e' = if step > 0 then e' - 1 else e' + 1 in
List.length indices = Stdlib.abs (e' - s') + 1
| A -> List.length indices = x_shape.(i)
| _ -> false)
(List.mapi (fun i spec -> (i, spec)) full_slice)
indices_per_dim
in
if all_contiguous then
let x_slice_config =
List.mapi
(fun i spec ->
match spec with
| I idx ->
let idx' = normalize_index x_shape.(i) idx in
(idx', idx' + 1)
| A -> (0, x_shape.(i))
| R (s, e) ->
let s' = normalize_index x_shape.(i) s in
let e' = normalize_index x_shape.(i) e - 1 in
if s' <= e' then (s', e' + 1) else (e', s' + 1)
| Rs (s, e, step) ->
let s' = normalize_index x_shape.(i) s in
let e' = normalize_index x_shape.(i) e in
let e' = if step > 0 then e' - 1 else e' + 1 in
if step > 0 then
if s' <= e' then (s', e' + 1)
else (s', s')
else if s' >= e' then (e', s' + 1)
else (s', s')
| _ -> assert false)
full_slice
in
let x_view = shrink (Array.of_list x_slice_config) x in
let y_for_blit =
if shape x_view = y_shape then y
else
try broadcast_to (shape x_view) y
with _ ->
Error.broadcast_incompatible ~op:"set_slice" ~shape1:y_shape
~shape2:(shape x_view) ()
in
blit y_for_blit x_view
else
let y_broadcast =
if y_shape = expected_shape then y else broadcast_to expected_shape y
in
let total_updates = Array.fold_left ( * ) 1 expected_shape in
let y_flat = reshape [| total_updates |] y_broadcast in
let scatter_indices =
init (B.context x) Dtype.int32 [| total_updates |] (fun arr ->
let linear_idx = arr.(0) in
let temp = ref linear_idx in
let y_pos = Array.make (Array.length expected_shape) 0 in
for i = Array.length expected_shape - 1 downto 0 do
y_pos.(i) <- !temp mod expected_shape.(i);
temp := !temp / expected_shape.(i)
done;
let x_pos =
Array.mapi
(fun i y_idx -> List.nth (List.nth indices_per_dim i) y_idx)
y_pos
in
let x_linear = ref 0 in
let stride = ref 1 in
for i = ndim - 1 downto 0 do
x_linear := !x_linear + (x_pos.(i) * !stride);
stride := !stride * x_shape.(i)
done;
Int32.of_int !x_linear)
in
let x_flat = reshape [| Array.fold_left ( * ) 1 x_shape |] x in
let result_flat =
B.op_scatter ~mode:`Set ~unique_indices:false x_flat scatter_indices
y_flat 0
in
let result = reshape x_shape result_flat in
blit result x
let get indices x =
let x_shape = shape x in
let normalized_indices =
List.mapi
(fun dim idx ->
if dim >= Array.length x_shape then
Error.invalid ~op:"get" ~what:"indices"
~reason:(Format.asprintf "too many for shape %a" Shape.pp x_shape)
()
else
let normalized_idx = normalize_index x_shape.(dim) idx in
if normalized_idx < 0 || normalized_idx >= x_shape.(dim) then
Error.invalid ~op:"get"
~what:
(Printf.sprintf "index [%s]"
(String.concat "," (List.map string_of_int indices)))
~reason:
(Printf.sprintf "out of bounds for shape %s"
(Shape.to_string x_shape))
~hint:
(Printf.sprintf "index %d at dim %d: %d ∉ [0, %d)" dim dim
normalized_idx x_shape.(dim))
()
else normalized_idx)
indices
in
slice_internal (List.map (fun i -> I i) normalized_indices) x
let set indices x value =
let x_shape = shape x in
let normalized_indices =
List.mapi
(fun dim idx ->
if dim >= Array.length x_shape then
Error.invalid ~op:"set" ~what:"indices"
~reason:(Format.asprintf "too many for shape %a" Shape.pp x_shape)
()
else
let normalized_idx = normalize_index x_shape.(dim) idx in
if normalized_idx < 0 || normalized_idx >= x_shape.(dim) then
Error.invalid ~op:"set"
~what:(Printf.sprintf "index %d at dimension %d" idx dim)
~reason:
(Format.asprintf "out of bounds for shape %a" Shape.pp x_shape)
~hint:
(Printf.sprintf "index %d at dim %d: %d ∉ [0, %d)" dim dim
normalized_idx x_shape.(dim))
()
else normalized_idx)
indices
in
set_slice_internal (List.map (fun i -> I i) normalized_indices) x value
let unsafe_get indices x =
let scalar_tensor = get indices x in
let ba = data scalar_tensor in
if numel scalar_tensor <> 1 then
Error.failed ~op:"unsafe_get" ~what:"expected scalar result"
~reason:(Printf.sprintf "got %d elements" (numel scalar_tensor))
();
match Lazy_view.strides (B.view scalar_tensor) with
| Some _ ->
let view_offset = offset scalar_tensor in
Array1.get ba view_offset
| None ->
if Array1.dim ba = 1 then Array1.get ba 0
else
Error.failed ~op:"unsafe_get"
~what:"cannot read from non-composable scalar view"
~hint:"this is likely a bug in get/slice implementation" ()
let unsafe_set indices value x =
let scalar_tensor = scalar (B.context x) (dtype x) value in
set indices x scalar_tensor
let slice specs t = slice_internal specs t
let set_slice specs t value = set_slice_internal specs t value
let item indices t =
let t_shape = shape t in
if List.length indices <> Array.length t_shape then
invalid_arg
(Printf.sprintf "item: need %d indices for %d-d tensor, got %d"
(Array.length t_shape) (Array.length t_shape) (List.length indices));
let scalar_t = get indices t in
unsafe_get [] scalar_t
let set_item indices value t =
let t_shape = shape t in
if List.length indices <> Array.length t_shape then
invalid_arg
(Printf.sprintf "set_item: need %d indices for %d-d tensor, got %d"
(Array.length t_shape) (Array.length t_shape) (List.length indices));
unsafe_set indices value t
let take ?axis ?(mode = `raise) indices t =
let t_shape = shape t in
let context = B.context t in
match axis with
| None ->
let t_flat = reshape [| numel t |] t in
let indices_processed =
match mode with
| `raise ->
indices
| `wrap ->
let n = numel t in
mod_ indices (scalar (B.context indices) Int32 (Int32.of_int n))
| `clip ->
let max_idx = numel t - 1 in
minimum
(maximum indices (zeros context Int32 (shape indices)))
(full context Int32 (shape indices) (Int32.of_int max_idx))
in
B.op_gather t_flat indices_processed 0
| Some axis ->
let axis = resolve_single_axis t axis in
let axis_size = t_shape.(axis) in
let indices_processed =
match mode with
| `raise -> indices
| `wrap ->
let n = axis_size in
mod_ indices (scalar (B.context indices) Int32 (Int32.of_int n))
| `clip ->
let max_idx = axis_size - 1 in
minimum
(maximum indices (zeros context Int32 (shape indices)))
(full context Int32 (shape indices) (Int32.of_int max_idx))
in
let n_indices = numel indices_processed in
let out_shape = Array.copy t_shape in
out_shape.(axis) <- n_indices;
let expanded_indices_shape = Array.copy t_shape in
expanded_indices_shape.(axis) <- n_indices;
for i = 0 to Array.length t_shape - 1 do
if i <> axis then expanded_indices_shape.(i) <- 1
done;
let indices_expanded =
reshape expanded_indices_shape indices_processed
in
let broadcast_shape = Array.copy t_shape in
broadcast_shape.(axis) <- n_indices;
let indices_broadcast = broadcast_to broadcast_shape indices_expanded in
let result = B.op_gather t indices_broadcast axis in
reshape out_shape result
let take_along_axis ~axis indices t =
let axis = resolve_single_axis t axis in
let t_shape = shape t in
let idx_shape = shape indices in
if Array.length t_shape <> Array.length idx_shape then
Error.shape_mismatch ~op:"take_along_axis" ~expected:t_shape
~actual:idx_shape ();
Array.iteri
(fun i dim ->
if i <> axis && dim <> idx_shape.(i) then
Error.invalid ~op:"take_along_axis" ~what:"shape"
~reason:
(Printf.sprintf "dimension %d: indices has %d but tensor has %d" i
idx_shape.(i) dim)
())
t_shape;
B.op_gather t indices axis
let put ?axis ~indices ~values ?(mode = `raise) t =
let indices =
if dtype indices = Int32 then indices else astype Int32 indices
in
let context = B.context t in
match axis with
| None ->
let t_shape_orig = shape t in
let t_flat = reshape [| numel t |] t in
let indices_processed =
match mode with
| `raise -> indices
| `wrap ->
let n = numel t in
mod_ indices (scalar (B.context indices) Int32 (Int32.of_int n))
| `clip ->
let max_idx = numel t - 1 in
minimum
(maximum indices (zeros context Int32 (shape indices)))
(full context Int32 (shape indices) (Int32.of_int max_idx))
in
let indices_flat = reshape [| numel indices |] indices_processed in
let values_flat = reshape [| numel values |] values in
let result =
B.op_scatter ~mode:`Set ~unique_indices:false t_flat indices_flat
values_flat 0
in
blit (reshape t_shape_orig result) t
| Some axis ->
let axis = resolve_single_axis t axis in
let indices_processed =
match mode with
| `raise -> indices
| `wrap ->
let n = dim axis t in
mod_ indices (scalar (B.context indices) Int32 (Int32.of_int n))
| `clip ->
let max_idx = dim axis t - 1 in
minimum
(maximum indices (zeros context Int32 (shape indices)))
(full context Int32 (shape indices) (Int32.of_int max_idx))
in
let result =
B.op_scatter ~mode:`Set ~unique_indices:false t indices_processed
values axis
in
blit result t
let put_along_axis ~axis ~indices ~values t =
let axis = resolve_single_axis t axis in
let t_shape = shape t in
let idx_shape = shape indices in
let val_shape = shape values in
if Array.length t_shape <> Array.length idx_shape then
Error.shape_mismatch ~op:"put_along_axis" ~expected:t_shape
~actual:idx_shape ();
let values =
if val_shape = idx_shape then values else broadcast_to idx_shape values
in
let result =
B.op_scatter ~mode:`Set ~unique_indices:false t indices values axis
in
blit result t
let nonzero_indices_only (condition : (int, uint8_elt) t) =
let total = numel condition in
let cond_flat = reshape [| total |] condition in
let n_nonzero =
let sum_result = sum (astype Int32 cond_flat) in
let scalar_val = squeeze sum_result |> unsafe_get [] in
Int32.to_int scalar_val
in
if n_nonzero = 0 then [| empty (B.context condition) Int32 [| 0 |] |]
else
let indices =
create (B.context condition) Int32 [| n_nonzero |]
(Array.make n_nonzero 0l)
in
let idx = ref 0 in
for i = 0 to total - 1 do
let elem_val = unsafe_get [ i ] cond_flat in
if elem_val <> 0 then (
set_item [ !idx ] (Int32.of_int i) indices;
incr idx)
done;
[| indices |]
let compress ?axis ~(condition : (int, uint8_elt) t) t =
match axis with
| None ->
let t_flat = flatten t in
let cond_flat = flatten condition in
let n_true =
sum ~axes:[ 0 ] (astype Int32 cond_flat)
|> squeeze |> unsafe_get [] |> Int32.to_int
in
if n_true = 0 then empty (B.context t) (dtype t) [| 0 |]
else
let indices = nonzero_indices_only cond_flat in
take indices.(0) t_flat
| Some axis ->
let axis = resolve_single_axis t axis in
let axis_size = dim axis t in
if numel condition <> axis_size then
invalid_arg
(Printf.sprintf "compress: length %d doesn't match axis %d size %d"
(numel condition) axis axis_size);
let true_indices =
nonzero_indices_only (reshape [| axis_size |] condition)
in
if Array.length true_indices = 0 || numel true_indices.(0) = 0 then (
let new_shape = Array.copy (shape t) in
new_shape.(axis) <- 0;
empty (B.context t) (dtype t) new_shape)
else take ~axis true_indices.(0) t
let ~condition t =
if shape condition <> shape t then invalid_arg "extract: shape mismatch";
compress ~condition (flatten t)
let nonzero (type a b) (t : (a, b) t) =
let t_shape = shape t in
let ndim = Array.length t_shape in
let zero = zeros (B.context t) (dtype t) [| 1 |] in
let mask = not_equal t (broadcast_to t_shape zero) in
let total = numel mask in
let mask_flat = reshape [| total |] mask in
let n_nonzero =
let sum_result = sum (astype Int32 mask_flat) in
let scalar_val = squeeze sum_result |> unsafe_get [] in
Int32.to_int scalar_val
in
if n_nonzero = 0 then
Array.init ndim (fun _ -> empty (B.context t) Int32 [| 0 |])
else
let coords =
Array.init ndim (fun _ ->
create (B.context t) Int32 [| n_nonzero |] (Array.make n_nonzero 0l))
in
let idx = ref 0 in
let rec process_indices pos dim_idx =
if dim_idx = ndim then (
let indices = Array.to_list pos in
let elem = get indices t in
let zero_scalar = zeros (B.context t) (dtype t) (shape elem) in
let is_nonzero_tensor = not_equal elem zero_scalar in
let is_nonzero = unsafe_get [] is_nonzero_tensor <> 0 in
if is_nonzero then (
for i = 0 to ndim - 1 do
let coord_arr = coords.(i) in
set_item [ !idx ] (Int32.of_int pos.(i)) coord_arr
done;
incr idx))
else
for i = 0 to t_shape.(dim_idx) - 1 do
pos.(dim_idx) <- i;
process_indices pos (dim_idx + 1)
done
in
let pos = Array.make ndim 0 in
process_indices pos 0;
Array.map (fun coord -> slice [ Rs (0, !idx, 1) ] coord) coords
let argwhere t =
let coords = nonzero t in
if Array.length coords = 0 then empty (B.context t) Int32 [| 0; 0 |]
else
let n_nonzero = dim 0 coords.(0) in
let ndim = Array.length coords in
if n_nonzero = 0 then empty (B.context t) Int32 [| 0; ndim |]
else
let result = zeros (B.context t) Int32 [| n_nonzero; ndim |] in
for i = 0 to ndim - 1 do
let col_slice = slice_internal [ A; I i ] result in
let coord_values = flatten coords.(i) in
blit coord_values col_slice
done;
result
let array_split ~axis sections x =
let ndim = ndim x in
let axis = resolve_single_axis x axis in
let axis_size = dim axis x in
match sections with
| `Indices indices ->
let indices = Array.of_list indices in
let n_sections = Array.length indices + 1 in
let splits = Array.make n_sections x in
let boundaries = Array.make (n_sections + 1) 0 in
boundaries.(0) <- 0;
Array.iteri (fun i idx -> boundaries.(i + 1) <- idx) indices;
boundaries.(n_sections) <- axis_size;
for i = 0 to n_sections - 1 do
let start = boundaries.(i) in
let stop = boundaries.(i + 1) in
if start < stop then
let slice_spec =
List.init ndim (fun j -> if j = axis then R (start, stop) else A)
in
splits.(i) <- slice_internal slice_spec x
else
let empty_shape = Array.copy (shape x) in
empty_shape.(axis) <- 0;
splits.(i) <- empty (B.context x) (dtype x) empty_shape
done;
Array.to_list splits
| `Count n ->
if n <= 0 then
Error.check_bounds ~op:"array_split" ~name:"sections" ~value:n ~min:1
();
let base_size = axis_size / n in
let remainder = axis_size mod n in
let sizes = Array.make n base_size in
for i = 0 to remainder - 1 do
sizes.(i) <- sizes.(i) + 1
done;
let splits = Array.make n x in
let start = ref 0 in
for i = 0 to n - 1 do
let size = sizes.(i) in
let stop = !start + size in
let slice_spec =
List.init ndim (fun j -> if j = axis then R (!start, stop) else A)
in
splits.(i) <- slice_internal slice_spec x;
start := stop
done;
Array.to_list splits
let split ~axis sections x =
let axis = resolve_single_axis x axis in
let axis_size = dim axis x in
if axis_size mod sections <> 0 then
Error.cannot ~op:"split" ~what:"divide evenly"
~from:(Printf.sprintf "axis %d (size %d)" axis axis_size)
~to_:(Printf.sprintf "%d sections" sections)
~reason:
(Printf.sprintf "%d %% %d = %d" axis_size sections
(axis_size mod sections))
~hint:"use array_split for uneven division" ();
array_split ~axis (`Count sections) x
let validate_random_params fname dtype shape =
if not (Dtype.is_float dtype) then
Error.invalid ~op:fname
~what:(Printf.sprintf "dtype %s" (Dtype.to_string dtype))
~reason:"not a float type"
~hint:"rand/randn only support Float16, Float32, Float64" ();
if Array.exists (fun x -> x < 0) shape then
Error.invalid_shape ~op:fname ~shape
~reason:"dimensions must be non-negative" ()
let rand ctx dtype ?(seed = 42) shape =
validate_random_params "rand" dtype shape;
let numel = array_prod shape in
if numel = 0 then zeros ctx dtype shape
else
let num_values = numel in
let key_vals =
Array.init (num_values * 2) (fun i -> Int32.of_int (seed + i))
in
let key = create ctx Dtype.int32 [| num_values; 2 |] key_vals in
let ctr_vals = Array.init (num_values * 2) (fun i -> Int32.of_int i) in
let counter = create ctx Dtype.int32 [| num_values; 2 |] ctr_vals in
let random_bits = B.op_threefry key counter in
let bits_flat = flatten random_bits in
let bits_needed =
if numel < size bits_flat then shrink [| (0, numel) |] bits_flat
else bits_flat
in
let bits_float32 = cast Dtype.float32 bits_needed in
let offset = scalar ctx Dtype.float32 2147483648.0 in
let shifted = add bits_float32 offset in
let normalizer = scalar ctx Dtype.float32 4294967296.0 in
let normalized = div shifted normalizer in
let result = cast dtype normalized in
reshape shape result
let randn ctx dtype ?(seed = 42) shape =
validate_random_params "randn" dtype shape;
let numel = array_prod shape in
if numel = 0 then zeros ctx dtype shape
else
let u1 = rand ctx Dtype.float32 ~seed shape in
let u2 = rand ctx Dtype.float32 ~seed:(seed + numel) shape in
let two_pi = scalar ctx Dtype.float32 (2.0 *. Float.pi) in
let angle = mul u1 two_pi in
let cos_part = cos angle in
let one = ones_like u2 in
let u2_safe = sub one u2 in
let eps = scalar ctx Dtype.float32 1e-7 in
let u2_nonzero = maximum u2_safe eps in
let log_u2 = log u2_nonzero in
let neg_two = scalar ctx Dtype.float32 (-2.0) in
let sqrt_arg = mul neg_two log_u2 in
let sqrt_part = sqrt sqrt_arg in
let result_f32 = mul cos_part sqrt_part in
cast dtype result_f32
let randint ctx dtype ?(seed = 42) ?(high = 10) shape low =
if not (Dtype.is_int dtype) then
Error.invalid ~op:"randint" ~what:"dtype"
~reason:"only integer dtypes supported" ();
if Array.exists (fun x -> x < 0) shape then
Error.invalid_shape ~op:"randint" ~shape
~reason:"dimensions must be non-negative" ();
if low >= high then
Error.invalid ~op:"randint" ~what:"range"
~reason:(Printf.sprintf "low=%d ≥ high=%d" low high)
();
let numel = array_prod shape in
if numel = 0 then zeros ctx dtype shape
else
let uniform = rand ctx Dtype.float32 ~seed shape in
let range = float_of_int (high - low) in
let range_tensor = scalar ctx Dtype.float32 range in
let scaled = mul uniform range_tensor in
let low_tensor = scalar ctx Dtype.float32 (float_of_int low) in
let shifted = add scaled low_tensor in
let floored = floor shifted in
cast dtype floored
let sort (type a b) ?(descending = false) ?(axis = -1) (x : (a, b) t) =
let axis = resolve_single_axis x axis in
let ndim_x = ndim x in
if axis < 0 || axis >= ndim_x then
Error.axis_out_of_bounds ~op:"sort" ~axis ~ndim:ndim_x ();
let orig_len = dim axis x in
if orig_len <= 1 then
let idx = arange (B.context x) Dtype.int32 0 orig_len 1 in
let idx_shape =
Array.init (ndim x) (fun i -> if i = axis then orig_len else 1)
in
let idx = reshape idx_shape idx in
(x, idx)
else
let n_stages =
int_of_float (Float.ceil (Float.log2 (float_of_int orig_len)))
in
let padded_len = 1 lsl n_stages in
let fill_value =
if descending then Dtype.min_value (dtype x)
else
match dtype x with
| dt when Dtype.is_float dt -> Dtype.of_float dt Float.infinity
| Dtype.Int32 -> Int32.max_int
| Dtype.Int64 -> Int64.max_int
| dt -> Dtype.of_float dt 1e10
in
let x_for_sort =
if Dtype.is_float (dtype x) then
let is_nan = isnan x in
let inf_val =
if descending then
full_like x (Dtype.of_float (dtype x) Float.neg_infinity)
else full_like x (Dtype.of_float (dtype x) Float.infinity)
in
where is_nan inf_val x
else x
in
let pad_config =
Array.init (ndim x) (fun i ->
if i = axis then (0, padded_len - orig_len) else (0, 0))
in
let x_pad = pad pad_config fill_value x_for_sort in
let unflatten_sizes = Array.make n_stages 2 in
let x_unflatten = unflatten axis unflatten_sizes x_pad in
let x_ref = ref x_unflatten in
for stage = 1 to n_stages do
(if stage <> n_stages then
let crossover_dim = axis + n_stages - stage - 1 in
let boxes = split ~axis:crossover_dim 2 !x_ref in
let blue_box = List.nth boxes 0 in
let green_box = List.nth boxes 1 in
let n_dims_to_flip = stage + 1 + (ndim x - axis) in
let flip_axes =
Array.init n_dims_to_flip (fun i -> ndim green_box - 1 - i)
|> Array.to_list
|> List.filter (fun i -> i >= 0 && i < ndim green_box)
in
let green_box_flipped = flip green_box ~axes:flip_axes in
x_ref :=
concatenate ~axis:crossover_dim [ blue_box; green_box_flipped ]);
for substage = stage - 1 downto 0 do
let partner_dim = axis + n_stages - substage - 1 in
let parts = split ~axis:partner_dim 2 !x_ref in
let x_top = List.nth parts 0 in
let x_bottom = List.nth parts 1 in
let x_larger = maximum x_top x_bottom in
let x_smaller = minimum x_top x_bottom in
x_ref :=
if descending then
concatenate ~axis:partner_dim [ x_larger; x_smaller ]
else concatenate ~axis:partner_dim [ x_smaller; x_larger ]
done;
if stage <> n_stages then
let crossover_dim = axis + n_stages - stage - 1 in
let boxes = split ~axis:crossover_dim 2 !x_ref in
let blue_box = List.nth boxes 0 in
let flipped_green_box = List.nth boxes 1 in
let n_dims_to_flip = stage + 1 + (ndim x - axis) in
let flip_axes =
Array.init n_dims_to_flip (fun i -> ndim flipped_green_box - 1 - i)
|> Array.to_list
|> List.filter (fun i -> i >= 0 && i < ndim flipped_green_box)
in
let green_box = flip ~axes:flip_axes flipped_green_box in
x_ref := concatenate ~axis:crossover_dim [ blue_box; green_box ]
done;
let x_sorted =
flatten ~start_dim:axis ~end_dim:(axis + n_stages - 1) !x_ref
in
let shrink_slice =
List.init (ndim x_sorted) (fun i ->
if i = axis then R (0, orig_len) else A)
in
let x_sorted = slice_internal shrink_slice x_sorted in
let idx = arange (B.context x) Dtype.int32 0 orig_len 1 in
let idx_shape =
Array.init (ndim x) (fun i -> if i = axis then orig_len else 1)
in
let idx = reshape idx_shape idx in
let idx = expand (shape x_sorted) idx in
let compute_counts tensor =
let t_exp_new = unsqueeze tensor ~axes:[ axis + 1 ] in
let t_exp_orig = unsqueeze tensor ~axes:[ axis ] in
let idx_exp_new = unsqueeze idx ~axes:[ axis + 1 ] in
let idx_exp_orig = unsqueeze idx ~axes:[ axis ] in
let le_mask = less_equal idx_exp_orig idx_exp_new in
let eq_mask = equal t_exp_orig t_exp_new in
let mask = logical_and le_mask eq_mask in
sum mask ~axes:[ axis + 1 ] ~keepdims:false
in
let count_orig = compute_counts x_for_sort in
let count_sorted = compute_counts x_sorted in
let self_exp = unsqueeze ~axes:[ axis + 1 ] x_for_sort in
let sorted_exp = unsqueeze x_sorted ~axes:[ axis ] in
let count_orig_exp = unsqueeze count_orig ~axes:[ axis + 1 ] in
let count_sorted_exp = unsqueeze count_sorted ~axes:[ axis ] in
let idx_exp = unsqueeze idx ~axes:[ axis + 1 ] in
let value_match = equal self_exp sorted_exp in
let count_match = equal count_orig_exp count_sorted_exp in
let matches = logical_and value_match count_match in
let matches_int = cast Dtype.int32 matches in
let weighted_idx = mul matches_int idx_exp in
let final_idx = sum weighted_idx ~axes:[ axis ] ~keepdims:false in
let x_sorted_final =
if Dtype.is_float (dtype x) then
let nan_val =
full_like x_sorted (Dtype.of_float (dtype x) Float.nan)
in
let is_inf =
if descending then
equal x_sorted
(full_like x_sorted
(Dtype.of_float (dtype x) Float.neg_infinity))
else
equal x_sorted
(full_like x_sorted (Dtype.of_float (dtype x) Float.infinity))
in
where is_inf nan_val x_sorted
else x_sorted
in
(x_sorted_final, final_idx)
let argsort ?(descending = false) ?(axis = -1) x =
let _, indices = sort ~descending ~axis x in
indices
let argmax ?axis ?(keepdims = false) x =
let t_ndim = ndim x in
let reduction_axis =
match axis with
| None -> List.init t_ndim Fun.id
| Some ax -> [ resolve_single_axis ~ndim_opt:t_ndim x ax ]
in
let t_for_reduce = if axis = None then flatten x else x in
let current_axis_idx =
if axis = None then 0 else List.nth reduction_axis 0
in
let axis_len = dim current_axis_idx t_for_reduce in
if axis_len = 0 then
let out_shape =
if keepdims then
shape
t_for_reduce
else
Array.of_list
(List.filteri
(fun i _ -> i <> current_axis_idx)
(Array.to_list (shape t_for_reduce)))
in
if Array.length out_shape = 0 && numel t_for_reduce > 0 then
scalar (B.context x) Dtype.int32 0l
else empty (B.context x) Dtype.int32 out_shape
else
let max_vals = max ~axes:reduction_axis ~keepdims:true t_for_reduce in
let is_max_mask = equal t_for_reduce max_vals in
let arange_vals =
arange (B.context x) Dtype.int32 (axis_len - 1) (-1) (-1)
in
let arange_shape = Array.make (ndim t_for_reduce) 1 in
arange_shape.(current_axis_idx) <- axis_len;
let arange_b = reshape arange_shape arange_vals in
let arange_bc = broadcast_to (shape is_max_mask) arange_b in
let masked_arange = mul (cast Dtype.int32 is_max_mask) arange_bc in
let max_indices_from_end =
max ~axes:reduction_axis ~keepdims:true masked_arange
in
let axis_len_tensor =
scalar (B.context x) Dtype.int32 (Int32.of_int (axis_len - 1))
in
let axis_len_bc =
broadcast_to (shape max_indices_from_end) axis_len_tensor
in
let final_indices = sub axis_len_bc max_indices_from_end in
if keepdims then final_indices
else
let final_shape =
if axis = None then [||]
else
Array.of_list
(List.filteri
(fun i _ -> i <> current_axis_idx)
(Array.to_list (shape t_for_reduce)))
in
reshape final_shape final_indices
let argmin (type a b) ?axis ?(keepdims = false) (x : (a, b) t) :
(int32, Dtype.int32_elt) t =
let t_dtype = dtype x in
let t_inverted =
if Dtype.is_float t_dtype then neg x
else if Dtype.is_int t_dtype && not (Dtype.is_uint t_dtype) then neg x
else if Dtype.is_uint t_dtype then
let max_val_specific : (a, b) t =
match t_dtype with
| Dtype.UInt8 -> scalar (B.context x) Dtype.uint8 255
| Dtype.UInt16 -> scalar (B.context x) Dtype.uint16 65535
| _ ->
Error.failed ~op:"argmin"
~what:"unsupported uint dtype for inversion" ()
in
let max_val_b = broadcast_to (shape x) max_val_specific in
sub max_val_b x
else Error.failed ~op:"argmin" ~what:"unsupported dtype" ()
in
argmax ?axis ~keepdims t_inverted
let dot x_tensor w_tensor =
let ndim_x = ndim x_tensor in
let ndim_w = ndim w_tensor in
if not (ndim_x > 0 && ndim_w > 0) then
Error.invalid ~op:"dot" ~what:"tensors" ~reason:"both must be at least 1D"
();
match (ndim_x, ndim_w) with
| 1, 1 ->
let product = mul x_tensor w_tensor in
sum product
| 1, _ ->
let x_2d = unsqueeze ~axes:[ 0 ] x_tensor in
let result = B.op_matmul x_2d w_tensor in
squeeze ~axes:[ ndim result - 2 ] result
| _, 1 ->
let w_2d = unsqueeze ~axes:[ 1 ] w_tensor in
let result = B.op_matmul x_tensor w_2d in
squeeze ~axes:[ ndim result - 1 ] result
| _ ->
B.op_matmul x_tensor w_tensor
let matmul a_orig b_orig =
let ndim_a_orig = ndim a_orig in
let ndim_b_orig = ndim b_orig in
if ndim_a_orig = 0 || ndim_b_orig = 0 then
Error.invalid ~op:"matmul" ~what:"inputs"
~reason:"cannot be 0-D (scalars)" ();
let a, b =
if ndim_a_orig = 1 && ndim_b_orig = 1 then
(unsqueeze ~axes:[ 0 ] a_orig, unsqueeze ~axes:[ 1 ] b_orig)
else if ndim_a_orig = 1 then
(unsqueeze ~axes:[ 0 ] a_orig, b_orig)
else if ndim_b_orig = 1 then
(a_orig, unsqueeze ~axes:[ 1 ] b_orig)
else
(a_orig, b_orig)
in
let result_intermediate = B.op_matmul a b in
if ndim_a_orig = 1 && ndim_b_orig = 1 then
squeeze result_intermediate
else if ndim_a_orig = 1 then
squeeze ~axes:[ ndim result_intermediate - 2 ] result_intermediate
else if ndim_b_orig = 1 then
squeeze ~axes:[ ndim result_intermediate - 1 ] result_intermediate
else
result_intermediate
let diagonal ?offset ?axis1 ?axis2 a =
let offset = Option.value offset ~default:0 in
let ndim_a = ndim a in
let axis1 = Option.value axis1 ~default:(ndim_a - 2) in
let axis2 = Option.value axis2 ~default:(ndim_a - 1) in
let axis1 = if axis1 < 0 then ndim_a + axis1 else axis1 in
let axis2 = if axis2 < 0 then ndim_a + axis2 else axis2 in
if axis1 = axis2 then Error.failed ~op:"diagonal" ~what:"axis1 = axis2" ();
if axis1 <> ndim_a - 2 || axis2 <> ndim_a - 1 then
Error.failed ~op:"diagonal" ~what:"non-default axes not yet implemented"
();
let shape_a = shape a in
if ndim_a < 2 then
Error.invalid ~op:"diagonal" ~what:"input must be at least 2D" ();
let m = shape_a.(ndim_a - 2) in
let n = shape_a.(ndim_a - 1) in
let diag_len =
if offset >= 0 then Stdlib.min m (n - offset)
else Stdlib.min (m + offset) n
in
if diag_len <= 0 then
let new_shape =
Array.init (ndim_a - 1) (fun i ->
if i < ndim_a - 2 then shape_a.(i) else 0)
in
zeros (B.context a) (dtype a) new_shape
else
let row_start = if offset < 0 then -offset else 0 in
let col_start = if offset > 0 then offset else 0 in
let sliced =
if
row_start > 0 || col_start > 0
|| row_start + diag_len < m
|| col_start + diag_len < n
then
let slice_spec =
Array.init ndim_a (fun i ->
if i = ndim_a - 2 then (row_start, row_start + diag_len)
else if i = ndim_a - 1 then (col_start, col_start + diag_len)
else (0, shape_a.(i)))
in
shrink slice_spec a
else if diag_len < m || diag_len < n then
let slice_spec =
Array.init ndim_a (fun i ->
if i = ndim_a - 2 then (0, diag_len)
else if i = ndim_a - 1 then (0, diag_len)
else (0, shape_a.(i)))
in
shrink slice_spec a
else a
in
let eye_mat = eye (B.context a) (dtype a) diag_len in
let eye_broadcasted =
if ndim_a > 2 then
let eye_shape =
Array.init ndim_a (fun i ->
if i < ndim_a - 2 then 1
else if i = ndim_a - 2 then diag_len
else diag_len)
in
let eye_reshaped = reshape eye_shape eye_mat in
broadcast_to (shape sliced) eye_reshaped
else eye_mat
in
let masked = mul sliced eye_broadcasted in
sum masked ~axes:[ ndim_a - 1 ] ~keepdims:false
let matrix_transpose x =
let nd = ndim x in
if nd < 2 then x else swapaxes (nd - 2) (nd - 1) x
let vdot (type a b) (a : (a, b) t) (b : (a, b) t) =
let a', b' =
try
let broadcasted = broadcast_arrays [ a; b ] in
let a_bc = List.nth broadcasted 0 in
let b_bc = List.nth broadcasted 1 in
(contiguous a_bc, contiguous b_bc)
with _ ->
(a, b)
in
let flat_a = flatten a' in
let flat_b = flatten b' in
if numel flat_a <> numel flat_b then
invalid_arg "vdot: different number of elements";
match dtype a with
| (Complex32 | Complex64) when dtype a = dtype b ->
sum (mul flat_a flat_b)
| _ -> sum (mul flat_a flat_b)
let vecdot ?axis x1 x2 =
match axis with
| None ->
let axis = ndim x1 - 1 in
let prod = mul x1 x2 in
B.op_reduce_sum ~axes:[| axis |] ~keepdims:false prod
| Some ax ->
let ax = if ax < 0 then ndim x1 + ax else ax in
let prod = mul x1 x2 in
B.op_reduce_sum ~axes:[| ax |] ~keepdims:false prod
let inner a b =
let shape_a = shape a in
let shape_b = shape b in
let last_a = shape_a.(ndim a - 1) in
let last_b = shape_b.(ndim b - 1) in
if last_a <> last_b then invalid_arg "inner: last dimensions differ";
vecdot ~axis:(-1) a b
let outer a b =
let flat_a = if ndim a = 0 then reshape [| 1 |] a else flatten a in
let flat_b = if ndim b = 0 then reshape [| 1 |] b else flatten b in
let a_col = reshape [| numel flat_a; 1 |] flat_a in
let b_row = reshape [| 1; numel flat_b |] flat_b in
let result = matmul a_col b_row in
let result = if ndim a = 0 then squeeze ~axes:[ 0 ] result else result in
let result =
if ndim b = 0 then squeeze ~axes:[ (if ndim a = 0 then 0 else 1) ] result
else result
in
result
let tensordot ?axes a b =
match axes with
| None ->
matmul a b
| Some (axes_a, axes_b) ->
let n_axes = List.length axes_a in
if n_axes <> List.length axes_b then
invalid_arg "tensordot: axes lists must have same length";
let ndim_a = ndim a in
let ndim_b = ndim b in
let axes_a =
Array.of_list
(List.map (fun ax -> if ax < 0 then ndim_a + ax else ax) axes_a)
in
let axes_b =
Array.of_list
(List.map (fun ax -> if ax < 0 then ndim_b + ax else ax) axes_b)
in
let shape_a = shape a in
let shape_b = shape b in
Array.iter2
(fun ax_a ax_b ->
if shape_a.(ax_a) <> shape_b.(ax_b) then
invalid_arg "tensordot: axes have different sizes")
axes_a axes_b;
let axes_a_set =
Array.fold_left (fun s x -> IntSet.add x s) IntSet.empty axes_a
in
let axes_b_set =
Array.fold_left (fun s x -> IntSet.add x s) IntSet.empty axes_b
in
let free_axes_a =
Array.init ndim_a (fun i -> i)
|> Array.to_list
|> List.filter (fun i -> not (IntSet.mem i axes_a_set))
|> Array.of_list
in
let free_axes_b =
Array.init ndim_b (fun i -> i)
|> Array.to_list
|> List.filter (fun i -> not (IntSet.mem i axes_b_set))
|> Array.of_list
in
let perm_a = Array.append free_axes_a axes_a in
let perm_b = Array.append axes_b free_axes_b in
let a_transposed =
if Array.length perm_a > 1 then
transpose ~axes:(Array.to_list perm_a) a
else a
in
let b_transposed =
if Array.length perm_b > 1 then
transpose ~axes:(Array.to_list perm_b) b
else b
in
let a_transposed = contiguous a_transposed in
let b_transposed = contiguous b_transposed in
let shape_a_t = shape a_transposed in
let shape_b_t = shape b_transposed in
let n_free_a = Array.length free_axes_a in
let n_free_b = Array.length free_axes_b in
let free_size_a =
if n_free_a = 0 then 1
else Array.fold_left ( * ) 1 (Array.sub shape_a_t 0 n_free_a)
in
let free_size_b =
if n_free_b = 0 then 1
else
Array.fold_left ( * ) 1
(Array.sub shape_b_t n_axes (ndim_b - n_axes))
in
let contracted_size =
Array.fold_left ( * ) 1 (Array.sub shape_a_t n_free_a n_axes)
in
let a_mat = reshape [| free_size_a; contracted_size |] a_transposed in
let b_mat = reshape [| contracted_size; free_size_b |] b_transposed in
let result_mat = matmul a_mat b_mat in
let result_shape =
Array.append
(if n_free_a = 0 then [||] else Array.sub shape_a_t 0 n_free_a)
(if n_free_b = 0 then [||]
else Array.sub shape_b_t n_axes (ndim_b - n_axes))
in
if Array.length result_shape = 0 then
squeeze result_mat
else reshape result_shape result_mat
module Einsum = struct
let invalid_arg fmt =
Printf.ksprintf (fun s -> invalid_arg ("einsum: " ^ s)) fmt
module CharSet = Set.Make (Char)
type token = Axis of char | Ellipsis
let string_contains str c =
try
ignore (String.index str c);
true
with Not_found -> false
let list_init n f =
let rec aux acc i =
if i = n then List.rev acc else aux (f i :: acc) (i + 1)
in
aux [] 0
let same_shape a b =
let len_a = Array.length a in
if len_a <> Array.length b then false
else
let rec aux i =
if i = len_a then true
else if a.(i) <> b.(i) then false
else aux (i + 1)
in
aux 0
let product dims =
let acc = ref 1 in
Array.iter (fun d -> acc := !acc * d) dims;
!acc
let slice arr start len = if len = 0 then [||] else Array.sub arr start len
let is_identity perm =
let len = Array.length perm in
let rec aux i =
if i = len then true else if perm.(i) <> i then false else aux (i + 1)
in
aux 0
let concat_arrays arrs = Array.concat arrs
let char_set_of_string str = CharSet.of_seq (String.to_seq str)
let all_distinct str =
String.length str = CharSet.cardinal (char_set_of_string str)
let permutes str str' =
CharSet.equal (char_set_of_string str) (char_set_of_string str')
let count_named tokens =
List.fold_left
(fun acc -> function Axis _ -> acc + 1 | Ellipsis -> acc)
0 tokens
let parse_operand str =
let len = String.length str in
if len = 0 then invalid_arg "empty subscript";
let rec loop idx acc ellipsis_seen =
if idx >= len then List.rev acc
else
match str.[idx] with
| '.' ->
if idx + 2 >= len || str.[idx + 1] <> '.' || str.[idx + 2] <> '.'
then invalid_arg "ellipsis must be '...'";
if ellipsis_seen then invalid_arg "multiple ellipsis in operand";
loop (idx + 3) (Ellipsis :: acc) true
| c
when (Char.code c >= Char.code 'a' && Char.code c <= Char.code 'z')
|| Char.code c >= Char.code 'A'
&& Char.code c <= Char.code 'Z'
|| Char.code c >= Char.code '0'
&& Char.code c <= Char.code '9'
|| Char.equal c '_' ->
loop (idx + 1) (Axis c :: acc) ellipsis_seen
| c -> invalid_arg "invalid character '%c' in subscript" c
in
loop 0 [] false
let find_arrow str =
let len = String.length str in
let rec aux idx =
if idx + 1 >= len then None
else if str.[idx] = '-' && str.[idx + 1] = '>' then Some idx
else aux (idx + 1)
in
aux 0
let parse_equation subscripts =
let subscripts = String.trim subscripts in
let arrow_pos = find_arrow subscripts in
let inputs_part, output_part_opt =
match arrow_pos with
| None -> (subscripts, None)
| Some idx ->
let inputs = String.sub subscripts 0 idx in
let output =
String.sub subscripts (idx + 2)
(String.length subscripts - idx - 2)
in
(inputs, Some (String.trim output))
in
let parse_inputs str =
str |> String.split_on_char ',' |> List.map String.trim
|> List.filter (fun s -> String.length s > 0)
in
let input_strs = parse_inputs inputs_part in
if input_strs = [] then invalid_arg "no input operands";
let input_tokens = Array.of_list (List.map parse_operand input_strs) in
let output_tokens_opt =
match output_part_opt with
| None -> None
| Some output_str ->
if String.length output_str = 0 then Some []
else Some (parse_operand output_str)
in
(input_tokens, output_tokens_opt)
type axis_label = Named of char | Ell of int
let remove_index list idx_to_remove =
let rec aux idx acc = function
| [] -> List.rev acc
| _x :: xs when idx = idx_to_remove -> List.rev_append acc xs
| x :: xs -> aux (idx + 1) (x :: acc) xs
in
aux 0 [] list
let diagonal_axes tensor axis1 axis2 =
let ndim_tensor = ndim tensor in
if axis1 < 0 || axis1 >= ndim_tensor || axis2 < 0 || axis2 >= ndim_tensor
then invalid_arg "diagonal axis out of bounds";
if axis1 = axis2 then invalid_arg "diagonal axes must differ";
let axis1, axis2 =
if axis1 < axis2 then (axis1, axis2) else (axis2, axis1)
in
let identity = Array.init ndim_tensor Fun.id in
let same_as_identity arr =
Array.length arr = Array.length identity
&& Array.for_all2 ( = ) arr identity
in
let others =
List.filter
(fun ax -> ax <> axis1 && ax <> axis2)
(Array.to_list identity)
in
let perm = Array.of_list (others @ [ axis1; axis2 ]) in
let tensor_permuted =
if same_as_identity perm then tensor
else transpose ~axes:(Array.to_list perm) tensor
in
let shape_perm = shape tensor_permuted in
if
shape_perm.(Array.length shape_perm - 1)
<> shape_perm.(Array.length shape_perm - 2)
then invalid_arg "diagonal requires equal dimensions for repeated index";
let diag_tensor = diagonal tensor_permuted in
let current_order = others @ [ axis1 ] in
let target_order =
List.filter (fun ax -> ax <> axis2) (Array.to_list identity)
in
let index_map = Hashtbl.create (List.length current_order) in
List.iteri (fun idx ax -> Hashtbl.add index_map ax idx) current_order;
let axes_reorder =
Array.of_list
(List.map
(fun ax ->
match Hashtbl.find_opt index_map ax with
| Some idx -> idx
| None -> assert false)
target_order)
in
if Array.length axes_reorder <= 1 then diag_tensor
else transpose ~axes:(Array.to_list axes_reorder) diag_tensor
let find_duplicate_named labels =
let seen = Hashtbl.create 16 in
let rec aux idx = function
| [] -> None
| Named c :: rest -> (
match Hashtbl.find_opt seen c with
| Some first -> Some (first, idx, c)
| None ->
Hashtbl.add seen c idx;
aux (idx + 1) rest)
| Ell _ :: rest -> aux (idx + 1) rest
in
aux 0 labels
let diagonalize_operand tensor tokens =
let ndim_tensor = ndim tensor in
let named_count = count_named tokens in
let ell_count = ndim_tensor - named_count in
if ell_count < 0 then invalid_arg "operand rank too small for subscripts";
let axis_labels =
let rec build tokens axis_idx acc =
match tokens with
| [] -> List.rev acc
| Axis c :: rest -> build rest (axis_idx + 1) (Named c :: acc)
| Ellipsis :: rest ->
let rec add acc i =
if i = ell_count then acc else add (Ell i :: acc) (i + 1)
in
build rest (axis_idx + ell_count) (add acc 0)
in
build tokens 0 []
in
let rec loop tensor labels =
match find_duplicate_named labels with
| None -> tensor
| Some (axis1, axis2, c) ->
let shape_tensor = shape tensor in
if shape_tensor.(axis1) <> shape_tensor.(axis2) then
invalid_arg
"index var '%c' must have consistent dimensions (%d vs %d)" c
shape_tensor.(axis1) shape_tensor.(axis2);
let tensor' = diagonal_axes tensor axis1 axis2 in
let labels' = remove_index labels axis2 in
loop tensor' labels'
in
let tensor' = loop tensor axis_labels in
let deduped_tokens =
let seen = Hashtbl.create 16 in
let rec aux acc = function
| [] -> List.rev acc
| Axis c :: rest ->
if Hashtbl.mem seen c then aux acc rest
else (
Hashtbl.add seen c ();
aux (Axis c :: acc) rest)
| Ellipsis :: rest -> aux (Ellipsis :: acc) rest
in
aux [] tokens
in
(tensor', deduped_tokens)
let expand_operand tensor tokens ell_rank =
let named_count = count_named tokens in
let ndim_tensor = ndim tensor in
let ell_count = ndim_tensor - named_count in
if ell_count < 0 then invalid_arg "operand rank too small for subscripts";
let ell_pad = ell_rank - ell_count in
if ell_pad < 0 then invalid_arg "ellipsis rank mismatch";
let shape_tensor = shape tensor in
let shape_idx = ref 0 in
let axis_pos = ref 0 in
let axis_labels_rev = ref [] in
let inserted_positions = ref [] in
List.iter
(function
| Axis c ->
if !shape_idx >= Array.length shape_tensor then
invalid_arg "subscripts rank mismatch";
incr shape_idx;
axis_labels_rev := Named c :: !axis_labels_rev;
incr axis_pos
| Ellipsis ->
let _ell_dims =
if ell_count = 0 then [||]
else Array.sub shape_tensor !shape_idx ell_count
in
shape_idx := !shape_idx + ell_count;
for idx = 0 to ell_rank - 1 do
axis_labels_rev := Ell idx :: !axis_labels_rev;
if idx < ell_pad then
inserted_positions := !axis_pos :: !inserted_positions;
incr axis_pos
done)
tokens;
if !shape_idx <> Array.length shape_tensor then
invalid_arg "operand tensor rank mismatch";
let axis_labels = List.rev !axis_labels_rev in
let insert_axes =
!inserted_positions |> List.sort compare |> Array.of_list
in
let tensor' =
if Array.length insert_axes = 0 then tensor
else unsqueeze ~axes:(Array.to_list insert_axes) tensor
in
(tensor', axis_labels)
let available_axis_chars =
let range a b =
let rec aux acc c =
if c < a then acc else aux (Char.chr c :: acc) (c - 1)
in
aux [] b
in
Array.of_list
(range (Char.code 'a') (Char.code 'z')
@ range (Char.code 'A') (Char.code 'Z')
@ range (Char.code '0') (Char.code '9')
@ [ '_'; '$'; '%'; '&'; '#'; '@'; '!'; '?'; ':'; ';'; '~'; '+'; '-' ])
let axis_char_mapping axes_lists output_axes =
let mapping = Hashtbl.create 32 in
let inverse = Hashtbl.create 32 in
let next = ref 0 in
let register axis =
if not (Hashtbl.mem mapping axis) then (
if !next >= Array.length available_axis_chars then
invalid_arg "too many distinct indices";
let c = available_axis_chars.(!next) in
incr next;
Hashtbl.add mapping axis c;
Hashtbl.add inverse c axis)
in
Array.iter (fun axes -> List.iter register (snd axes)) axes_lists;
List.iter register output_axes;
(mapping, inverse)
let string_of_axes mapping axes =
let len = List.length axes in
let bytes = Bytes.create len in
List.iteri
(fun idx axis ->
let c = Hashtbl.find mapping axis in
Bytes.set bytes idx c)
axes;
Bytes.unsafe_to_string bytes
type binary_result = {
left_axes : int array;
right_axes : int array;
left_free_axes : int array;
right_free_axes : int array;
shared_left_axes : int array;
shared_right_axes : int array;
noncontracted_left_axes : int array;
shape : int array;
vars : string;
}
let binary_einsum ~keep_axes ~left:(shape_a, str_a) ~right:(shape_b, str_b)
=
assert (all_distinct str_a);
assert (all_distinct str_b);
assert (String.length str_a = Array.length shape_a);
assert (String.length str_b = Array.length shape_b);
let kept_b_vars =
let map = Hashtbl.create (String.length str_b) in
StringLabels.iteri str_b ~f:(fun i char -> Hashtbl.add map char i);
map
in
let rev_var_shape = ref [] in
let contractions = ref [] in
let shared_left_rev = ref [] in
let shared_right_rev = ref [] in
let left_free_rev = ref [] in
let right_free_rev = ref [] in
let noncontracted_left_rev = ref [] in
StringLabels.iteri str_a ~f:(fun axis_a char ->
let dim_a = shape_a.(axis_a) in
match Hashtbl.find_opt kept_b_vars char with
| None ->
left_free_rev := axis_a :: !left_free_rev;
noncontracted_left_rev := axis_a :: !noncontracted_left_rev;
rev_var_shape := (dim_a, char) :: !rev_var_shape
| Some axis_b ->
let dim_b = shape_b.(axis_b) in
if dim_a <> dim_b then
invalid_arg
"index var '%c' must have consistent dimensions (%d on the \
left, %d on the right)"
char dim_a dim_b;
if CharSet.mem char keep_axes then (
shared_left_rev := axis_a :: !shared_left_rev;
shared_right_rev := axis_b :: !shared_right_rev;
noncontracted_left_rev := axis_a :: !noncontracted_left_rev;
rev_var_shape := (dim_a, char) :: !rev_var_shape;
Hashtbl.remove kept_b_vars char)
else (
contractions := (axis_a, axis_b) :: !contractions;
Hashtbl.remove kept_b_vars char));
StringLabels.iter str_b ~f:(fun char ->
match Hashtbl.find_opt kept_b_vars char with
| None -> ()
| Some axis_b ->
right_free_rev := axis_b :: !right_free_rev;
rev_var_shape := (shape_b.(axis_b), char) :: !rev_var_shape);
let left_axes, right_axes =
let as_, bs = List.split !contractions in
(Array.of_list as_, Array.of_list bs)
in
let left_free_axes = Array.of_list (List.rev !left_free_rev) in
let right_free_axes = Array.of_list (List.rev !right_free_rev) in
let shared_left_axes = Array.of_list (List.rev !shared_left_rev) in
let shared_right_axes = Array.of_list (List.rev !shared_right_rev) in
let noncontracted_left_axes =
Array.of_list (List.rev !noncontracted_left_rev)
in
let shape, vars =
let shape, vars = List.split @@ List.rev !rev_var_shape in
(Array.of_list shape, String.of_seq (List.to_seq vars))
in
assert (all_distinct vars);
{
left_axes;
right_axes;
left_free_axes;
right_free_axes;
shared_left_axes;
shared_right_axes;
noncontracted_left_axes;
shape;
vars;
}
type ('a, 'b) plan =
| Operand of ('a, 'b) t * string
| Contract of ('a, 'b) plan * ('a, 'b) plan * binary_result
let get_shape_vars = function
| Operand (x, str) -> (shape x, str)
| Contract (_, _, result) -> (result.shape, result.vars)
let add_to_plan ~keep_axes plan (op_b, str_b) =
let shape_a, str_a = get_shape_vars plan in
let result =
binary_einsum ~keep_axes ~left:(shape_a, str_a)
~right:(shape op_b, str_b)
in
Contract (plan, Operand (op_b, str_b), result)
let make_plan ~keep_axes vars_operands =
let len = Array.length vars_operands in
assert (len > 0);
let op, str = vars_operands.(0) in
let plan_so_far = ref (Operand (op, str)) in
for i = 1 to len - 1 do
plan_so_far := add_to_plan ~keep_axes !plan_so_far vars_operands.(i)
done;
!plan_so_far
let contract_pair op_a op_b result =
let {
left_axes;
right_axes;
left_free_axes;
right_free_axes;
shared_left_axes;
shared_right_axes;
noncontracted_left_axes;
shape = target_shape;
vars = _;
} =
result
in
let perm_left =
concat_arrays [ shared_left_axes; left_free_axes; left_axes ]
in
let perm_right =
concat_arrays [ shared_right_axes; right_axes; right_free_axes ]
in
let reorder_if_needed tensor perm =
if Array.length perm <= 1 || is_identity perm then tensor
else transpose ~axes:(Array.to_list perm) tensor
in
let op_a_perm = reorder_if_needed op_a perm_left |> contiguous in
let op_b_perm = reorder_if_needed op_b perm_right |> contiguous in
let shape_a = shape op_a_perm in
let shape_b = shape op_b_perm in
let batch_len = Array.length shared_left_axes in
let left_free_len = Array.length left_free_axes in
let right_free_len = Array.length right_free_axes in
let contract_len = Array.length left_axes in
let contract_len_right = Array.length right_axes in
if contract_len <> contract_len_right then
invalid_arg "einsum: internal contract axes mismatch";
if Array.length shared_right_axes <> batch_len then
invalid_arg "einsum: internal shared axes mismatch";
let batch_dims_left = slice shape_a 0 batch_len in
let left_only_dims = slice shape_a batch_len left_free_len in
let contract_dims_left =
slice shape_a (batch_len + left_free_len) contract_len
in
let batch_dims_right = slice shape_b 0 batch_len in
let contract_dims_right = slice shape_b batch_len contract_len_right in
let right_only_dims =
slice shape_b (batch_len + contract_len_right) right_free_len
in
if not (same_shape batch_dims_left batch_dims_right) then
invalid_arg "einsum: shared axes must have identical dimensions";
if not (same_shape contract_dims_left contract_dims_right) then
invalid_arg "einsum: contracted axes must have identical dimensions";
let left_m = product left_only_dims in
let left_k = product contract_dims_left in
let right_n = product right_only_dims in
let left_shape_mat =
concat_arrays [ batch_dims_left; [| left_m |]; [| left_k |] ]
in
let right_shape_mat =
concat_arrays [ batch_dims_right; [| left_k |]; [| right_n |] ]
in
let op_a_ready =
if same_shape (shape op_a_perm) left_shape_mat then op_a_perm
else reshape left_shape_mat op_a_perm
in
let op_b_ready =
if same_shape (shape op_b_perm) right_shape_mat then op_b_perm
else reshape right_shape_mat op_b_perm
in
let result_mat = matmul op_a_ready op_b_ready in
let preorder_shape =
concat_arrays [ batch_dims_left; left_only_dims; right_only_dims ]
in
let result_preorder =
if same_shape (shape result_mat) preorder_shape then result_mat
else reshape preorder_shape result_mat
in
let combined_left_axes =
concat_arrays [ shared_left_axes; left_free_axes ]
in
let total_left = Array.length combined_left_axes in
let total_right = Array.length right_free_axes in
let result_reordered =
if total_left <= 1 then result_preorder
else (
if Array.length noncontracted_left_axes <> total_left then
invalid_arg "einsum: left axis bookkeeping mismatch";
let map = Hashtbl.create total_left in
Array.iteri
(fun idx axis -> Hashtbl.replace map axis idx)
combined_left_axes;
let perm_left_reorder =
Array.map
(fun axis ->
match Hashtbl.find_opt map axis with
| Some idx -> idx
| None -> invalid_arg "einsum: missing axis while reordering")
noncontracted_left_axes
in
if is_identity perm_left_reorder then result_preorder
else
let total_dims = total_left + total_right in
let axes_perm =
Array.init total_dims (fun i ->
if i < total_left then perm_left_reorder.(i) else i)
in
transpose ~axes:(Array.to_list axes_perm) result_preorder)
in
let result_reordered = contiguous result_reordered in
if same_shape (shape result_reordered) target_shape then result_reordered
else reshape target_shape result_reordered
let rec eval_plan = function
| Operand (op, str) -> (op, str)
| Contract (a, b, result) ->
let op_a, _ = eval_plan a in
let op_b, _ = eval_plan b in
let tensor = contract_pair op_a op_b result in
(tensor, result.vars)
let calculate subscripts operands =
let operand_count = Array.length operands in
if operand_count = 0 then invalid_arg "no input operands";
let input_tokens, output_tokens_opt = parse_equation subscripts in
if Array.length input_tokens <> operand_count then
invalid_arg "number of inputs must equal number of operands";
let axis_occurrences = Hashtbl.create 32 in
Array.iter
(fun tokens ->
List.iter
(function
| Axis c ->
let count =
match Hashtbl.find_opt axis_occurrences c with
| Some n -> n + 1
| None -> 1
in
Hashtbl.replace axis_occurrences c count
| Ellipsis -> ())
tokens)
input_tokens;
let diag_results =
Array.mapi
(fun i tokens -> diagonalize_operand operands.(i) tokens)
input_tokens
in
let ell_rank =
Array.fold_left
(fun acc (tensor, tokens) ->
let ell_count = ndim tensor - count_named tokens in
if ell_count < 0 then
invalid_arg "operand rank too small for subscripts";
Stdlib.max acc ell_count)
0 diag_results
in
let output_has_ellipsis =
match output_tokens_opt with
| Some tokens ->
List.exists (function Ellipsis -> true | _ -> false) tokens
| None -> false
in
if output_has_ellipsis && ell_rank = 0 then
invalid_arg "output ellipsis requires ellipsis in inputs";
let expanded =
Array.map
(fun (tensor, tokens) -> expand_operand tensor tokens ell_rank)
diag_results
in
let axis_dims = Hashtbl.create 32 in
let update_axis_dim axis dim =
match Hashtbl.find_opt axis_dims axis with
| None -> Hashtbl.add axis_dims axis dim
| Some existing -> (
if existing = dim then ()
else if existing = 1 then Hashtbl.replace axis_dims axis dim
else if dim = 1 then ()
else
match axis with
| Named c ->
invalid_arg
"index var '%c' must have consistent dimensions (%d vs %d)"
c existing dim
| Ell idx ->
invalid_arg
"ellipsis dimension %d must have consistent dimensions (%d \
vs %d)"
idx existing dim)
in
Array.iter
(fun (tensor, axes) ->
let shape_tensor = shape tensor in
let rank = Array.length shape_tensor in
let axes_len = List.length axes in
if rank <> axes_len then invalid_arg "internal einsum shape mismatch";
List.iteri
(fun idx axis -> update_axis_dim axis shape_tensor.(idx))
axes)
expanded;
let broadcasted =
Array.map
(fun (tensor, axes) ->
let target_shape =
Array.of_list
(List.map (fun axis -> Hashtbl.find axis_dims axis) axes)
in
let tensor' =
let current_shape = shape tensor in
if same_shape current_shape target_shape then tensor
else broadcast_to target_shape tensor
in
(tensor', axes))
expanded
in
let output_axes =
match output_tokens_opt with
| Some tokens ->
let seen_named = Hashtbl.create 16 in
let ell_seen = ref false in
let acc_rev = ref [] in
List.iter
(function
| Axis c ->
if Hashtbl.mem seen_named c then
invalid_arg "output must have distinct indices";
Hashtbl.add seen_named c true;
if not (Hashtbl.mem axis_dims (Named c)) then
invalid_arg "output index '%c' not found in inputs" c;
acc_rev := Named c :: !acc_rev
| Ellipsis ->
if !ell_seen then invalid_arg "multiple ellipsis in output";
ell_seen := true;
if ell_rank = 0 then
invalid_arg "ellipsis not present in inputs";
let ell_axes = list_init ell_rank (fun idx -> Ell idx) in
List.iter (fun axis -> acc_rev := axis :: !acc_rev) ell_axes)
tokens;
List.rev !acc_rev
| None ->
let ell_axes =
if ell_rank = 0 then []
else list_init ell_rank (fun idx -> Ell idx)
in
let named_axes =
Hashtbl.fold
(fun c count acc ->
if count = 1 && Hashtbl.mem axis_dims (Named c) then
Named c :: acc
else acc)
axis_occurrences []
in
let named_axes_sorted =
List.sort
(fun axis1 axis2 ->
match (axis1, axis2) with
| Named c1, Named c2 -> Char.compare c1 c2
| _ -> 0)
named_axes
in
ell_axes @ named_axes_sorted
in
let mapping, inverse = axis_char_mapping broadcasted output_axes in
let keep_axes =
Hashtbl.fold
(fun c axis acc ->
match axis with
| Ell _ -> CharSet.add c acc
| Named name ->
let count =
match Hashtbl.find_opt axis_occurrences name with
| Some cnt -> cnt
| None -> 0
in
if
count > 1
&& List.exists
(function
| Named name' -> Char.equal name name' | Ell _ -> false)
output_axes
then CharSet.add c acc
else acc)
inverse CharSet.empty
in
let vars_operands =
Array.map
(fun (tensor, axes) -> (tensor, string_of_axes mapping axes))
broadcasted
in
let plan = make_plan ~keep_axes vars_operands in
let result_tensor, result_axes = eval_plan plan in
let output_str = string_of_axes mapping output_axes in
let axes_to_reduce =
let len = String.length result_axes in
let indices = ref [] in
for i = 0 to len - 1 do
let c = result_axes.[i] in
if not (string_contains output_str c) then indices := i :: !indices
done;
List.sort (fun a b -> compare b a) !indices
in
let result_tensor =
List.fold_left
(fun acc axis_idx -> sum ~axes:[ axis_idx ] acc)
result_tensor axes_to_reduce
in
let current_axes =
let buf = Buffer.create (String.length result_axes) in
String.iter
(fun c -> if string_contains output_str c then Buffer.add_char buf c)
result_axes;
Buffer.contents buf
in
let len_current = String.length current_axes in
if len_current <> String.length output_str then
invalid_arg "contracted input vars '%s' must match output vars '%s'"
current_axes output_str;
let axes_perm =
Array.init len_current (fun i ->
let c = current_axes.[i] in
try String.index output_str c
with Not_found ->
invalid_arg
"contracted input vars '%s' must match output vars '%s'"
current_axes output_str)
in
let need_transpose =
let len = Array.length axes_perm in
if len <= 1 then false
else
let rec check i =
if i = len then true
else if axes_perm.(i) = i then check (i + 1)
else false
in
not (check 0)
in
let result_tensor =
if need_transpose then
transpose ~axes:(Array.to_list axes_perm) result_tensor
else result_tensor
in
result_tensor
end
let einsum subscripts operands = Einsum.calculate subscripts operands
let kron a b =
let shape_a = shape a in
let shape_b = shape b in
let a_2d = if ndim a = 1 then reshape [| shape_a.(0); 1 |] a else a in
let b_2d = if ndim b = 1 then reshape [| shape_b.(0); 1 |] b else b in
let a_shape = shape a_2d in
let b_shape = shape b_2d in
let m_a = a_shape.(0) in
let n_a = if Array.length a_shape > 1 then a_shape.(1) else 1 in
let m_b = b_shape.(0) in
let n_b = if Array.length b_shape > 1 then b_shape.(1) else 1 in
let a_expanded = reshape [| m_a; 1; n_a; 1 |] a_2d in
let b_expanded = reshape [| 1; m_b; 1; n_b |] b_2d in
let result = mul a_expanded b_expanded in
let final_shape = [| m_a * m_b; n_a * n_b |] in
let result_flat = reshape final_shape result in
if ndim a = 1 && ndim b = 1 then flatten result_flat else result_flat
let multi_dot arrays =
match arrays with
| [||] -> invalid_arg "multi_dot: empty array"
| [| arr |] -> arr
| _ ->
let rec multiply_all = function
| [] -> failwith "unreachable"
| [ x ] -> x
| x :: xs -> matmul x (multiply_all xs)
in
multiply_all (Array.to_list arrays)
let cross ?axis a b =
let axis = Option.value axis ~default:(-1) in
let axis = if axis < 0 then ndim a + axis else axis in
let shape_a = shape a in
let shape_b = shape b in
if axis >= ndim a then
Error.invalid ~op:"cross" ~what:"axis" ~reason:"out of bounds" ();
if shape_a.(axis) <> 3 then invalid_arg "cross: axis dim not 3";
if shape_b.(axis) <> 3 then invalid_arg "cross: axis dim not 3";
let slice_at_index tensor ax idx =
let slices =
Array.init (ndim tensor) (fun i ->
if i = ax then R (idx, idx + 1) else A)
in
squeeze ~axes:[ ax ] (slice_internal (Array.to_list slices) tensor)
in
let a1 = slice_at_index a axis 0 in
let a2 = slice_at_index a axis 1 in
let a3 = slice_at_index a axis 2 in
let b1 = slice_at_index b axis 0 in
let b2 = slice_at_index b axis 1 in
let b3 = slice_at_index b axis 2 in
let c1 = sub (mul a2 b3) (mul a3 b2) in
let c2 = sub (mul a3 b1) (mul a1 b3) in
let c3 = sub (mul a1 b2) (mul a2 b1) in
stack ~axis [ c1; c2; c3 ]
let check_square ~op a =
let sh = shape a in
let n = Array.length sh in
if n < 2 then
Error.invalid ~op ~what:"input" ~reason:"requires at least 2D array" ();
if sh.(n - 1) <> sh.(n - 2) then
invalid_arg (Printf.sprintf "%s: coefficient matrix must be square" op)
let check_float_or_complex (type a b) ~op (a : (a, b) t) =
match dtype a with
| Float16 -> ()
| Float32 -> ()
| Float64 -> ()
| Complex32 -> ()
| Complex64 -> ()
| _ -> Error.invalid ~op ~what:"dtype" ~reason:"must be float or complex" ()
let check_real (type a b) ~op (a : (a, b) t) =
match dtype a with
| Float16 -> ()
| Float32 -> ()
| Float64 -> ()
| _ -> Error.invalid ~op ~what:"dtype" ~reason:"must be real (float)" ()
let cholesky ?upper a =
check_square ~op:"cholesky" a;
check_float_or_complex ~op:"cholesky" a;
let upper = Option.value upper ~default:false in
B.op_cholesky ~upper a
let qr ?mode a =
check_float_or_complex ~op:"qr" a;
let reduced =
match mode with Some `Reduced -> true | None | Some `Complete -> false
in
B.op_qr ~reduced a
let svd ?full_matrices a =
check_float_or_complex ~op:"svd" a;
let full_matrices = Option.value full_matrices ~default:false in
B.op_svd ~full_matrices a
let svdvals a =
check_float_or_complex ~op:"svdvals" a;
let _, s, _ = B.op_svd ~full_matrices:false a in
s
let eig a =
check_square ~op:"eig" a;
check_float_or_complex ~op:"eig" a;
match B.op_eig ~vectors:true a with
| vals, Some vecs -> (vals, vecs)
| _vals, None ->
Error.invalid ~op:"eig" ~what:"result" ~reason:"expected eigenvectors"
()
let eigh ?uplo a =
check_square ~op:"eigh" a;
check_real ~op:"eigh" a;
let _ = uplo in
match B.op_eigh ~vectors:true a with
| vals, Some vecs -> (vals, vecs)
| _vals, None ->
Error.invalid ~op:"eigh" ~what:"result" ~reason:"expected eigenvectors"
()
let eigvals a =
check_square ~op:"eigvals" a;
check_float_or_complex ~op:"eigvals" a;
let vals, _ = B.op_eig ~vectors:false a in
vals
let eigvalsh ?uplo a =
check_square ~op:"eigvalsh" a;
check_real ~op:"eigvalsh" a;
let _ = uplo in
let vals, _ = B.op_eigh ~vectors:false a in
vals
let norm (type a b) ?ord ?axes ?keepdims (x : (a, b) t) =
let keepdims = Option.value keepdims ~default:false in
match (ord, axes) with
| None, None ->
sqrt (sum (square (abs x)) ~keepdims)
| None, Some _ ->
sqrt (sum (square (abs x)) ?axes ~keepdims)
| Some `Fro, _ -> sqrt (sum (square (abs x)) ?axes ~keepdims)
| Some `One, None ->
max (sum (abs x) ~axes:[ ndim x - 2 ] ~keepdims) ~keepdims
| Some `NegOne, None ->
if ndim x = 1 then min (abs x) ~keepdims
else
let column_sums = sum (abs x) ~axes:[ ndim x - 2 ] in
min column_sums ~keepdims
| Some `Two, None ->
let s = svdvals x |> cast (dtype x) in
max s ~keepdims
| Some `NegTwo, None ->
let s = svdvals x |> cast (dtype x) in
min s ~keepdims
| Some `Inf, None ->
if ndim x = 1 then max (abs x) ~keepdims
else max (sum (abs x) ~axes:[ ndim x - 1 ] ~keepdims) ~keepdims
| Some `NegInf, None ->
if ndim x = 1 then min (abs x) ~keepdims
else
let row_sums = sum (abs x) ~axes:[ ndim x - 1 ] in
min row_sums ~keepdims
| Some `Nuc, None ->
if ndim x < 2 then
Error.invalid ~op:"norm" ~what:"input"
~reason:"nuclear norm defined for matrices" ()
else
let s = svdvals x |> cast (dtype x) in
sum s ~keepdims
| Some `NegOne, _ | Some `NegTwo, _ | Some `NegInf, _ | Some `Nuc, _ ->
Error.failed ~op:"norm"
~what:"this combination of ord and axis not implemented" ()
| Some (`P p), _ ->
if p = 1.0 && axes = None && ndim x = 2 then
max (sum (abs x) ~axes:[ ndim x - 2 ] ~keepdims) ~keepdims
else
let abs_x = abs x in
let p_val = Dtype.of_float (dtype x) p in
let p_tensor = full (B.context x) (dtype x) [||] p_val in
let pow_x = pow abs_x p_tensor in
let sum_pow = sum pow_x ?axes ~keepdims in
let one = Dtype.one (dtype x) in
let one_tensor = full (B.context x) (dtype x) [||] one in
let inv_p_tensor = div one_tensor p_tensor in
pow sum_pow inv_p_tensor
| _ ->
Error.failed ~op:"norm"
~what:"this combination of ord and axis not implemented" ()
let rec slogdet a =
check_square ~op:"slogdet" a;
check_float_or_complex ~op:"slogdet" a;
let dtype_a = dtype a in
let is_complex =
Dtype.equal dtype_a Dtype.complex32 || Dtype.equal dtype_a Dtype.complex64
in
let sh = shape a in
let rank = Array.length sh in
if (not is_complex) && sh.(rank - 1) = 2 && sh.(rank - 2) = 2 then
let prefix = List.init (Stdlib.max 0 (rank - 2)) (fun _ -> A) in
let a11 = slice_internal (prefix @ [ I 0; I 0 ]) a in
let a12 = slice_internal (prefix @ [ I 0; I 1 ]) a in
let a21 = slice_internal (prefix @ [ I 1; I 0 ]) a in
let a22 = slice_internal (prefix @ [ I 1; I 1 ]) a in
let det64 = sub (mul a11 a22) (mul a12 a21) |> cast Dtype.float64 in
let zero = zeros (B.context det64) Dtype.float64 (shape det64) in
let sign_pos = greater det64 zero in
let sign_neg = less det64 zero in
let sign_pos_f = cast Dtype.float32 (cast Dtype.float64 sign_pos) in
let sign_neg_f = cast Dtype.float32 (cast Dtype.float64 sign_neg) in
let sign_float = sub sign_pos_f sign_neg_f in
let abs_det = abs det64 in
let logdet64 =
let is_zero = cmpeq abs_det zero in
let neg_inf =
full (B.context det64) Dtype.float64 (shape det64) Float.neg_infinity
in
where is_zero neg_inf (log abs_det)
in
let logdet = cast Dtype.float32 logdet64 in
(sign_float, logdet)
else
let _q, r = B.op_qr ~reduced:false a in
let r_diag = diagonal r in
let signs = sign r_diag in
let sign_det =
if ndim signs > 1 then prod signs ~axes:[ -1 ] ~keepdims:false
else prod signs
in
let sign_float = cast Dtype.float32 (cast Dtype.float64 sign_det) in
let abs_diag = abs r_diag in
let abs_float64 = cast Dtype.float64 abs_diag in
let zero =
zeros (B.context abs_float64) Dtype.float64 (shape abs_float64)
in
let log_abs_diag =
let is_zero = cmpeq abs_float64 zero in
let neg_inf =
full (B.context abs_float64) Dtype.float64 (shape abs_float64)
Float.neg_infinity
in
where is_zero neg_inf (log abs_float64)
in
let logdet64 =
if ndim log_abs_diag > 1 then
sum log_abs_diag ~axes:[ -1 ] ~keepdims:false
else sum log_abs_diag
in
let logdet = cast Dtype.float32 logdet64 in
(sign_float, logdet)
and det a =
check_square ~op:"det" a;
check_float_or_complex ~op:"det" a;
let sign, logabs = slogdet a in
let dtype_a = dtype a in
let abs_det = exp logabs |> cast dtype_a in
let sign_cast = cast dtype_a sign in
mul sign_cast abs_det
let matrix_rank ?tol ?rtol ?hermitian a =
check_float_or_complex ~op:"matrix_rank" a;
let _ = hermitian in
let s = svdvals a in
let max_s = max s |> unsafe_get [] in
let m, n =
shape a |> fun sh -> (sh.(Array.length sh - 2), sh.(Array.length sh - 1))
in
let eps =
if Dtype.equal (dtype a) Dtype.float32 then 1.2e-7
else if Dtype.equal (dtype a) Dtype.float64 then 2.2e-16
else 1e-15
in
let tol =
match (tol, rtol) with
| Some t, _ -> t
| None, Some r -> r *. max_s
| None, None -> float_of_int (Stdlib.max m n) *. eps *. max_s
in
let mask = greater s (scalar (B.context a) (dtype s) tol) in
let mask = cast (dtype s) mask in
let count = sum mask |> unsafe_get [] in
int_of_float (Float.round count)
let trace ?offset a =
let offset = Option.value offset ~default:0 in
let sh = shape a in
let n = Array.length sh in
if n < 2 then
Error.invalid ~op:"trace" ~what:"input"
~reason:"requires at least 2D array" ();
let diag = diagonal ~offset a in
sum diag ~axes:[ -1 ] ~keepdims:false
let solve a b =
check_square ~op:"solve" a;
check_float_or_complex ~op:"solve" a;
check_float_or_complex ~op:"solve" b;
let a_ndim = ndim a in
let b_ndim = ndim b in
let b_expanded =
if a_ndim > 2 && b_ndim = 2 then
let a_shape = shape a in
let b_shape = shape b in
let a_batch_size =
Array.fold_left ( * ) 1 (Array.sub a_shape 0 (a_ndim - 2))
in
if b_shape.(0) = a_batch_size && b_shape.(1) = a_shape.(a_ndim - 2) then
expand_dims [ -1 ] b
else b
else b
in
let q, r = B.op_qr ~reduced:true a in
let r_diag = diagonal r |> cast Dtype.float64 in
let m = dim (-2) a in
let eps = if Dtype.equal (dtype a) Dtype.float32 then 1e-6 else 1e-12 in
let tol = eps *. float_of_int m in
let tol_tensor = full (B.context r_diag) Dtype.float64 (shape r_diag) tol in
let zero_mask = less (abs r_diag) tol_tensor in
let zero_count = sum (cast Dtype.float64 zero_mask) |> unsafe_get [] in
if zero_count > 0. then invalid_arg "solve: matrix is singular";
let y = matmul (matrix_transpose q) b_expanded in
let result =
B.op_triangular_solve ~upper:true ~transpose:false ~unit_diag:false r y
in
if b_expanded != b then squeeze ~axes:[ ndim result - 1 ] result else result
let lstsq ?rcond a b =
check_float_or_complex ~op:"lstsq" a;
check_float_or_complex ~op:"lstsq" b;
let _ = rcond in
let q, r = B.op_qr ~reduced:true a in
let y = matmul (matrix_transpose q) b in
let m, n =
shape a |> fun sh -> (sh.(Array.length sh - 2), sh.(Array.length sh - 1))
in
let x =
if m >= n then
let r_square =
if ndim r = 2 then slice_internal [ R (0, n); R (0, n) ] r
else slice_internal [ A; R (0, n); R (0, n) ] r
in
let y_top =
if ndim y = 2 then slice_internal [ R (0, n); A ] y
else if ndim y = 1 then slice_internal [ R (0, n) ] y
else slice_internal [ A; R (0, n); A ] y
in
B.op_triangular_solve ~upper:true ~transpose:false ~unit_diag:false
r_square y_top
else
Error.failed ~op:"lstsq" ~what:"underdetermined systems not implemented"
()
in
let residuals =
if m > n then
let res = sub b (matmul a x) in
sum (square res) ~axes:[ ndim res - 2 ] ~keepdims:false
else zeros (B.context a) (dtype b) [||]
in
let rank = matrix_rank a in
let s = svdvals a in
(x, residuals, rank, s)
let inv a =
check_square ~op:"inv" a;
check_float_or_complex ~op:"inv" a;
let sh = shape a in
let n = sh.(Array.length sh - 1) in
let batch_shape = Array.sub sh 0 (Array.length sh - 2) in
let eye_shape = Array.append batch_shape [| n; n |] in
let i = eye (B.context a) (dtype a) n in
let i = broadcast_to eye_shape i in
try solve a i
with Invalid_argument msg when String.sub msg 0 5 = "solve" ->
invalid_arg ("inv" ^ String.sub msg 5 (String.length msg - 5))
let matrix_power a n =
let shape_a = shape a in
let ndim_a = Array.length shape_a in
if ndim_a < 2 then
Error.invalid ~op:"matrix_power" ~what:"input"
~reason:"requires at least 2D array" ();
let m = shape_a.(ndim_a - 2) in
let k = shape_a.(ndim_a - 1) in
if m <> k then
Error.invalid ~op:"matrix_power" ~what:"matrix"
~reason:(Printf.sprintf "must be square, got %dx%d" m k)
();
if n = 0 then eye (B.context a) (dtype a) m
else if n = 1 then copy a
else if n > 0 then
let rec power acc base exp =
if exp = 0 then acc
else if exp mod 2 = 0 then power acc (matmul base base) (exp / 2)
else power (matmul acc base) (matmul base base) (exp / 2)
in
power a a (n - 1)
else
try
let inv_a = inv a in
let pos_n = -n in
if pos_n = 1 then inv_a
else
let rec power acc base exp =
if exp = 0 then acc
else if exp mod 2 = 0 then power acc (matmul base base) (exp / 2)
else power (matmul acc base) (matmul base base) (exp / 2)
in
power inv_a inv_a (pos_n - 1)
with Invalid_argument _ ->
invalid_arg "matrix_power: singular for negative exponent"
let cond ?p x =
check_square ~op:"cond" x;
check_float_or_complex ~op:"cond" x;
match p with
| None | Some `Two ->
let s = svdvals x in
let dtype_s = dtype s in
let max_s_tensor = max s in
let max_s = max_s_tensor |> unsafe_get [] in
let eps =
if Dtype.equal dtype_s Dtype.float32 then 1.2e-7
else if Dtype.equal dtype_s Dtype.float64 then 2.2e-16
else 1e-15
in
let tol = eps *. max_s in
let tol_tensor = scalar (B.context x) dtype_s tol in
let safe_s = where (greater s tol_tensor) s tol_tensor in
let min_s_tensor =
if ndim safe_s > 1 then min safe_s ~axes:[ -1 ] ~keepdims:false
else min safe_s
in
let ratio = div max_s_tensor min_s_tensor in
cast (dtype x) ratio
| Some `One ->
let inv_x = inv x in
let norm_x = norm ~ord:`One x in
let norm_inv = norm ~ord:`One inv_x in
mul norm_x norm_inv
| Some `Inf ->
let inv_x = inv x in
let norm_x = norm ~ord:`Inf x in
let norm_inv = norm ~ord:`Inf inv_x in
mul norm_x norm_inv
| _ -> Error.failed ~op:"cond" ~what:"unsupported norm" ()
let pinv (type a b) ?rtol:_ ?hermitian (a : (a, b) t) =
check_float_or_complex ~op:"pinv" a;
let _ = hermitian in
let u, s, vh = B.op_svd ~full_matrices:false a in
let cutoff =
let max_s = max s |> unsafe_get [] in
let m, n =
shape a |> fun sh -> (sh.(Array.length sh - 2), sh.(Array.length sh - 1))
in
let eps =
if Dtype.equal (dtype a) Dtype.float32 then 1.2e-7
else if Dtype.equal (dtype a) Dtype.float64 then 2.2e-16
else 1e-15
in
float_of_int (Stdlib.max m n) *. eps *. max_s
in
let ones_s = ones (B.context s) (dtype s) (shape s) in
let threshold = scalar (B.context a) (dtype s) cutoff in
let mask = greater s threshold in
let safe_s = where mask s ones_s in
let s_inv = div ones_s safe_s in
let mask = cast (dtype s) mask in
let s_inv = mul s_inv mask in
let s_inv = cast (dtype a) s_inv in
let s_inv_expanded = unsqueeze ~axes:[ 0 ] s_inv in
let vs = mul (matrix_transpose vh) s_inv_expanded in
matmul vs (matrix_transpose u)
let tensorsolve ?axes a b =
check_float_or_complex ~op:"tensorsolve" a;
check_float_or_complex ~op:"tensorsolve" b;
let a_shape = shape a in
let b_shape = shape b in
let a_rank = Array.length a_shape in
let b_rank = Array.length b_shape in
if b_rank = 0 then
Error.invalid ~op:"tensorsolve" ~what:"b"
~reason:"must have at least one dimension" ();
if a_rank < b_rank then
Error.invalid ~op:"tensorsolve" ~what:"a"
~reason:"rank must be >= rank of b" ();
let axes_for_b =
match axes with
| None -> Array.init b_rank (fun i -> a_rank - b_rank + i)
| Some axes ->
if List.length axes <> b_rank then
Error.invalid ~op:"tensorsolve" ~what:"axes"
~reason:
(Printf.sprintf "expected %d entries, got %d" b_rank
(List.length axes))
();
let ax_arr = Array.of_list axes in
let seen = Array.make a_rank false in
Array.map
(fun ax ->
let axis = if ax < 0 then ax + a_rank else ax in
if axis < 0 || axis >= a_rank then
Error.axis_out_of_bounds ~op:"tensorsolve" ~axis:ax ~ndim:a_rank
();
if seen.(axis) then
Error.invalid ~op:"tensorsolve"
~what:(Printf.sprintf "axis %d" ax)
~reason:"repeated" ();
seen.(axis) <- true;
axis)
ax_arr
in
let selected = Array.make a_rank false in
Array.iter (fun ax -> selected.(ax) <- true) axes_for_b;
let free_axes =
Array.init a_rank Fun.id |> Array.to_list
|> List.filter (fun ax -> not selected.(ax))
|> Array.of_list
in
let permutation = Array.append free_axes axes_for_b in
let a_perm =
let rec is_identity idx =
if idx = a_rank then true
else if permutation.(idx) <> idx then false
else is_identity (idx + 1)
in
if is_identity 0 then a else transpose ~axes:(Array.to_list permutation) a
in
let perm_shape = shape a_perm in
let free_rank = Array.length free_axes in
let free_shape = Array.sub perm_shape 0 free_rank in
let rhs_shape = Array.sub perm_shape free_rank b_rank in
if rhs_shape <> b_shape then
Error.shape_mismatch ~op:"tensorsolve" ~expected:b_shape ~actual:rhs_shape
();
let rows = array_prod free_shape in
let cols = array_prod rhs_shape in
if rows <> cols then
Error.invalid ~op:"tensorsolve" ~what:"a"
~reason:"leading dimensions must match trailing dimensions" ();
let a_mat = reshape [| rows; cols |] a_perm in
let b_vec = reshape [| rows |] b in
let solution =
try solve a_mat b_vec
with Invalid_argument _ ->
let pinv_a = pinv a_mat in
let b_col = reshape [| rows; 1 |] b_vec in
let x_col = matmul pinv_a b_col in
reshape [| cols |] x_col
in
reshape free_shape solution
let tensorinv ?ind a =
check_float_or_complex ~op:"tensorinv" a;
let shape_a = shape a in
let rank = Array.length shape_a in
if rank = 0 then
Error.invalid ~op:"tensorinv" ~what:"input"
~reason:"must have at least one dimension" ();
let ind = Option.value ind ~default:(rank / 2) in
if ind <= 0 || ind >= rank then
Error.invalid ~op:"tensorinv" ~what:"ind"
~reason:"must split dimensions into two non-empty groups" ();
let left_dims = Array.sub shape_a 0 ind in
let right_dims = Array.sub shape_a ind (rank - ind) in
let left_size = array_prod left_dims in
let right_size = array_prod right_dims in
if left_size <> right_size then
Error.invalid ~op:"tensorinv" ~what:"input"
~reason:"leading and trailing dimensions must have equal product" ();
let a_mat = reshape [| left_size; right_size |] a in
let inv_mat = try inv a_mat with Invalid_argument _ -> pinv a_mat in
let out_shape = Array.append right_dims left_dims in
reshape out_shape inv_mat
let complex (type a b) ~(real : (a, b) t) ~(imag : (a, b) t) =
let real_shape = shape real in
let imag_shape = shape imag in
if real_shape <> imag_shape then
Error.shape_mismatch ~op:"complex" ~expected:real_shape ~actual:imag_shape
();
let size = Array.fold_left ( * ) 1 real_shape in
match dtype real with
| Float32 ->
let real = (real : (float, float32_elt) t) in
let imag = (imag : (float, float32_elt) t) in
let complex_data =
Array.init size (fun i ->
let idx = Shape.unravel_index i real_shape |> Array.to_list in
let re = unsafe_get idx real in
let im = unsafe_get idx imag in
Complex.{ re; im })
in
Obj.magic (create (B.context real) complex32 real_shape complex_data)
| Float64 ->
let real = (real : (float, float64_elt) t) in
let imag = (imag : (float, float64_elt) t) in
let complex_data =
Array.init size (fun i ->
let idx = Shape.unravel_index i real_shape |> Array.to_list in
let re = unsafe_get idx real in
let im = unsafe_get idx imag in
Complex.{ re; im })
in
Obj.magic (create (B.context real) complex64 real_shape complex_data)
| _ ->
Error.invalid ~op:"complex" ~what:"dtype"
~reason:"real and imag must be float32 or float64" ()
let real (type a b) (x : (a, b) t) =
match dtype x with
| Complex32 ->
let x = (x : (Complex.t, complex32_elt) t) in
let shape_x = shape x in
let size = Array.fold_left ( * ) 1 shape_x in
let real_data =
Array.init size (fun i ->
let idx = Shape.unravel_index i shape_x |> Array.to_list in
let c = unsafe_get idx x in
c.Complex.re)
in
Obj.magic (create (B.context x) float32 shape_x real_data)
| Complex64 ->
let x = (x : (Complex.t, complex64_elt) t) in
let shape_x = shape x in
let size = Array.fold_left ( * ) 1 shape_x in
let real_data =
Array.init size (fun i ->
let idx = Shape.unravel_index i shape_x |> Array.to_list in
let c = unsafe_get idx x in
c.Complex.re)
in
Obj.magic (create (B.context x) float64 shape_x real_data)
| _ ->
Error.invalid ~op:"real" ~what:"dtype"
~reason:"input must be complex32 or complex64" ()
let imag (type a b) (x : (a, b) t) =
match dtype x with
| Complex32 ->
let x = (x : (Complex.t, complex32_elt) t) in
let shape_x = shape x in
let size = Array.fold_left ( * ) 1 shape_x in
let imag_data =
Array.init size (fun i ->
let idx = Shape.unravel_index i shape_x |> Array.to_list in
let c = unsafe_get idx x in
c.Complex.im)
in
Obj.magic (create (B.context x) float32 shape_x imag_data)
| Complex64 ->
let x = (x : (Complex.t, complex64_elt) t) in
let shape_x = shape x in
let size = Array.fold_left ( * ) 1 shape_x in
let imag_data =
Array.init size (fun i ->
let idx = Shape.unravel_index i shape_x |> Array.to_list in
let c = unsafe_get idx x in
c.Complex.im)
in
Obj.magic (create (B.context x) float64 shape_x imag_data)
| _ ->
Error.invalid ~op:"imag" ~what:"dtype"
~reason:"input must be complex32 or complex64" ()
type fft_norm = [ `Backward | `Forward | `Ortho ]
let pad_or_truncate_for_fft x axes s =
if s = None then x
else
let s_arr = Array.of_list (Option.get s) in
let x_padded = ref x in
List.iteri
(fun i ax ->
let ax = if ax < 0 then ndim !x_padded + ax else ax in
let cur_size = dim ax !x_padded in
let target = s_arr.(i) in
if target <> cur_size then
if target > cur_size then (
let pad_config = Array.make (ndim !x_padded) (0, 0) in
let pad_amount = target - cur_size in
pad_config.(ax) <- (0, pad_amount);
x_padded :=
B.op_pad !x_padded pad_config (Dtype.zero (dtype !x_padded)))
else
let shrink_config =
Array.init (ndim !x_padded) (fun idx ->
if idx = ax then (0, target) else (0, dim idx !x_padded))
in
x_padded := B.op_shrink !x_padded shrink_config)
axes;
!x_padded
let fftn (type a) ?axes ?s ?(norm = `Backward) (x : (Complex.t, a) t) :
(Complex.t, a) t =
let ndim_x = ndim x in
let axes_list =
match axes with
| None -> List.init ndim_x Fun.id
| Some a -> List.map (fun ax -> if ax < 0 then ndim_x + ax else ax) a
in
(match s with
| Some sizes when List.length sizes <> List.length axes_list ->
Error.invalid ~op:"fft" ~what:"s parameter"
~reason:"must have same length as axes" ()
| _ -> ());
let x_padded = pad_or_truncate_for_fft x axes_list s in
let norm_scale =
match norm with
| `Backward -> 1.0
| `Forward ->
let n =
List.fold_left (fun acc ax -> acc * dim ax x_padded) 1 axes_list
in
1.0 /. float_of_int n
| `Ortho ->
let n =
List.fold_left (fun acc ax -> acc * dim ax x_padded) 1 axes_list
in
1.0 /. Stdlib.sqrt (float_of_int n)
in
let result = B.op_fft x_padded ~axes:(Array.of_list axes_list) in
if norm_scale <> 1.0 then
let scale_value =
match B.dtype result with
| Complex32 | Complex64 | Complex16 ->
Complex.{ re = norm_scale; im = 0.0 }
in
let scale_tensor =
scalar (B.context result) (B.dtype result) scale_value
in
mul result scale_tensor
else result
let ifftn (type a) ?axes ?s ?(norm = `Backward) (x : (Complex.t, a) t) :
(Complex.t, a) t =
let ndim_x = ndim x in
let axes_list =
match axes with
| None -> List.init ndim_x Fun.id
| Some a -> List.map (fun ax -> if ax < 0 then ndim_x + ax else ax) a
in
(match s with
| Some sizes when List.length sizes <> List.length axes_list ->
Error.invalid ~op:"ifft" ~what:"s parameter"
~reason:"must have same length as axes" ()
| _ -> ());
let result_with_size =
match s with
| None ->
let norm_scale =
match norm with
| `Backward ->
let n =
List.fold_left (fun acc ax -> acc * dim ax x) 1 axes_list
in
1.0 /. float_of_int n
| `Forward -> 1.0
| `Ortho ->
let n =
List.fold_left (fun acc ax -> acc * dim ax x) 1 axes_list
in
1.0 /. Stdlib.sqrt (float_of_int n)
in
let result = B.op_ifft x ~axes:(Array.of_list axes_list) in
(result, norm_scale)
| Some sizes ->
let x_padded = pad_or_truncate_for_fft x axes_list s in
let norm_scale =
match norm with
| `Backward ->
let n = ref 1 in
List.iter (fun size -> n := !n * size) sizes;
1.0 /. float_of_int !n
| `Forward -> 1.0
| `Ortho ->
let n = ref 1 in
List.iter (fun size -> n := !n * size) sizes;
1.0 /. Stdlib.sqrt (float_of_int !n)
in
let result = B.op_ifft x_padded ~axes:(Array.of_list axes_list) in
(result, norm_scale)
in
let result, norm_scale = result_with_size in
let backend_scale = 1.0 in
let total_scale = backend_scale *. norm_scale in
if total_scale <> 1.0 then
let scale_value =
match B.dtype result with
| Complex32 | Complex64 | Complex16 ->
Complex.{ re = total_scale; im = 0.0 }
in
let scale_tensor =
scalar (B.context result) (B.dtype result) scale_value
in
mul result scale_tensor
else result
let rfftn ?axes ?s ?(norm = `Backward) x =
let ndim_x = ndim x in
let axes_list = match axes with None -> [ ndim_x - 1 ] | Some ax -> ax in
let x_padded = pad_or_truncate_for_fft x axes_list s in
let norm_scale =
match norm with
| `Backward -> 1.0
| `Forward ->
let n =
List.fold_left (fun acc ax -> acc * dim ax x_padded) 1 axes_list
in
1.0 /. float_of_int n
| `Ortho ->
let n =
List.fold_left (fun acc ax -> acc * dim ax x_padded) 1 axes_list
in
1.0 /. Stdlib.sqrt (float_of_int n)
in
let result =
B.op_rfft x_padded ~dtype:Dtype.Complex64 ~axes:(Array.of_list axes_list)
in
if norm_scale <> 1.0 then
let scale_value = Complex.{ re = norm_scale; im = 0.0 } in
let scale_tensor =
scalar (B.context result) (B.dtype result) scale_value
in
mul result scale_tensor
else result
let irfftn ?axes ?s ?(norm = `Backward) x =
let ndim_x = ndim x in
let axes_list = match axes with None -> [ ndim_x - 1 ] | Some ax -> ax in
let output_sizes =
match s with
| Some sizes -> sizes
| None ->
let input_shape = shape x in
List.mapi
(fun i axis ->
let axis = if axis < 0 then ndim_x + axis else axis in
if i = List.length axes_list - 1 then
(input_shape.(axis) - 1) * 2
else input_shape.(axis))
axes_list
in
let norm_sizes =
let input_shape = shape x in
List.mapi
(fun i axis ->
let axis = if axis < 0 then ndim_x + axis else axis in
if i = List.length axes_list - 1 then
match s with
| Some sizes ->
List.nth sizes i
| None ->
let inferred_size = (input_shape.(axis) - 1) * 2 in
inferred_size
else
match s with
| Some sizes -> List.nth sizes i
| None -> input_shape.(axis))
axes_list
in
let norm_scale =
match norm with
| `Backward ->
let n = List.fold_left (fun acc size -> acc * size) 1 norm_sizes in
1.0 /. float_of_int n
| `Forward -> 1.0
| `Ortho ->
let n = List.fold_left (fun acc size -> acc * size) 1 norm_sizes in
1.0 /. Stdlib.sqrt (float_of_int n)
in
let backend_scale = 1.0 in
let s_param =
match s with None -> None | Some _ -> Some (Array.of_list output_sizes)
in
let result =
B.op_irfft x ~dtype:Dtype.Float64 ~axes:(Array.of_list axes_list)
~s:s_param
in
let total_scale = backend_scale *. norm_scale in
if total_scale <> 1.0 then
let scale_tensor =
scalar (B.context result) (B.dtype result) total_scale
in
mul result scale_tensor
else result
let fft ?(axis = -1) ?n ?(norm = `Backward) x =
let n_param = match n with None -> None | Some size -> Some [ size ] in
fftn x ~axes:[ axis ] ?s:n_param ~norm
let ifft ?(axis = -1) ?n ?(norm = `Backward) x =
let n_param = match n with None -> None | Some size -> Some [ size ] in
ifftn x ~axes:[ axis ] ?s:n_param ~norm
let rfft ?(axis = -1) ?n ?(norm = `Backward) x =
let n_param = match n with None -> None | Some size -> Some [ size ] in
rfftn x ~axes:[ axis ] ?s:n_param ~norm
let irfft ?(axis = -1) ?n ?(norm = `Backward) x =
let n_param = match n with None -> None | Some size -> Some [ size ] in
irfftn x ~axes:[ axis ] ?s:n_param ~norm
let fft2 ?axes ?s ?(norm = `Backward) x =
let n = ndim x in
if n < 2 then
Error.invalid ~op:"fft2" ~what:"input"
~reason:(Printf.sprintf "requires at least 2D array, got %dD" n)
();
let axes_list =
match axes with None -> [ n - 2; n - 1 ] | Some ax -> ax
in
if List.length axes_list <> 2 then
Error.invalid ~op:"fft2" ~what:"axes"
~reason:"must specify exactly 2 axes" ();
fftn x ~axes:axes_list ?s ~norm
let ifft2 ?axes ?s ?(norm = `Backward) x =
let n = ndim x in
if n < 2 then
Error.invalid ~op:"ifft2" ~what:"input"
~reason:(Printf.sprintf "requires at least 2D array, got %dD" n)
();
let axes_list =
match axes with None -> [ n - 2; n - 1 ] | Some ax -> ax
in
if List.length axes_list <> 2 then
Error.invalid ~op:"ifft2" ~what:"axes"
~reason:"must specify exactly 2 axes" ();
ifftn x ~axes:axes_list ?s ~norm
let fftn ?axes ?s ?(norm = `Backward) x =
let axes_list =
match axes with None -> List.init (ndim x) Fun.id | Some ax -> ax
in
fftn x ~axes:axes_list ?s ~norm
let ifftn ?axes ?s ?(norm = `Backward) x =
let axes_list =
match axes with None -> List.init (ndim x) Fun.id | Some ax -> ax
in
ifftn x ~axes:axes_list ?s ~norm
let rfft2 ?axes ?s ?(norm = `Backward) x =
let n = ndim x in
if n < 2 then
Error.invalid ~op:"rfft2" ~what:"input"
~reason:(Printf.sprintf "requires at least 2D array, got %dD" n)
();
let axes_list =
match axes with None -> [ n - 2; n - 1 ] | Some ax -> ax
in
if List.length axes_list <> 2 then
Error.invalid ~op:"rfft2" ~what:"axes"
~reason:"must specify exactly 2 axes" ();
rfftn x ~axes:axes_list ?s ~norm
let irfft2 ?axes ?s ?(norm = `Backward) x =
let n = ndim x in
if n < 2 then
Error.invalid ~op:"irfft2" ~what:"input"
~reason:(Printf.sprintf "requires at least 2D array, got %dD" n)
();
let axes_list =
match axes with None -> [ n - 2; n - 1 ] | Some ax -> ax
in
if List.length axes_list <> 2 then
Error.invalid ~op:"irfft2" ~what:"axes"
~reason:"must specify exactly 2 axes" ();
irfftn x ~axes:axes_list ?s ~norm
let rfftn ?axes ?s ?(norm = `Backward) x =
let axes_list =
match axes with None -> List.init (ndim x) Fun.id | Some ax -> ax
in
rfftn x ~axes:axes_list ?s ~norm
let irfftn ?axes ?s ?(norm = `Backward) x =
let axes_list =
match axes with None -> List.init (ndim x) Fun.id | Some ax -> ax
in
irfftn x ~axes:axes_list ?s ~norm
let hfft ?(axis = -1) ?n ?norm x =
let n = match n with None -> 2 * (dim axis x - 1) | Some n -> n in
let axis = resolve_single_axis x axis in
irfftn x ~axes:[ axis ] ~s:[ n ] ?norm
let ihfft ?(axis = -1) ?n ?norm x =
let n = match n with None -> dim axis x | Some n -> n in
let axis = resolve_single_axis x axis in
rfftn x ~axes:[ axis ] ~s:[ n ] ?norm
let fftfreq ctx ?(d = 1.0) n =
let dtype = Dtype.float64 in
let val_ = 1.0 /. (float_of_int n *. d) in
let results =
if n mod 2 = 0 then
let p1 = arange ctx Dtype.int32 0 (n / 2) 1 in
let p2 = arange ctx Dtype.int32 (-(n / 2)) 0 1 in
concatenate ~axis:0 [ cast dtype p1; cast dtype p2 ]
else
let p1 = arange ctx Dtype.int32 0 ((n + 1) / 2) 1 in
let p2 = arange ctx Dtype.int32 (-((n - 1) / 2)) 0 1 in
concatenate ~axis:0 [ cast dtype p1; cast dtype p2 ]
in
mul_s results val_
let rfftfreq ctx ?(d = 1.0) n =
let dtype = Dtype.float64 in
let val_ = 1.0 /. (float_of_int n *. d) in
let results = arange ctx Dtype.int32 0 ((n / 2) + 1) 1 in
let scale_tensor = scalar ctx dtype val_ in
mul (cast dtype results) scale_tensor
let fftshift ?axes x =
let shape_x = shape x in
let ndim_x = Array.length shape_x in
let axes_list =
match axes with None -> List.init ndim_x Fun.id | Some ax -> ax
in
List.fold_left
(fun acc axis ->
let axis = resolve_single_axis acc axis in
let n = shape_x.(axis) in
let shift = n / 2 in
roll shift acc ~axis)
x axes_list
let ifftshift ?axes x =
let shape_x = shape x in
let ndim_x = Array.length shape_x in
let axes_list =
match axes with None -> List.init ndim_x Fun.id | Some ax -> ax
in
List.fold_left
(fun acc axis ->
let axis = resolve_single_axis acc axis in
let n = shape_x.(axis) in
let shift = -(n / 2) in
roll shift acc ~axis)
x axes_list
let relu6 x =
let zero = scalar_like x 0.0 in
let six = scalar_like x 6.0 in
let max_x = maximum x zero in
minimum max_x six
let hard_sigmoid ?(alpha = 1.0 /. 6.0) ?(beta = 0.5) x =
let dt = dtype x in
let alpha_x = B.op_const_scalar (B.context x) alpha dt in
let beta_x = B.op_const_scalar (B.context x) beta dt in
let one_x = B.op_const_scalar (B.context x) 1.0 dt in
let term1_arg = add (mul alpha_x x) beta_x in
let term1 = relu term1_arg in
let term2_arg = sub term1_arg one_x in
let term2 = relu term2_arg in
sub term1 term2
let softplus x =
let one = scalar_like x 1. in
let exp_x = exp x in
let sum = add one exp_x in
log sum
let silu x =
let sig_x = sigmoid x in
mul x sig_x
let hard_silu x =
let y = hard_sigmoid x in
mul x y
let log_sigmoid x =
let zero = scalar_like x 0.0 in
let one = scalar_like x 1.0 in
let is_positive = greater x zero in
let neg_x = neg x in
let exp_neg_x = exp neg_x in
let branch1 = neg (log (add one exp_neg_x)) in
let exp_x = exp x in
let branch2 = sub x (log (add one exp_x)) in
where is_positive branch1 branch2
let leaky_relu ?(negative_slope = 0.01) x =
let slope = scalar_like x negative_slope in
let slope_x = mul slope x in
maximum x slope_x
let hard_tanh x =
let one = scalar_like x 1. in
let neg_one = scalar_like x (-1.0) in
let min_x = minimum x one in
maximum neg_one min_x
let elu ?(alpha = 1.0) x =
let zero = scalar_like x 0.0 in
let one = scalar_like x 1. in
let alpha_scalar = scalar_like x alpha in
let exp_x = exp x in
let exp_minus_one = sub exp_x one in
let min_part = minimum zero exp_minus_one in
let alpha_min = mul alpha_scalar min_part in
let max_x = maximum x zero in
add max_x alpha_min
let selu x =
let alpha = 1.6732632423543772848170429916717 in
let lambda = 1.0507009873554804934193349852946 in
let elu_x = elu ~alpha x in
let lambda_scalar = scalar_like x lambda in
mul lambda_scalar elu_x
let softmax ?(axes = [ -1 ]) x =
let ndim = Array.length (shape x) in
let axes_normalized =
List.map (fun ax -> if ax < 0 then ndim + ax else ax) axes
in
let max_x = max x ~axes:axes_normalized ~keepdims:true in
let x_shifted = sub x max_x in
let exp_x = exp x_shifted in
let sum_exp = sum exp_x ~axes:axes_normalized ~keepdims:true in
div exp_x sum_exp
let gelu_approx x =
let one = scalar_like x 1.0 in
let half = scalar_like x 0.5 in
let sqrt2_pi = scalar_like x 0.7978845608 in
let coeff = scalar_like x 0.044715 in
let x2 = mul x x in
let inner = add one (mul coeff x2) in
let arg = mul (mul x sqrt2_pi) inner in
let y = tanh arg in
mul half (mul x (add one y))
let erf x =
let p = scalar_like x 0.3275911 in
let a1 = scalar_like x 0.254829592 in
let a2 = scalar_like x (-0.284496736) in
let a3 = scalar_like x 1.421413741 in
let a4 = scalar_like x (-1.453152027) in
let a5 = scalar_like x 1.061405429 in
let sign_x = sign x in
let abs_x = abs x in
let one = scalar_like x 1.0 in
let t = div one (add one (mul p abs_x)) in
let t2 = mul t t in
let t3 = mul t2 t in
let t4 = mul t3 t in
let t5 = mul t4 t in
let poly = add (mul a1 t) (mul a2 t2) in
let poly = add poly (mul a3 t3) in
let poly = add poly (mul a4 t4) in
let poly = add poly (mul a5 t5) in
let x2 = mul x x in
let exp_neg_x2 = exp (neg x2) in
let result = sub one (mul exp_neg_x2 poly) in
mul sign_x result
let gelu x =
let half = scalar_like x 0.5 in
let one = scalar_like x 1.0 in
let sqrt2 = scalar_like x 1.4142135623730951 in
let x_over_sqrt2 = div x sqrt2 in
let erf_val = erf x_over_sqrt2 in
mul (mul half x) (add one erf_val)
let softsign x =
let one = scalar_like x 1.0 in
let abs_x = maximum x (neg x) in
div x (add one abs_x)
let mish x =
let arg = softplus x in
let y = tanh arg in
mul x y
let im2col ~kernel_size ~stride ~dilation ~padding x =
B.op_unfold x ~kernel_size ~stride ~dilation ~padding
let col2im ~output_size ~kernel_size ~stride ~dilation ~padding x =
B.op_fold x ~output_size ~kernel_size ~stride ~dilation ~padding
let calculate_padding_for_mode input_spatial_shape ~k_s ~s_s ~d_s
~(mode : [< `Full | `Valid | `Same ])
~(op_type : [ `Convolution | `Correlation ]) =
let num_spatial = Array.length input_spatial_shape in
if
not
(Array.length k_s = num_spatial
&& Array.length s_s = num_spatial
&& Array.length d_s = num_spatial)
then
Error.invalid ~op:"calculate_padding_for_mode" ~what:"array lengths"
~reason:"shape/kernel/stride/dilation must have same length" ();
match mode with
| `Valid -> Array.make num_spatial (0, 0)
| `Full ->
Array.init num_spatial (fun i ->
let pad_each_side = d_s.(i) * (k_s.(i) - 1) in
(pad_each_side, pad_each_side))
| `Same ->
Array.init num_spatial (fun i ->
let is_d, ss_d, ks_d, ds_d =
(input_spatial_shape.(i), s_s.(i), k_s.(i), d_s.(i))
in
let os_d = ceildiv is_d ss_d in
let eff_ks_d = (ds_d * (ks_d - 1)) + 1 in
let total_pad_d =
Stdlib.max 0 (((os_d - 1) * ss_d) + eff_ks_d - is_d)
in
let pad_before, pad_after =
if
ks_d mod 2 = 0
&& total_pad_d mod 2 = 1
&& op_type = `Convolution
then
((total_pad_d / 2) + 1, total_pad_d / 2)
else
(total_pad_d / 2, total_pad_d - (total_pad_d / 2))
in
(pad_before, pad_after))
let correlate_nd_general ~groups stride_s_arr ~padding_mode dilation_s_arr
?fillvalue:_ num_spatial_dims ?bias ~op_type x w =
if ndim w <> num_spatial_dims + 2 then
Error.invalid ~op:"correlate_nd" ~what:"weight tensor"
~reason:(Printf.sprintf "must be %dD" (num_spatial_dims + 2))
();
if ndim x <> num_spatial_dims + 2 then
Error.invalid ~op:"correlate_nd" ~what:"input tensor"
~reason:(Printf.sprintf "must be %dD" (num_spatial_dims + 2))
();
if Array.length stride_s_arr <> num_spatial_dims then
Error.invalid ~op:"correlate_nd" ~what:"stride_s_arr length"
~reason:"mismatch with num_spatial_dims" ();
if Array.length dilation_s_arr <> num_spatial_dims then
Error.invalid ~op:"correlate_nd" ~what:"dilation_s_arr length"
~reason:"mismatch with num_spatial_dims" ();
let bs = dim 0 x in
let cin_total = dim 1 x in
let input_spatial_shape_arr =
Array.init num_spatial_dims (fun i -> dim (i + 2) x)
in
let cout = dim 0 w in
let cin_per_group = dim 1 w in
let kernel_spatial_shape_arr =
Array.init num_spatial_dims (fun i -> dim (i + 2) w)
in
if Array.exists (fun d -> d = 0) input_spatial_shape_arr then
let empty_spatial = Array.make num_spatial_dims 0 in
let empty_shape = Array.concat [ [| bs; cout |]; empty_spatial ] in
empty (B.context x) (dtype x) empty_shape
else (
if cin_total <> groups * cin_per_group then
Error.invalid ~op:"correlate_nd"
~what:(Printf.sprintf "channel configuration")
~reason:(Printf.sprintf "%d ≠ %d×%d" cin_total groups cin_per_group)
~hint:
(Printf.sprintf
"expected %d channels for %d groups with %d channels each"
(groups * cin_per_group) groups cin_per_group)
();
let rcout = cout / groups in
if groups * rcout <> cout then
Error.invalid ~op:"correlate_nd"
~what:(Printf.sprintf "cout %d" cout)
~reason:(Printf.sprintf "%d %% %d ≠ 0" cout groups)
~hint:
(Printf.sprintf
"expected %d channels for %d groups with %d channels each" cout
groups rcout)
();
let padding_config_pairs_arr =
calculate_padding_for_mode input_spatial_shape_arr
~k_s:kernel_spatial_shape_arr ~s_s:stride_s_arr ~d_s:dilation_s_arr
~mode:padding_mode ~op_type
in
let x_col =
B.op_unfold x ~kernel_size:kernel_spatial_shape_arr ~stride:stride_s_arr
~dilation:dilation_s_arr ~padding:padding_config_pairs_arr
in
let x_col_shape = shape x_col in
let num_blocks = x_col_shape.(2) in
let output_spatial_shape_arr =
if num_spatial_dims = 1 then [| num_blocks |]
else if num_spatial_dims = 2 then
let padded_h =
input_spatial_shape_arr.(0)
+ fst padding_config_pairs_arr.(0)
+ snd padding_config_pairs_arr.(0)
in
let padded_w =
input_spatial_shape_arr.(1)
+ fst padding_config_pairs_arr.(1)
+ snd padding_config_pairs_arr.(1)
in
let effective_kh =
((kernel_spatial_shape_arr.(0) - 1) * dilation_s_arr.(0)) + 1
in
let effective_kw =
((kernel_spatial_shape_arr.(1) - 1) * dilation_s_arr.(1)) + 1
in
let out_h = ((padded_h - effective_kh) / stride_s_arr.(0)) + 1 in
let out_w = ((padded_w - effective_kw) / stride_s_arr.(1)) + 1 in
[| out_h; out_w |]
else
let padded_spatial =
Array.init num_spatial_dims (fun i ->
input_spatial_shape_arr.(i)
+ fst padding_config_pairs_arr.(i)
+ snd padding_config_pairs_arr.(i))
in
Array.init num_spatial_dims (fun i ->
let effective_kernel =
((kernel_spatial_shape_arr.(i) - 1) * dilation_s_arr.(i)) + 1
in
((padded_spatial.(i) - effective_kernel) / stride_s_arr.(i)) + 1)
in
let kernel_elements = Array.fold_left ( * ) 1 kernel_spatial_shape_arr in
let result =
if groups = 1 then
let w_cont = B.op_contiguous w in
let w_reshaped =
reshape [| cout; cin_total * kernel_elements |] w_cont
in
matmul w_reshaped x_col
else
let x_col_grouped =
reshape
[| bs; groups; cin_per_group * kernel_elements; num_blocks |]
x_col
in
let w_cont = B.op_contiguous w in
let w_grouped =
reshape [| groups; rcout; cin_per_group * kernel_elements |] w_cont
in
let x_col_batched =
reshape
[| bs * groups; cin_per_group * kernel_elements; num_blocks |]
x_col_grouped
in
let w_batched =
reshape
[| groups; rcout; cin_per_group * kernel_elements |]
w_grouped
in
let w_expanded = unsqueeze ~axes:[ 0 ] w_batched in
let w_expanded =
expand
[| bs; groups; rcout; cin_per_group * kernel_elements |]
w_expanded
in
let w_expanded =
reshape
[| bs * groups; rcout; cin_per_group * kernel_elements |]
w_expanded
in
let result_batched = matmul w_expanded x_col_batched in
let result_grouped =
reshape [| bs; groups; rcout; num_blocks |] result_batched
in
reshape [| bs; cout; num_blocks |] result_grouped
in
let final_shape =
Array.concat [ [| bs; cout |]; output_spatial_shape_arr ]
in
let result_reshaped = reshape final_shape result in
let result_corrected = result_reshaped in
match bias with
| None -> result_corrected
| Some b ->
let bias_shape =
Array.concat [ [| 1; cout |]; Array.make num_spatial_dims 1 ]
in
let bias_reshaped = reshape bias_shape b in
add result_corrected bias_reshaped)
let correlate_nd ?(groups = 1) stride_s_arr
?(padding_mode : [ `Full | `Valid | `Same ] = `Valid) dilation_s_arr
?fillvalue num_spatial_dims ?bias x w =
correlate_nd_general ~groups stride_s_arr ~padding_mode dilation_s_arr
?fillvalue num_spatial_dims ?bias ~op_type:`Correlation x w
(** Correlate1D (cross-correlation). x: input tensor (bs, cin_total, iw) w:
weight tensor (cout, cin_per_group, kw) bias: optional bias tensor (cout)
stride, dilation: integers for the spatial dimension. padding_mode:
[ `Full | `Valid | `Same ] fillvalue: optional scalar to fill padding.
Defaults to 0 of x's dtype. *)
let correlate1d ?groups ?(stride = 1) ?padding_mode ?(dilation = 1) ?fillvalue
?bias x w =
correlate_nd ?groups [| stride |] ?padding_mode [| dilation |] ?fillvalue 1
?bias x w
(** Correlate2D (cross-correlation). x: input tensor (bs, cin_total, ih, iw)
w: weight tensor (cout, cin_per_group, kh, kw) bias: optional bias tensor
(cout) stride, dilation: (int*int) tuples for (h,w) spatial dimensions.
padding_mode: [ `Full | `Valid | `Same ] fillvalue: optional scalar to
fill padding. Defaults to 0 of x's dtype. *)
let correlate2d ?groups ?(stride = (1, 1)) ?padding_mode ?(dilation = (1, 1))
?fillvalue ?bias x w =
correlate_nd ?groups (pair_to_array stride) ?padding_mode
(pair_to_array dilation) ?fillvalue 2 ?bias x w
(** ConvolveND - Generic N-Dimensional version. This flips the kernel
(weights) along all its spatial dimensions then calls correlate_nd. *)
let convolve_nd ?groups stride_s_arr ?padding_mode dilation_s_arr ?fillvalue
num_spatial_dims ?bias x w =
let w_ndim = ndim w in
if w_ndim < num_spatial_dims + 2 then
Error.invalid ~op:"convolve_nd" ~what:"weight tensor"
~reason:
(Printf.sprintf "needs at least %d dims for spatial flipping"
(num_spatial_dims + 2))
();
let flip_axes_bools = Array.make w_ndim false in
for i = 0 to num_spatial_dims - 1 do
flip_axes_bools.(2 + i) <- true
done;
let w_flipped = B.op_flip w flip_axes_bools in
let groups = Option.value groups ~default:1 in
let padding_mode = Option.value padding_mode ~default:`Valid in
correlate_nd_general ~groups stride_s_arr ~padding_mode dilation_s_arr
?fillvalue num_spatial_dims ?bias ~op_type:`Convolution x w_flipped
(** Convolve1D. x: input tensor (bs, cin_total, iw) w: weight tensor (cout,
cin_per_group, kw) *)
let convolve1d ?groups ?(stride = 1) ?padding_mode ?(dilation = 1) ?fillvalue
?bias x w =
convolve_nd ?groups [| stride |] ?padding_mode [| dilation |] ?fillvalue 1
?bias x w
(** Convolve2D. x: input tensor (bs, cin_total, ih, iw) w: weight tensor
(cout, cin_per_group, kh, kw) *)
let convolve2d ?groups ?(stride = (1, 1)) ?padding_mode ?(dilation = (1, 1))
?fillvalue ?bias x w =
convolve_nd ?groups (pair_to_array stride) ?padding_mode
(pair_to_array dilation) ?fillvalue 2 ?bias x w
(** Helper to resolve padding specification for pooling/convolution
operations. Input `padding_spec` is user-facing. Output `(int*int) array`
is for `B.op_pad`, (pad_before, pad_after) for each spatial dimension. *)
let resolve_padding_for_ops padding_spec ~input_spatial_shape ~k_s ~s_s ~d_s
~op_type =
match padding_spec with
| `Same | `Valid | `Full ->
calculate_padding_for_mode input_spatial_shape ~k_s ~s_s ~d_s
~mode:padding_spec ~op_type
(** Helper to adjust padding for ceil_mode=true. Analogous to tinygrad's
_apply_ceil_mode. Input `current_pads_pairs` is (pad_before, pad_after)
for each spatial dim. Output is new (pad_before, pad_after) array for each
spatial dim. *)
let apply_ceil_mode ~current_pads_pairs ~input_spatial_shape ~k_s ~s_s ~d_s =
let num_spatial_dims = Array.length k_s in
let pads_adj = Array.copy current_pads_pairs in
let o_s =
Array.init num_spatial_dims (fun i ->
let i_d = input_spatial_shape.(i) in
let d_d = d_s.(i) in
let k_d = k_s.(i) in
let s_d = s_s.(i) in
let p_b, p_a = current_pads_pairs.(i) in
ceildiv (i_d + p_b + p_a - ((d_d * (k_d - 1)) + 1)) s_d + 1)
in
for i = 0 to num_spatial_dims - 1 do
let o_d, i_d, s_d, k_d, d_d =
(o_s.(i), input_spatial_shape.(i), s_s.(i), k_s.(i), d_s.(i))
in
let p_b, p_a = current_pads_pairs.(i) in
let pad_needed_for_last_window_start =
(s_d * (o_d - 1)) + ((d_d * (k_d - 1)) + 1) - (i_d + p_b + p_a)
in
let effective_pad_before_input_start =
Stdlib.max 0 ((s_d * (o_d - 1)) - (p_b + i_d - 1))
in
pads_adj.(i) <-
( fst pads_adj.(i),
snd pads_adj.(i)
+ pad_needed_for_last_window_start - effective_pad_before_input_start
)
done;
pads_adj
let pool_setup ~num_spatial_dims ~kernel_size ?stride ?dilation ~padding_spec
~ceil_mode x =
let x_ndim = ndim x in
let input_spatial_shape =
Array.sub (shape x) (x_ndim - num_spatial_dims) num_spatial_dims
in
let s_s = Option.value stride ~default:kernel_size in
let d_s = Option.value dilation ~default:(Array.make num_spatial_dims 1) in
let reg_pads =
resolve_padding_for_ops padding_spec ~input_spatial_shape ~k_s:kernel_size
~s_s ~d_s ~op_type:`Convolution
in
let pads =
if ceil_mode then
apply_ceil_mode ~current_pads_pairs:reg_pads ~input_spatial_shape
~k_s:kernel_size ~s_s ~d_s
else reg_pads
in
let full_pad_config =
Array.concat [ Array.make (x_ndim - num_spatial_dims) (0, 0); pads ]
in
(input_spatial_shape, s_s, d_s, pads, reg_pads, full_pad_config)
let avg_pool_nd ~kernel_size ?stride ?dilation ~padding_spec ~ceil_mode
~count_include_pad ~num_spatial_dims x =
let x_ndim = ndim x in
let ( _input_spatial_shape,
s_s,
d_s,
_current_pads_pairs,
_reg_pads_pairs,
full_pad_config ) =
pool_setup ~num_spatial_dims ~kernel_size ?stride ?dilation ~padding_spec
~ceil_mode x
in
let padding_pairs =
Array.sub full_pad_config (x_ndim - num_spatial_dims) num_spatial_dims
in
let x_unfolded =
B.op_unfold x ~kernel_size ~stride:s_s ~dilation:d_s
~padding:padding_pairs
in
let prefix_shape = Array.sub (shape x) 0 (x_ndim - num_spatial_dims) in
let padded_spatial =
Array.init num_spatial_dims (fun i ->
(shape x).(x_ndim - num_spatial_dims + i)
+ fst padding_pairs.(i)
+ snd padding_pairs.(i))
in
let output_spatial =
Array.init num_spatial_dims (fun i ->
let effective_kernel = ((kernel_size.(i) - 1) * d_s.(i)) + 1 in
((padded_spatial.(i) - effective_kernel) / s_s.(i)) + 1)
in
let channels =
if x_ndim - num_spatial_dims >= 1 then (
let ch_prod = ref 1 in
for i = 1 to x_ndim - num_spatial_dims - 1 do
ch_prod := !ch_prod * (shape x).(i)
done;
!ch_prod)
else 1
in
let kernel_elements = array_prod kernel_size in
let num_blocks = (shape x_unfolded).(Array.length (shape x_unfolded) - 1) in
let batch_size =
if Array.length prefix_shape >= 1 then prefix_shape.(0) else 1
in
let x_reshaped =
reshape [| batch_size; channels; kernel_elements; num_blocks |] x_unfolded
in
let sum_pooled =
sum x_reshaped ~axes:[ Array.length (shape x_reshaped) - 2 ]
in
let result_shape = Array.concat [ prefix_shape; output_spatial ] in
let sum_reshaped = reshape result_shape sum_pooled in
let sum_corrected = sum_reshaped in
if count_include_pad && not ceil_mode then
let kernel_numel = float_of_int kernel_elements in
div_s sum_corrected kernel_numel
else
let ones = ones_like x in
let ones_unfolded =
B.op_unfold ones ~kernel_size ~stride:s_s ~dilation:d_s
~padding:padding_pairs
in
let ones_reshaped =
reshape
(Array.concat
[ prefix_shape; [| channels; kernel_elements; num_blocks |] ])
ones_unfolded
in
let count =
sum ones_reshaped ~axes:[ Array.length (shape ones_reshaped) - 2 ]
in
let count_reshaped = reshape result_shape count in
let count_corrected =
if num_spatial_dims = 2 then
transpose
~axes:
(Array.to_list
(Array.init x_ndim (fun i ->
if i = x_ndim - 2 then x_ndim - 1
else if i = x_ndim - 1 then x_ndim - 2
else i)))
count_reshaped
else count_reshaped
in
div sum_corrected count_corrected
let max_pool_nd ~kernel_size ?stride ?dilation ~padding_spec ~ceil_mode
~return_indices ~num_spatial_dims x =
let x_ndim = ndim x in
let input_spatial_shape =
Array.sub (shape x) (x_ndim - num_spatial_dims) num_spatial_dims
in
if Array.exists (fun d -> d = 0) input_spatial_shape then
let empty_output = empty (B.context x) (dtype x) (shape x) in
if return_indices then
let empty_indices = empty (B.context x) Dtype.int32 (shape x) in
(empty_output, Some empty_indices)
else (empty_output, None)
else
let ( _input_spatial_shape,
s_s,
d_s,
_current_pads_pairs,
_,
full_pad_config ) =
pool_setup ~num_spatial_dims ~kernel_size ?stride ?dilation
~padding_spec ~ceil_mode x
in
let padding_pairs =
Array.sub full_pad_config (x_ndim - num_spatial_dims) num_spatial_dims
in
let x_unfolded =
B.op_unfold x ~kernel_size ~stride:s_s ~dilation:d_s
~padding:padding_pairs
in
let prefix_shape = Array.sub (shape x) 0 (x_ndim - num_spatial_dims) in
let padded_spatial =
Array.init num_spatial_dims (fun i ->
(shape x).(x_ndim - num_spatial_dims + i)
+ fst padding_pairs.(i)
+ snd padding_pairs.(i))
in
let output_spatial =
Array.init num_spatial_dims (fun i ->
let effective_kernel = ((kernel_size.(i) - 1) * d_s.(i)) + 1 in
((padded_spatial.(i) - effective_kernel) / s_s.(i)) + 1)
in
let channels =
if x_ndim - num_spatial_dims >= 1 then (
let ch_prod = ref 1 in
for i = 1 to x_ndim - num_spatial_dims - 1 do
ch_prod := !ch_prod * (shape x).(i)
done;
!ch_prod)
else 1
in
let kernel_elements = array_prod kernel_size in
let num_blocks =
(shape x_unfolded).(Array.length (shape x_unfolded) - 1)
in
let batch_size =
if Array.length prefix_shape >= 1 then prefix_shape.(0) else 1
in
let x_reshaped =
reshape
[| batch_size; channels; kernel_elements; num_blocks |]
x_unfolded
in
let max_pooled =
B.op_reduce_max x_reshaped
~axes:[| Array.length (shape x_reshaped) - 2 |]
~keepdims:false
in
let result_shape = Array.concat [ prefix_shape; output_spatial ] in
let max_values = reshape result_shape max_pooled in
let max_values_corrected = max_values in
if not return_indices then (max_values_corrected, None)
else
let kernel_indices =
arange (B.context x) Dtype.int32 0 kernel_elements 1
in
let kernel_indices_reshaped =
reshape [| 1; 1; kernel_elements; 1 |] kernel_indices
in
let kernel_indices_broadcast =
broadcast_to (shape x_reshaped) kernel_indices_reshaped
in
let max_expanded =
unsqueeze ~axes:[ Array.length (shape x_reshaped) - 2 ] max_pooled
in
let max_broadcast = broadcast_to (shape x_reshaped) max_expanded in
let is_max = equal x_reshaped max_broadcast in
let large_val =
scalar (B.context x) Dtype.int32 (Int32.of_int kernel_elements)
in
let masked_indices =
where is_max kernel_indices_broadcast
(broadcast_to (shape kernel_indices_broadcast) large_val)
in
let kernel_idx =
min masked_indices
~axes:[ Array.length (shape masked_indices) - 2 ]
~keepdims:false
in
let final_indices = reshape result_shape kernel_idx in
let final_indices_corrected = final_indices in
(max_values_corrected, Some final_indices_corrected)
let avg_pool1d ~kernel_size ?stride ?dilation ?(padding_spec = `Valid)
?(ceil_mode = false) ?(count_include_pad = true) x =
avg_pool_nd x ~kernel_size:[| kernel_size |]
?stride:(Option.map (fun s -> [| s |]) stride)
?dilation:(Option.map (fun d -> [| d |]) dilation)
~padding_spec ~ceil_mode ~count_include_pad ~num_spatial_dims:1
let avg_pool2d ~kernel_size ?stride ?dilation ?(padding_spec = `Valid)
?(ceil_mode = false) ?(count_include_pad = true) x =
avg_pool_nd x
~kernel_size:(pair_to_array kernel_size)
?stride:(Option.map pair_to_array stride)
?dilation:(Option.map pair_to_array dilation)
~padding_spec ~ceil_mode ~count_include_pad ~num_spatial_dims:2
let max_pool1d ~kernel_size ?stride ?dilation ?(padding_spec = `Valid)
?(ceil_mode = false) ?(return_indices = false) x =
max_pool_nd x ~kernel_size:[| kernel_size |]
?stride:(Option.map (fun s -> [| s |]) stride)
?dilation:(Option.map (fun d -> [| d |]) dilation)
~padding_spec ~ceil_mode ~return_indices ~num_spatial_dims:1
let max_pool2d ~kernel_size ?stride ?dilation ?(padding_spec = `Valid)
?(ceil_mode = false) ?(return_indices = false) x =
max_pool_nd x
~kernel_size:(pair_to_array kernel_size)
?stride:(Option.map pair_to_array stride)
?dilation:(Option.map pair_to_array dilation)
~padding_spec ~ceil_mode ~return_indices ~num_spatial_dims:2
(** Internal N-Dimensional min pooling using unfold and reduce. *)
let min_pool_nd ~kernel_size ?stride ?dilation ~padding_spec ~ceil_mode
~return_indices ~num_spatial_dims x =
let x_ndim = ndim x in
let input_spatial_shape =
Array.sub (shape x) (x_ndim - num_spatial_dims) num_spatial_dims
in
if Array.exists (fun d -> d = 0) input_spatial_shape then
let empty_output = empty (B.context x) (dtype x) (shape x) in
if return_indices then
let empty_indices = empty (B.context x) Dtype.int32 (shape x) in
(empty_output, Some empty_indices)
else (empty_output, None)
else
let ( _input_spatial_shape,
s_s,
d_s,
_current_pads_pairs,
_,
full_pad_config ) =
pool_setup ~num_spatial_dims ~kernel_size ?stride ?dilation
~padding_spec ~ceil_mode x
in
let padding_pairs =
Array.sub full_pad_config (x_ndim - num_spatial_dims) num_spatial_dims
in
let x_unfolded =
B.op_unfold x ~kernel_size ~stride:s_s ~dilation:d_s
~padding:padding_pairs
in
let prefix_shape = Array.sub (shape x) 0 (x_ndim - num_spatial_dims) in
let padded_spatial =
Array.init num_spatial_dims (fun i ->
(shape x).(x_ndim - num_spatial_dims + i)
+ fst padding_pairs.(i)
+ snd padding_pairs.(i))
in
let output_spatial =
Array.init num_spatial_dims (fun i ->
let effective_kernel = ((kernel_size.(i) - 1) * d_s.(i)) + 1 in
((padded_spatial.(i) - effective_kernel) / s_s.(i)) + 1)
in
let channels =
if x_ndim - num_spatial_dims >= 1 then (
let ch_prod = ref 1 in
for i = 1 to x_ndim - num_spatial_dims - 1 do
ch_prod := !ch_prod * (shape x).(i)
done;
!ch_prod)
else 1
in
let kernel_elements = array_prod kernel_size in
let num_blocks =
(shape x_unfolded).(Array.length (shape x_unfolded) - 1)
in
let batch_size =
if Array.length prefix_shape >= 1 then prefix_shape.(0) else 1
in
let x_reshaped =
reshape
[| batch_size; channels; kernel_elements; num_blocks |]
x_unfolded
in
let min_pooled = ref None in
for k = 0 to kernel_elements - 1 do
let slice =
B.op_shrink x_reshaped
[| (0, batch_size); (0, channels); (k, k + 1); (0, num_blocks) |]
in
let slice_squeezed =
reshape [| batch_size; channels; num_blocks |] slice
in
match !min_pooled with
| None -> min_pooled := Some slice_squeezed
| Some current -> min_pooled := Some (minimum current slice_squeezed)
done;
let min_values_3d = Option.get !min_pooled in
let result_shape = Array.concat [ prefix_shape; output_spatial ] in
let min_values = reshape result_shape min_values_3d in
let min_values_corrected = min_values in
if not return_indices then (min_values_corrected, None)
else (min_values_corrected, None)
let min_pool1d ~kernel_size ?stride ?dilation ?(padding_spec = `Valid)
?(ceil_mode = false) ?(return_indices = false) x =
min_pool_nd x ~kernel_size:[| kernel_size |]
?stride:(Option.map (fun s -> [| s |]) stride)
?dilation:(Option.map (fun d -> [| d |]) dilation)
~padding_spec ~ceil_mode ~return_indices ~num_spatial_dims:1
let min_pool2d ~kernel_size ?stride ?dilation ?(padding_spec = `Valid)
?(ceil_mode = false) ?(return_indices = false) x =
min_pool_nd x
~kernel_size:(pair_to_array kernel_size)
?stride:(Option.map pair_to_array stride)
?dilation:(Option.map pair_to_array dilation)
~padding_spec ~ceil_mode ~return_indices ~num_spatial_dims:2
(** Helper for N-dim one-hot encoding. Creates a new last dimension for
classes. *)
let one_hot ~num_classes index_tensor =
let index_dt = dtype index_tensor in
if not (Dtype.is_int index_dt || Dtype.is_uint index_dt) then
Error.invalid ~op:"one_hot"
~what:(Printf.sprintf "dtype %s" (Dtype.to_string index_dt))
~reason:"indices must be integer type" ();
let index_expanded = unsqueeze index_tensor ~axes:[ ndim index_tensor ] in
let arange_x = arange (B.context index_tensor) index_dt 0 num_classes 1 in
let ndim_expanded = ndim index_expanded in
let shape_for_arange = Array.make ndim_expanded 1 in
shape_for_arange.(ndim_expanded - 1) <- num_classes;
let arange_b = reshape shape_for_arange arange_x in
cmpeq index_expanded arange_b
(** Internal N-Dimensional max unpooling. *)
let max_unpool_nd ~kernel_size ?stride ?dilation ~padding_spec
?output_size_opt ~num_spatial_dims input_x indices_x =
let bs = dim 0 input_x in
let c = dim 1 input_x in
let pooled_spatial_shape = Array.sub (shape input_x) 2 num_spatial_dims in
let output_spatial_shape =
match output_size_opt with
| Some os_arr -> os_arr
| None ->
let s_s = Option.value stride ~default:kernel_size in
let d_s =
Option.value dilation ~default:(Array.make num_spatial_dims 1)
in
let pads_pairs =
resolve_padding_for_ops padding_spec
~input_spatial_shape:pooled_spatial_shape
~k_s:kernel_size ~s_s ~d_s ~op_type:`Convolution
in
Array.init num_spatial_dims (fun i ->
let pooled_dim_size = pooled_spatial_shape.(i) in
let k = kernel_size.(i) in
let s = s_s.(i) in
let d = d_s.(i) in
let pb, pa = pads_pairs.(i) in
((pooled_dim_size - 1) * s) - pb - pa + ((d * (k - 1)) + 1))
in
let prod_output_spatial_size = array_prod output_spatial_shape in
let one_hot_mask_for_indices =
one_hot indices_x ~num_classes:prod_output_spatial_size
in
let input_expanded = unsqueeze input_x ~axes:[ ndim input_x ] in
let multiplied = mul one_hot_mask_for_indices input_expanded in
let sum_axes = Array.init num_spatial_dims (fun i -> 2 + i) in
let result_flat_spatial =
sum multiplied ~axes:(Array.to_list sum_axes) ~keepdims:false
in
let final_shape = Array.concat [ [| bs; c |]; output_spatial_shape ] in
reshape final_shape result_flat_spatial
let max_unpool1d input_x indices_x ~kernel_size ?stride ?dilation
?(padding_spec = `Valid) ?output_size_opt () =
max_unpool_nd input_x indices_x ~kernel_size:[| kernel_size |]
?stride:(Option.map (fun s -> [| s |]) stride)
?dilation:(Option.map (fun d -> [| d |]) dilation)
~padding_spec ?output_size_opt ~num_spatial_dims:1
let max_unpool2d input_x indices_x ~kernel_size ?stride ?dilation
?(padding_spec = `Valid) ?output_size_opt () =
max_unpool_nd input_x indices_x
~kernel_size:(pair_to_array kernel_size)
?stride:(Option.map pair_to_array stride)
?dilation:(Option.map pair_to_array dilation)
~padding_spec ?output_size_opt ~num_spatial_dims:2
let pp_data (type a b) fmt (x : (a, b) t) =
let open Format in
let view = B.view x in
let buffer = B.data x in
let dtype = dtype x in
let shape =
match Symbolic_shape.eval (Lazy_view.shape view) with
| Some arr -> arr
| None ->
Error.failed ~op:"pp_data"
~what:"cannot print tensor with symbolic shape" ()
in
let ndim = Array.length shape in
let sz =
match Symbolic_shape.eval_dim (Lazy_view.numel view) with
| Some n -> n
| None ->
Error.failed ~op:"pp_data"
~what:"cannot print tensor with symbolic size" ()
in
let pp_element fmt (elt : a) =
match dtype with
| Float16 -> fprintf fmt "%g" elt
| Float32 -> fprintf fmt "%g" elt
| Float64 -> fprintf fmt "%g" elt
| BFloat16 -> fprintf fmt "%g" elt
| Float8_e4m3 -> fprintf fmt "%g" elt
| Float8_e5m2 -> fprintf fmt "%g" elt
| Int8 -> fprintf fmt "%d" elt
| Int16 -> fprintf fmt "%d" elt
| Int32 -> fprintf fmt "%ld" elt
| Int64 -> fprintf fmt "%Ld" elt
| UInt8 -> fprintf fmt "%d" elt
| UInt16 -> fprintf fmt "%d" elt
| Int -> fprintf fmt "%d" elt
| NativeInt -> fprintf fmt "%nd" elt
| Int4 -> fprintf fmt "%d" elt
| UInt4 -> fprintf fmt "%d" elt
| QInt8 -> fprintf fmt "%d" elt
| QUInt8 -> fprintf fmt "%d" elt
| Bool -> fprintf fmt "%b" elt
| Complex32 -> fprintf fmt "(%g+%gi)" elt.re elt.im
| Complex64 -> fprintf fmt "(%g+%gi)" elt.re elt.im
| Complex16 -> fprintf fmt "(%g+%gi)" elt.re elt.im
in
if sz = 0 && ndim > 0 then fprintf fmt "[]"
else if ndim = 0 then
if sz > 0 then
let value =
Array1.unsafe_get buffer
(match Symbolic_shape.eval_dim (Lazy_view.offset view) with
| Some n -> n
| None ->
Error.failed ~op:"pp_data"
~what:"cannot access data with symbolic offset" ())
in
pp_element fmt value
else fprintf fmt "<empty scalar>"
else
let rec pp_slice fmt current_indices =
let current_ndim = List.length current_indices in
if current_ndim = ndim then
let md_index = Array.of_list current_indices in
let linear_offset =
let strides =
match Lazy_view.strides view with
| Some s -> s
| None ->
Error.failed ~op:"pp_data"
~what:"cannot print non-contiguous symbolic tensor" ()
in
let offset =
match Symbolic_shape.eval_dim (Lazy_view.offset view) with
| Some n -> n
| None ->
Error.failed ~op:"pp_data"
~what:"cannot print tensor with symbolic offset" ()
in
Shape.ravel_index md_index strides + offset
in
if linear_offset < 0 || linear_offset >= Array1.dim buffer then
fprintf fmt "<OOB:%d/%d>" linear_offset (Array1.dim buffer)
else
let value = Array1.unsafe_get buffer linear_offset in
pp_element fmt value
else
let axis = current_ndim in
let dim_size = shape.(axis) in
fprintf fmt "[";
if dim_size > 0 then (
if axis < ndim - 1 then pp_open_vbox fmt 0 else pp_open_hbox fmt ();
for i = 0 to dim_size - 1 do
if i > 0 then (
fprintf fmt ",";
if axis = ndim - 1 then fprintf fmt " " else pp_print_cut fmt ());
pp_slice fmt (current_indices @ [ i ])
done;
pp_close_box fmt ());
fprintf fmt "]"
in
if sz > 0 then pp_slice fmt [] else fprintf fmt "[]"
let format_to_string pp x =
let buf = Stdlib.Buffer.create 1024 in
let fmt = Format.formatter_of_buffer buf in
pp fmt x;
Format.pp_print_flush fmt ();
Stdlib.Buffer.contents buf
let print_with_formatter pp x =
pp Format.std_formatter x;
Format.pp_print_newline Format.std_formatter ();
Format.pp_print_flush Format.std_formatter ()
let data_to_string x = format_to_string pp_data x
let print_data x = print_with_formatter pp_data x
let pp_dtype fmt dtype = Format.fprintf fmt "%s" (Dtype.to_string dtype)
let dtype_to_string dtype = Dtype.to_string dtype
let shape_to_string shape =
let shape_str =
Array.map string_of_int shape |> Array.to_list |> String.concat "x"
in
Printf.sprintf "[%s]" shape_str
let pp_shape fmt shape = Format.fprintf fmt "%s" (shape_to_string shape)
let pp fmt x =
let open Format in
let view = B.view x in
fprintf fmt "@[<v 0>";
fprintf fmt "Nx Info:@,";
fprintf fmt " Shape: %s@,"
(Symbolic_shape.to_string (Lazy_view.shape view));
fprintf fmt " Dtype: %a@," pp_dtype (dtype x);
fprintf fmt " Strides: %s@,"
(match Lazy_view.strides view with
| Some s ->
"["
^ String.concat "; " (Array.to_list (Array.map string_of_int s))
^ "]"
| None -> "<symbolic>");
fprintf fmt " Offset: %s@,"
(match Symbolic_shape.eval_dim (Lazy_view.offset view) with
| Some n -> string_of_int n
| None -> "<symbolic>");
fprintf fmt " Size: %s@,"
(match Symbolic_shape.eval_dim (Lazy_view.numel view) with
| Some n -> string_of_int n
| None -> "<symbolic>");
fprintf fmt " Data: %a@," pp_data x
let print x = print_with_formatter pp x
let to_string x = format_to_string pp x
let map_item f x =
let dt = dtype x in
let sh = shape x in
let result = empty (B.context x) dt sh in
let data_src = data (contiguous x) in
let data_dst = data result in
let sz = size x in
for i = 0 to sz - 1 do
let v = Array1.unsafe_get data_src i in
let v' = f v in
Array1.unsafe_set data_dst i v'
done;
result
let iter_item f x =
let data_src = data (contiguous x) in
let sz = size x in
for i = 0 to sz - 1 do
let v = Array1.unsafe_get data_src i in
f v
done
let fold_item f init x =
let data_src = data (contiguous x) in
let sz = size x in
let acc = ref init in
for i = 0 to sz - 1 do
let v = Array1.unsafe_get data_src i in
acc := f !acc v
done;
!acc
let map f x =
let dt = dtype x in
let sh = shape x in
let result = empty (B.context x) dt sh in
let total_size = size x in
for i = 0 to total_size - 1 do
let idx = Shape.unravel_index i sh |> Array.to_list in
let v = get idx x in
let v' = f v in
set idx result v'
done;
result
let iter f x =
let sh = shape x in
let total_size = size x in
for i = 0 to total_size - 1 do
let idx = Shape.unravel_index i sh |> Array.to_list in
let v = get idx x in
f v
done
let fold f init x =
let sh = shape x in
let total_size = size x in
let acc = ref init in
for i = 0 to total_size - 1 do
let idx = Shape.unravel_index i sh |> Array.to_list in
let v = get idx x in
acc := f !acc v
done;
!acc
module Infix = struct
let ( + ) = add
let ( +$ ) = add_s
let ( - ) = sub
let ( -$ ) = sub_s
let ( * ) = mul
let ( *$ ) = mul_s
let ( / ) = div
let ( /$ ) = div_s
let ( ** ) = pow
let ( **$ ) = pow_s
let ( % ) = mod_
let ( mod ) = mod_
let ( %$ ) = mod_s
let ( lxor ) = bitwise_xor
let ( lor ) = bitwise_or
let ( land ) = bitwise_and
let ( ^ ) = logical_xor
let ( && ) = logical_and
let ( || ) = logical_or
let ( ~- ) = logical_not
let ( < ) = less
let ( <$ ) = less_s
let ( <> ) = not_equal
let ( <>$ ) = not_equal_s
let ( = ) = equal
let ( =$ ) = equal_s
let ( > ) = greater
let ( >$ ) = greater_s
let ( <= ) = less_equal
let ( <=$ ) = less_equal_s
let ( >= ) = greater_equal
let ( >=$ ) = greater_equal_s
let ( @@ ) = matmul
let ( /@ ) = solve
let ( **@ ) = matrix_power
let ( <.> ) = dot
let ( @= ) a b = concatenate ~axis:0 [ a; b ]
let ( @|| ) a b = concatenate ~axis:1 [ a; b ]
let ( .%{} ) x indices = get indices x
let ( .%{}<- ) x indices value = set indices x value
let ( .${} ) x slice_def = slice slice_def x
let ( .${}<- ) x slice_def value = set_slice slice_def x value
end
end