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
| /*
| Face-API
| homepage: <https://github.com/vladmandic/face-api>
| author: <https://github.com/vladmandic>'
| */
|
| var Eq=Object.create;var u0=Object.defineProperty;var Aq=Object.getOwnPropertyDescriptor;var Dq=Object.getOwnPropertyNames;var $q=Object.getPrototypeOf,Rq=Object.prototype.hasOwnProperty;var wr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Kt=(r,t)=>{for(var e in t)u0(r,e,{get:t[e],enumerable:!0})},Fq=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dq(t))!Rq.call(r,o)&&o!==e&&u0(r,o,{get:()=>t[o],enumerable:!(n=Aq(t,o))||n.enumerable});return r};var Xl=(r,t,e)=>(e=r!=null?Eq($q(r)):{},Fq(t||!r||!r.__esModule?u0(e,"default",{value:r,enumerable:!0}):e,r));var M_=wr((Zmt,P_)=>{P_.exports=Ue;var Io=null;try{Io=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(r){}function Ue(r,t,e){this.low=r|0,this.high=t|0,this.unsigned=!!e}Ue.prototype.__isLong__;Object.defineProperty(Ue.prototype,"__isLong__",{value:!0});function Gn(r){return(r&&r.__isLong__)===!0}Ue.isLong=Gn;var T_={},__={};function fc(r,t){var e,n,o;return t?(r>>>=0,(o=0<=r&&r<256)&&(n=__[r],n)?n:(e=He(r,(r|0)<0?-1:0,!0),o&&(__[r]=e),e)):(r|=0,(o=-128<=r&&r<128)&&(n=T_[r],n)?n:(e=He(r,r<0?-1:0,!1),o&&(T_[r]=e),e))}Ue.fromInt=fc;function Co(r,t){if(isNaN(r))return t?mc:vo;if(t){if(r<0)return mc;if(r>=$_)return O_}else{if(r<=-A_)return Vn;if(r+1>=A_)return F_}return r<0?Co(-r,t).neg():He(r%Qp|0,r/Qp|0,t)}Ue.fromNumber=Co;function He(r,t,e){return new Ue(r,t,e)}Ue.fromBits=He;var tx=Math.pow;function C0(r,t,e){if(r.length===0)throw Error("empty string");if(r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return vo;if(typeof t=="number"?(e=t,t=!1):t=!!t,e=e||10,e<2||36<e)throw RangeError("radix");var n;if((n=r.indexOf("-"))>0)throw Error("interior hyphen");if(n===0)return C0(r.substring(1),t,e).neg();for(var o=Co(tx(e,8)),s=vo,i=0;i<r.length;i+=8){var a=Math.min(8,r.length-i),u=parseInt(r.substring(i,i+a),e);if(a<8){var l=Co(tx(e,a));s=s.mul(l).add(Co(u))}else s=s.mul(o),s=s.add(Co(u))}return s.unsigned=t,s}Ue.fromString=C0;function li(r,t){return typeof r=="number"?Co(r,t):typeof r=="string"?C0(r,t):He(r.low,r.high,typeof t=="boolean"?t:r.unsigned)}Ue.fromValue=li;var E_=65536,nK=1<<24,Qp=E_*E_,$_=Qp*Qp,A_=$_/2,D_=fc(nK),vo=fc(0);Ue.ZERO=vo;var mc=fc(0,!0);Ue.UZERO=mc;var Jp=fc(1);Ue.ONE=Jp;var R_=fc(1,!0);Ue.UONE=R_;var I0=fc(-1);Ue.NEG_ONE=I0;var F_=He(-1,2147483647,!1);Ue.MAX_VALUE=F_;var O_=He(-1,-1,!0);Ue.MAX_UNSIGNED_VALUE=O_;var Vn=He(0,-2147483648,!1);Ue.MIN_VALUE=Vn;var xt=Ue.prototype;xt.toInt=function(){return this.unsigned?this.low>>>0:this.low};xt.toNumber=function(){return this.unsigned?(this.high>>>0)*Qp+(this.low>>>0):this.high*Qp+(this.low>>>0)};xt.toString=function(t){if(t=t||10,t<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(Vn)){var e=Co(t),n=this.div(e),o=n.mul(e).sub(this);return n.toString(t)+o.toInt().toString(t)}else return"-"+this.neg().toString(t);for(var s=Co(tx(t,6),this.unsigned),i=this,a="";;){var u=i.div(s),l=i.sub(u.mul(s)).toInt()>>>0,c=l.toString(t);if(i=u,i.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};xt.getHighBits=function(){return this.high};xt.getHighBitsUnsigned=function(){return this.high>>>0};xt.getLowBits=function(){return this.low};xt.getLowBitsUnsigned=function(){return this.low>>>0};xt.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Vn)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<<e);e--);return this.high!=0?e+33:e+1};xt.isZero=function(){return this.high===0&&this.low===0};xt.eqz=xt.isZero;xt.isNegative=function(){return!this.unsigned&&this.high<0};xt.isPositive=function(){return this.unsigned||this.high>=0};xt.isOdd=function(){return(this.low&1)===1};xt.isEven=function(){return(this.low&1)===0};xt.equals=function(t){return Gn(t)||(t=li(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};xt.eq=xt.equals;xt.notEquals=function(t){return!this.eq(t)};xt.neq=xt.notEquals;xt.ne=xt.notEquals;xt.lessThan=function(t){return this.comp(t)<0};xt.lt=xt.lessThan;xt.lessThanOrEqual=function(t){return this.comp(t)<=0};xt.lte=xt.lessThanOrEqual;xt.le=xt.lessThanOrEqual;xt.greaterThan=function(t){return this.comp(t)>0};xt.gt=xt.greaterThan;xt.greaterThanOrEqual=function(t){return this.comp(t)>=0};xt.gte=xt.greaterThanOrEqual;xt.ge=xt.greaterThanOrEqual;xt.compare=function(t){if(Gn(t)||(t=li(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};xt.comp=xt.compare;xt.negate=function(){return!this.unsigned&&this.eq(Vn)?Vn:this.not().add(Jp)};xt.neg=xt.negate;xt.add=function(t){Gn(t)||(t=li(t));var e=this.high>>>16,n=this.high&65535,o=this.low>>>16,s=this.low&65535,i=t.high>>>16,a=t.high&65535,u=t.low>>>16,l=t.low&65535,c=0,p=0,m=0,f=0;return f+=s+l,m+=f>>>16,f&=65535,m+=o+u,p+=m>>>16,m&=65535,p+=n+a,c+=p>>>16,p&=65535,c+=e+i,c&=65535,He(m<<16|f,c<<16|p,this.unsigned)};xt.subtract=function(t){return Gn(t)||(t=li(t)),this.add(t.neg())};xt.sub=xt.subtract;xt.multiply=function(t){if(this.isZero())return vo;if(Gn(t)||(t=li(t)),Io){var e=Io.mul(this.low,this.high,t.low,t.high);return He(e,Io.get_high(),this.unsigned)}if(t.isZero())return vo;if(this.eq(Vn))return t.isOdd()?Vn:vo;if(t.eq(Vn))return this.isOdd()?Vn:vo;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(D_)&&t.lt(D_))return Co(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,o=this.high&65535,s=this.low>>>16,i=this.low&65535,a=t.high>>>16,u=t.high&65535,l=t.low>>>16,c=t.low&65535,p=0,m=0,f=0,d=0;return d+=i*c,f+=d>>>16,d&=65535,f+=s*c,m+=f>>>16,f&=65535,f+=i*l,m+=f>>>16,f&=65535,m+=o*c,p+=m>>>16,m&=65535,m+=s*l,p+=m>>>16,m&=65535,m+=i*u,p+=m>>>16,m&=65535,p+=n*c+o*l+s*u+i*a,p&=65535,He(f<<16|d,p<<16|m,this.unsigned)};xt.mul=xt.multiply;xt.divide=function(t){if(Gn(t)||(t=li(t)),t.isZero())throw Error("division by zero");if(Io){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Io.div_u:Io.div_s)(this.low,this.high,t.low,t.high);return He(e,Io.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?mc:vo;var n,o,s;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return mc;if(t.gt(this.shru(1)))return R_;s=mc}else{if(this.eq(Vn)){if(t.eq(Jp)||t.eq(I0))return Vn;if(t.eq(Vn))return Jp;var i=this.shr(1);return n=i.div(t).shl(1),n.eq(vo)?t.isNegative()?Jp:I0:(o=this.sub(t.mul(n)),s=n.add(o.div(t)),s)}else if(t.eq(Vn))return this.unsigned?mc:vo;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=vo}for(o=this;o.gte(t);){n=Math.max(1,Math.floor(o.toNumber()/t.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),u=a<=48?1:tx(2,a-48),l=Co(n),c=l.mul(t);c.isNegative()||c.gt(o);)n-=u,l=Co(n,this.unsigned),c=l.mul(t);l.isZero()&&(l=Jp),s=s.add(l),o=o.sub(c)}return s};xt.div=xt.divide;xt.modulo=function(t){if(Gn(t)||(t=li(t)),Io){var e=(this.unsigned?Io.rem_u:Io.rem_s)(this.low,this.high,t.low,t.high);return He(e,Io.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};xt.mod=xt.modulo;xt.rem=xt.modulo;xt.not=function(){return He(~this.low,~this.high,this.unsigned)};xt.and=function(t){return Gn(t)||(t=li(t)),He(this.low&t.low,this.high&t.high,this.unsigned)};xt.or=function(t){return Gn(t)||(t=li(t)),He(this.low|t.low,this.high|t.high,this.unsigned)};xt.xor=function(t){return Gn(t)||(t=li(t)),He(this.low^t.low,this.high^t.high,this.unsigned)};xt.shiftLeft=function(t){return Gn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?He(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):He(0,this.low<<t-32,this.unsigned)};xt.shl=xt.shiftLeft;xt.shiftRight=function(t){return Gn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?He(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):He(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};xt.shr=xt.shiftRight;xt.shiftRightUnsigned=function(t){if(Gn(t)&&(t=t.toInt()),t&=63,t===0)return this;var e=this.high;if(t<32){var n=this.low;return He(n>>>t|e<<32-t,e>>>t,this.unsigned)}else return t===32?He(e,0,this.unsigned):He(e>>>t-32,0,this.unsigned)};xt.shru=xt.shiftRightUnsigned;xt.shr_u=xt.shiftRightUnsigned;xt.toSigned=function(){return this.unsigned?He(this.low,this.high,!1):this};xt.toUnsigned=function(){return this.unsigned?this:He(this.low,this.high,!0)};xt.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};xt.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};xt.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};Ue.fromBytes=function(t,e,n){return n?Ue.fromBytesLE(t,e):Ue.fromBytesBE(t,e)};Ue.fromBytesLE=function(t,e){return new Ue(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};Ue.fromBytesBE=function(t,e){return new Ue(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}});var yE=wr(()=>{});var bE=wr(()=>{});var YE=wr((XE,eN)=>{(function(r,t,e){function n(a){var u=this,l=i();u.next=function(){var c=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=c-(u.c=c|0)},u.c=1,u.s0=l(" "),u.s1=l(" "),u.s2=l(" "),u.s0-=l(a),u.s0<0&&(u.s0+=1),u.s1-=l(a),u.s1<0&&(u.s1+=1),u.s2-=l(a),u.s2<0&&(u.s2+=1),l=null}function o(a,u){return u.c=a.c,u.s0=a.s0,u.s1=a.s1,u.s2=a.s2,u}function s(a,u){var l=new n(a),c=u&&u.state,p=l.next;return p.int32=function(){return l.next()*4294967296|0},p.double=function(){return p()+(p()*2097152|0)*11102230246251565e-32},p.quick=p,c&&(typeof c=="object"&&o(c,l),p.state=function(){return o(l,{})}),p}function i(){var a=4022871197,u=function(l){l=String(l);for(var c=0;c<l.length;c++){a+=l.charCodeAt(c);var p=.02519603282416938*a;a=p>>>0,p-=a,p*=a,a=p>>>0,p-=a,a+=p*4294967296}return(a>>>0)*23283064365386963e-26};return u}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.alea=s})(XE,typeof eN=="object"&&eN,typeof define=="function"&&define)});var JE=wr((ZE,rN)=>{(function(r,t,e){function n(i){var a=this,u="";a.x=0,a.y=0,a.z=0,a.w=0,a.next=function(){var c=a.x^a.x<<11;return a.x=a.y,a.y=a.z,a.z=a.w,a.w^=a.w>>>19^c^c>>>8},i===(i|0)?a.x=i:u+=i;for(var l=0;l<u.length+64;l++)a.x^=u.charCodeAt(l)|0,a.next()}function o(i,a){return a.x=i.x,a.y=i.y,a.z=i.z,a.w=i.w,a}function s(i,a){var u=new n(i),l=a&&a.state,c=function(){return(u.next()>>>0)/4294967296};return c.double=function(){do var p=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=u.next,c.quick=c,l&&(typeof l=="object"&&o(l,u),c.state=function(){return o(u,{})}),c}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.xor128=s})(ZE,typeof rN=="object"&&rN,typeof define=="function"&&define)});var tA=wr((QE,nN)=>{(function(r,t,e){function n(i){var a=this,u="";a.next=function(){var c=a.x^a.x>>>2;return a.x=a.y,a.y=a.z,a.z=a.w,a.w=a.v,(a.d=a.d+362437|0)+(a.v=a.v^a.v<<4^(c^c<<1))|0},a.x=0,a.y=0,a.z=0,a.w=0,a.v=0,i===(i|0)?a.x=i:u+=i;for(var l=0;l<u.length+64;l++)a.x^=u.charCodeAt(l)|0,l==u.length&&(a.d=a.x<<10^a.x>>>4),a.next()}function o(i,a){return a.x=i.x,a.y=i.y,a.z=i.z,a.w=i.w,a.v=i.v,a.d=i.d,a}function s(i,a){var u=new n(i),l=a&&a.state,c=function(){return(u.next()>>>0)/4294967296};return c.double=function(){do var p=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=u.next,c.quick=c,l&&(typeof l=="object"&&o(l,u),c.state=function(){return o(u,{})}),c}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.xorwow=s})(QE,typeof nN=="object"&&nN,typeof define=="function"&&define)});var rA=wr((eA,oN)=>{(function(r,t,e){function n(i){var a=this;a.next=function(){var l=a.x,c=a.i,p,m,f;return p=l[c],p^=p>>>7,m=p^p<<24,p=l[c+1&7],m^=p^p>>>10,p=l[c+3&7],m^=p^p>>>3,p=l[c+4&7],m^=p^p<<7,p=l[c+7&7],p=p^p<<13,m^=p^p<<9,l[c]=m,a.i=c+1&7,m};function u(l,c){var p,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,p=0;p<c.length;++p)f[p&7]=f[p&7]<<15^c.charCodeAt(p)+f[p+1&7]<<13;for(;f.length<8;)f.push(0);for(p=0;p<8&&f[p]===0;++p);for(p==8?m=f[7]=-1:m=f[p],l.x=f,l.i=0,p=256;p>0;--p)l.next()}u(a,i)}function o(i,a){return a.x=i.x.slice(),a.i=i.i,a}function s(i,a){i==null&&(i=+new Date);var u=new n(i),l=a&&a.state,c=function(){return(u.next()>>>0)/4294967296};return c.double=function(){do var p=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=u.next,c.quick=c,l&&(l.x&&o(l,u),c.state=function(){return o(u,{})}),c}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.xorshift7=s})(eA,typeof oN=="object"&&oN,typeof define=="function"&&define)});var oA=wr((nA,sN)=>{(function(r,t,e){function n(i){var a=this;a.next=function(){var l=a.w,c=a.X,p=a.i,m,f;return a.w=l=l+1640531527|0,f=c[p+34&127],m=c[p=p+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[p]=f^m,a.i=p,f+(l^l>>>16)|0};function u(l,c){var p,m,f,d,h,g=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,d=-32;d<x;++d)c&&(m^=c.charCodeAt((d+32)%c.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,p=g[d&127]^=m+h,f=p==0?f+1:0);for(f>=128&&(g[(c&&c.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],p=g[f=f+1&127],m^=m<<13,p^=p<<17,m^=m>>>15,p^=p>>>12,g[f]=m^p;l.w=h,l.X=g,l.i=f}u(a,i)}function o(i,a){return a.i=i.i,a.w=i.w,a.X=i.X.slice(),a}function s(i,a){i==null&&(i=+new Date);var u=new n(i),l=a&&a.state,c=function(){return(u.next()>>>0)/4294967296};return c.double=function(){do var p=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=u.next,c.quick=c,l&&(l.X&&o(l,u),c.state=function(){return o(u,{})}),c}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.xor4096=s})(nA,typeof sN=="object"&&sN,typeof define=="function"&&define)});var iA=wr((sA,iN)=>{(function(r,t,e){function n(i){var a=this,u="";a.next=function(){var c=a.b,p=a.c,m=a.d,f=a.a;return c=c<<25^c>>>7^p,p=p-m|0,m=m<<24^m>>>8^f,f=f-c|0,a.b=c=c<<20^c>>>12^p,a.c=p=p-m|0,a.d=m<<16^p>>>16^f,a.a=f-c|0},a.a=0,a.b=0,a.c=-1640531527,a.d=1367130551,i===Math.floor(i)?(a.a=i/4294967296|0,a.b=i|0):u+=i;for(var l=0;l<u.length+20;l++)a.b^=u.charCodeAt(l)|0,a.next()}function o(i,a){return a.a=i.a,a.b=i.b,a.c=i.c,a.d=i.d,a}function s(i,a){var u=new n(i),l=a&&a.state,c=function(){return(u.next()>>>0)/4294967296};return c.double=function(){do var p=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=u.next,c.quick=c,l&&(typeof l=="object"&&o(l,u),c.state=function(){return o(u,{})}),c}t&&t.exports?t.exports=s:e&&e.amd?e(function(){return s}):this.tychei=s})(sA,typeof iN=="object"&&iN,typeof define=="function"&&define)});var aA=wr(()=>{});var uA=wr((lA,ny)=>{(function(r,t,e){var n=256,o=6,s=52,i="random",a=e.pow(n,o),u=e.pow(2,s),l=u*2,c=n-1,p;function m(w,I,N){var E=[];I=I==!0?{entropy:!0}:I||{};var A=g(h(I.entropy?[w,b(t)]:w==null?x():w,3),E),D=new f(E),F=function(){for(var P=D.g(o),V=a,G=0;P<u;)P=(P+G)*n,V*=n,G=D.g(1);for(;P>=l;)P/=2,V/=2,G>>>=1;return(P+G)/V};return F.int32=function(){return D.g(4)|0},F.quick=function(){return D.g(4)/4294967296},F.double=F,g(b(D.S),t),(I.pass||N||function(P,V,G,W){return W&&(W.S&&d(W,D),P.state=function(){return d(D,{})}),G?(e[i]=P,V):P})(F,A,"global"in I?I.global:this==e,I.state)}function f(w){var I,N=w.length,E=this,A=0,D=E.i=E.j=0,F=E.S=[];for(N||(w=[N++]);A<n;)F[A]=A++;for(A=0;A<n;A++)F[A]=F[D=c&D+w[A%N]+(I=F[A])],F[D]=I;(E.g=function(P){for(var V,G=0,W=E.i,q=E.j,H=E.S;P--;)V=H[W=c&W+1],G=G*n+H[c&(H[W]=H[q=c&q+V])+(H[q]=V)];return E.i=W,E.j=q,G})(n)}function d(w,I){return I.i=w.i,I.j=w.j,I.S=w.S.slice(),I}function h(w,I){var N=[],E=typeof w,A;if(I&&E=="object")for(A in w)try{N.push(h(w[A],I-1))}catch(D){}return N.length?N:E=="string"?w:w+"\0"}function g(w,I){for(var N=w+"",E,A=0;A<N.length;)I[c&A]=c&(E^=I[c&A]*19)+N.charCodeAt(A++);return b(I)}function x(){try{var w;return p&&(w=p.randomBytes)?w=w(n):(w=new Uint8Array(n),(r.crypto||r.msCrypto).getRandomValues(w)),b(w)}catch(E){var I=r.navigator,N=I&&I.plugins;return[+new Date,r,N,r.screen,b(t)]}}function b(w){return String.fromCharCode.apply(0,w)}if(g(e.random(),t),typeof ny=="object"&&ny.exports){ny.exports=m;try{p=aA()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return m}):e["seed"+i]=m})(typeof self!="undefined"?self:lA,[],Math)});var bh=wr((W1t,cA)=>{var _X=YE(),EX=JE(),AX=tA(),DX=rA(),$X=oA(),RX=iA(),Sc=uA();Sc.alea=_X;Sc.xor128=EX;Sc.xorwow=AX;Sc.xorshift7=DX;Sc.xor4096=$X;Sc.tychei=RX;cA.exports=Sc});var Tk=wr(()=>{});var pw=wr(()=>{});var X1=wr(()=>{});var MH=wr(()=>{});var LH=wr(()=>{});var zH=wr(()=>{});var BH=wr((EC,Z1)=>{var Y1=(()=>{var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(t){t=t||{};function e(){return it.buffer!=re&&je(it.buffer),xe}function n(){return it.buffer!=re&&je(it.buffer),fe}function o(){return it.buffer!=re&&je(it.buffer),Ae}function s(){return it.buffer!=re&&je(it.buffer),Ln}function i(){return it.buffer!=re&&je(it.buffer),lr}function a(){return it.buffer!=re&&je(it.buffer),eo}function u(){return it.buffer!=re&&je(it.buffer),Vr}var l=typeof t!="undefined"?t:{},c,p;l.ready=new Promise(function(M,U){c=M,p=U});var m;typeof process!="undefined"&&process.listeners&&(m={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var f=Object.assign({},l),d=[],h="./this.program",g=(M,U)=>{throw U},x=typeof window=="object",b=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I=l.ENVIRONMENT_IS_PTHREAD||!1,N="";function E(M){return l.locateFile?l.locateFile(M,N):N+M}var A,D,F,P;function V(M){if(M instanceof sc)return;X("exiting due to exception: "+M)}if(w){var G=pw(),W=X1();b?N=W.dirname(N)+"/":N=__dirname+"/",A=(U,dt)=>(U=Ep(U)?new URL(U):W.normalize(U),G.readFileSync(U,dt?void 0:"utf8")),F=U=>{var dt=A(U,!0);return dt.buffer||(dt=new Uint8Array(dt)),dt},D=(U,dt,Lt)=>{U=Ep(U)?new URL(U):W.normalize(U),G.readFile(U,function(Zt,Yt){Zt?Lt(Zt):dt(Yt.buffer)})},process.argv.length>1&&(h=process.argv[1].replace(/\\/g,"/")),d=process.argv.slice(2),process.on("uncaughtException",function(U){if(!(U instanceof sc))throw U}),process.on("unhandledRejection",function(U){throw U}),g=(U,dt)=>{if(Wo())throw process.exitCode=U,dt;V(dt),process.exit(U)},l.inspect=function(){return"[Emscripten Module object]"};let M;try{M=MH()}catch(U){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),U}global.Worker=M.Worker}else(x||b)&&(b?N=self.location.href:typeof document!="undefined"&&document.currentScript&&(N=document.currentScript.src),typeof r!="undefined"&&r&&(N=r),N.indexOf("blob:")!==0?N=N.substr(0,N.replace(/[?#].*/,"").lastIndexOf("/")+1):N="",w||(A=M=>{var U=new XMLHttpRequest;return U.open("GET",M,!1),U.send(null),U.responseText},b&&(F=M=>{var U=new XMLHttpRequest;return U.open("GET",M,!1),U.responseType="arraybuffer",U.send(null),new Uint8Array(U.response)}),D=(M,U,dt)=>{var Lt=new XMLHttpRequest;Lt.open("GET",M,!0),Lt.responseType="arraybuffer",Lt.onload=()=>{if(Lt.status==200||Lt.status==0&&Lt.response){U(Lt.response);return}dt()},Lt.onerror=dt,Lt.send(null)}),P=M=>document.title=M);w&&typeof performance=="undefined"&&(global.performance=LH().performance);var q=console.log.bind(console),H=console.warn.bind(console);w&&(q=M=>G.writeSync(1,M+`
| `),H=M=>G.writeSync(2,M+`
| `));var K=l.print||q,X=l.printErr||H;Object.assign(l,f),f=null,l.arguments&&(d=l.arguments),l.thisProgram&&(h=l.thisProgram),l.quit&&(g=l.quit);var Z=4,et=Atomics.load,nt=Atomics.store,st=Atomics.compareExchange,at;l.wasmBinary&&(at=l.wasmBinary);var ot=l.noExitRuntime||!0;typeof WebAssembly!="object"&&oc("no native wasm support detected");var it,mt,gt=!1,Ct;function Rt(M,U){M||oc(U)}var Dt=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Ht(M,U,dt){U>>>=0;for(var Lt=U+dt,Zt=U;M[Zt]&&!(Zt>=Lt);)++Zt;if(Zt-U>16&&M.buffer&&Dt)return Dt.decode(M.buffer instanceof SharedArrayBuffer?M.slice(U,Zt):M.subarray(U,Zt));for(var Yt="";U<Zt;){var bt=M[U++];if(!(bt&128)){Yt+=String.fromCharCode(bt);continue}var $t=M[U++]&63;if((bt&224)==192){Yt+=String.fromCharCode((bt&31)<<6|$t);continue}var nr=M[U++]&63;if((bt&240)==224?bt=(bt&15)<<12|$t<<6|nr:bt=(bt&7)<<18|$t<<12|nr<<6|M[U++]&63,bt<65536)Yt+=String.fromCharCode(bt);else{var so=bt-65536;Yt+=String.fromCharCode(55296|so>>10,56320|so&1023)}}return Yt}function qt(M,U){return M>>>=0,M?Ht(n(),M,U):""}function ce(M,U,dt,Lt){if(dt>>>=0,!(Lt>0))return 0;for(var Zt=dt,Yt=dt+Lt-1,bt=0;bt<M.length;++bt){var $t=M.charCodeAt(bt);if($t>=55296&&$t<=57343){var nr=M.charCodeAt(++bt);$t=65536+(($t&1023)<<10)|nr&1023}if($t<=127){if(dt>=Yt)break;U[dt++>>>0]=$t}else if($t<=2047){if(dt+1>=Yt)break;U[dt++>>>0]=192|$t>>6,U[dt++>>>0]=128|$t&63}else if($t<=65535){if(dt+2>=Yt)break;U[dt++>>>0]=224|$t>>12,U[dt++>>>0]=128|$t>>6&63,U[dt++>>>0]=128|$t&63}else{if(dt+3>=Yt)break;U[dt++>>>0]=240|$t>>18,U[dt++>>>0]=128|$t>>12&63,U[dt++>>>0]=128|$t>>6&63,U[dt++>>>0]=128|$t&63}}return U[dt>>>0]=0,dt-Zt}function ge(M,U,dt){return ce(M,n(),U,dt)}var re,xe,fe,Ae,De,Ln,lr,eo,Vr;I&&(re=l.buffer);function je(M){re=M,l.HEAP8=xe=new Int8Array(M),l.HEAP16=Ae=new Int16Array(M),l.HEAP32=Ln=new Int32Array(M),l.HEAPU8=fe=new Uint8Array(M),l.HEAPU16=De=new Uint16Array(M),l.HEAPU32=lr=new Uint32Array(M),l.HEAPF32=eo=new Float32Array(M),l.HEAPF64=Vr=new Float64Array(M)}var Gr=l.INITIAL_MEMORY||16777216;if(I)it=l.wasmMemory,re=l.buffer;else if(l.wasmMemory)it=l.wasmMemory;else if(it=new WebAssembly.Memory({initial:Gr/65536,maximum:65536,shared:!0}),!(it.buffer instanceof SharedArrayBuffer))throw X("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&X("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");it&&(re=it.buffer),Gr=re.byteLength,je(re);var Wr,ro=[],no=[],Qr=[],ka=!1;function Wo(){return ot}function Ei(){if(l.preRun)for(typeof l.preRun=="function"&&(l.preRun=[l.preRun]);l.preRun.length;)qd(l.preRun.shift());Xd(ro)}function Ar(){ka=!0,!I&&Xd(no)}function Ta(){if(!I){if(l.postRun)for(typeof l.postRun=="function"&&(l.postRun=[l.postRun]);l.postRun.length;)o_(l.postRun.shift());Xd(Qr)}}function qd(M){ro.unshift(M)}function Kd(M){no.unshift(M)}function o_(M){Qr.unshift(M)}var ql=0,_p=null,_a=null;function $C(M){ql++,l.monitorRunDependencies&&l.monitorRunDependencies(ql)}function Cg(M){if(ql--,l.monitorRunDependencies&&l.monitorRunDependencies(ql),ql==0&&(_p!==null&&(clearInterval(_p),_p=null),_a)){var U=_a;_a=null,U()}}function oc(M){l.onAbort&&l.onAbort(M),M="Aborted("+M+")",X(M),gt=!0,Ct=1,M+=". Build with -sASSERTIONS for more info.";var U=new WebAssembly.RuntimeError(M);throw p(U),U}var RC="data:application/octet-stream;base64,";function vg(M){return M.startsWith(RC)}function Ep(M){return M.startsWith("file://")}var tn;tn="tfjs-backend-wasm-threaded-simd.wasm",vg(tn)||(tn=E(tn));function Sg(M){try{if(M==tn&&at)return new Uint8Array(at);if(F)return F(M);throw"both async and sync fetching of the wasm failed"}catch(U){oc(U)}}function FC(){if(!at&&(x||b)){if(typeof fetch=="function"&&!Ep(tn))return fetch(tn,{credentials:"same-origin"}).then(function(M){if(!M.ok)throw"failed to load wasm binary file at '"+tn+"'";return M.arrayBuffer()}).catch(function(){return Sg(tn)});if(D)return new Promise(function(M,U){D(tn,function(dt){M(new Uint8Array(dt))},U)})}return Promise.resolve().then(function(){return Sg(tn)})}function OC(){var M={env:Mg,wasi_snapshot_preview1:Mg};function U(bt,$t){var nr=bt.exports;if(l.asm=nr,UC(l.asm._emscripten_tls_init),Wr=l.asm.__indirect_function_table,Kd(l.asm.__wasm_call_ctors),mt=$t,!I){var so=Xt.unusedWorkers.length;Xt.unusedWorkers.forEach(function(Aa){Xt.loadWasmModuleToWorker(Aa,function(){--so||Cg("wasm-instantiate")})})}}I||$C("wasm-instantiate");function dt(bt){U(bt.instance,bt.module)}function Lt(bt){return FC().then(function($t){return WebAssembly.instantiate($t,M)}).then(function($t){return $t}).then(bt,function($t){X("failed to asynchronously prepare wasm: "+$t),oc($t)})}function Zt(){return!at&&typeof WebAssembly.instantiateStreaming=="function"&&!vg(tn)&&!Ep(tn)&&!w&&typeof fetch=="function"?fetch(tn,{credentials:"same-origin"}).then(function(bt){var $t=WebAssembly.instantiateStreaming(bt,M);return $t.then(dt,function(nr){return X("wasm streaming compile failed: "+nr),X("falling back to ArrayBuffer instantiation"),Lt(dt)})}):Lt(dt)}if(l.instantiateWasm)try{var Yt=l.instantiateWasm(M,U);return Yt}catch(bt){X("Module.instantiateWasm callback failed with error: "+bt),p(bt)}return Zt().catch(p),{}}var s_,i_,Ng={};function sc(M){this.name="ExitStatus",this.message="Program terminated with exit("+M+")",this.status=M}function PC(M){var U=Xt.pthreads[M];delete Xt.pthreads[M],U.terminate(),i0(M),Xt.runningWorkers.splice(Xt.runningWorkers.indexOf(U),1),U.pthread_ptr=0}function MC(M){var U=Xt.pthreads[M];U.postMessage({cmd:"cancel"})}function jd(M){var U=Xt.pthreads[M];Rt(U),Xt.returnWorkerToPool(U)}function LC(M){var U=Xt.getNewWorker();if(!U)return 6;Xt.runningWorkers.push(U),Xt.pthreads[M.pthread_ptr]=U,U.pthread_ptr=M.pthread_ptr;var dt={cmd:"run",start_routine:M.startRoutine,arg:M.arg,pthread_ptr:M.pthread_ptr};return U.runPthread=()=>{w&&U.ref(),U.postMessage(dt,M.transferList),delete U.runPthread},U.loaded&&U.runPthread(),0}var kg={varargs:void 0,get:function(){kg.varargs+=4;var M=s()[kg.varargs-4>>>2];return M},getStr:function(M){var U=qt(M);return U}};function Tg(M){if(I)return Kl(1,1,M);Ct=M,Wo()||(Xt.terminateAllThreads(),l.onExit&&l.onExit(M),gt=!0),g(M,new sc(M))}function zC(M,U){if(Ct=M,!U&&I)throw Eg(M),"unwind";Tg(M)}var _g=zC;function BC(M){if(M instanceof sc||M=="unwind")return Ct;g(1,M)}var Xt={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){I?Xt.initWorker():Xt.initMainThread()},initMainThread:function(){for(var M=8;M--;)Xt.allocateUnusedWorker()},initWorker:function(){ot=!1},setExitStatus:function(M){Ct=M},terminateAllThreads:function(){for(var M of Object.values(Xt.pthreads))Xt.returnWorkerToPool(M);for(var M of Xt.unusedWorkers)M.terminate();Xt.unusedWorkers=[]},returnWorkerToPool:function(M){var U=M.pthread_ptr;delete Xt.pthreads[U],Xt.unusedWorkers.push(M),Xt.runningWorkers.splice(Xt.runningWorkers.indexOf(M),1),M.pthread_ptr=0,w&&M.unref(),i0(U)},receiveObjectTransfer:function(M){},threadInitTLS:function(){Xt.tlsInitFunctions.forEach(M=>M())},loadWasmModuleToWorker:function(M,U){M.onmessage=Yt=>{var bt=Yt.data,$t=bt.cmd;if(M.pthread_ptr&&(Xt.currentProxiedOperationCallerThread=M.pthread_ptr),bt.targetThread&&bt.targetThread!=Wg()){var nr=Xt.pthreads[bt.targetThread];nr?nr.postMessage(bt,bt.transferList):X('Internal error! Worker sent a message "'+$t+'" to target pthread '+bt.targetThread+", but that thread no longer exists!"),Xt.currentProxiedOperationCallerThread=void 0;return}$t==="processProxyingQueue"?Yd(bt.queue):$t==="spawnThread"?LC(bt):$t==="cleanupThread"?jd(bt.thread):$t==="killThread"?PC(bt.thread):$t==="cancelThread"?MC(bt.thread):$t==="loaded"?(M.loaded=!0,w&&M.unref(),U&&U(M),M.runPthread&&M.runPthread()):$t==="print"?K("Thread "+bt.threadId+": "+bt.text):$t==="printErr"?X("Thread "+bt.threadId+": "+bt.text):$t==="alert"?alert("Thread "+bt.threadId+": "+bt.text):bt.target==="setimmediate"?M.postMessage(bt):$t==="callHandler"?l[bt.handler](...bt.args):$t&&X("worker sent an unknown command "+$t),Xt.currentProxiedOperationCallerThread=void 0},M.onerror=Yt=>{var bt="worker sent an error!";throw X(bt+" "+Yt.filename+":"+Yt.lineno+": "+Yt.message),Yt},w&&(M.on("message",function(Yt){M.onmessage({data:Yt})}),M.on("error",function(Yt){M.onerror(Yt)}),M.on("detachedExit",function(){}));var dt=[],Lt=["onExit","onAbort","print","printErr"];for(var Zt of Lt)l.hasOwnProperty(Zt)&&dt.push(Zt);M.postMessage({cmd:"load",handlers:dt,urlOrBlob:l.mainScriptUrlOrBlob||r,wasmMemory:it,wasmModule:mt})},allocateUnusedWorker:function(){var M,U=E("tfjs-backend-wasm-threaded-simd.worker.js");M=new Worker(U),Xt.unusedWorkers.push(M)},getNewWorker:function(){return Xt.unusedWorkers.length==0&&(Xt.allocateUnusedWorker(),Xt.loadWasmModuleToWorker(Xt.unusedWorkers[0])),Xt.unusedWorkers.pop()}};l.PThread=Xt;function Xd(M){for(;M.length>0;)M.shift()(l)}function VC(){var M=Wg(),U=s()[M+52>>>2],dt=s()[M+56>>>2],Lt=U-dt;m_(U,Lt),Ug(U)}l.establishStackSpace=VC;function Eg(M){if(I)return Kl(2,0,M);try{_g(M)}catch(U){BC(U)}}var Ap=[];function GC(M){var U=Ap[M];return U||(M>=Ap.length&&(Ap.length=M+1),Ap[M]=U=Wr.get(M)),U}function WC(M,U){var dt=GC(M)(U);Wo()?Xt.setExitStatus(dt):p_(dt)}l.invokeEntryPoint=WC;function UC(M){Xt.tlsInitFunctions.push(M)}function HC(M){l_(M,!b,1,!x),Xt.threadInitTLS()}function qC(M){I?postMessage({cmd:"cleanupThread",thread:M}):jd(M)}function Ag(M,U,dt,Lt){return I?Kl(3,1,M,U,dt,Lt):Dg(M,U,dt,Lt)}function Dg(M,U,dt,Lt){if(typeof SharedArrayBuffer=="undefined")return X("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Zt=[],Yt=0;if(I&&(Zt.length===0||Yt))return Ag(M,U,dt,Lt);if(Yt)return Yt;var bt={startRoutine:dt,pthread_ptr:M,arg:Lt,transferList:Zt};return I?(bt.cmd="spawnThread",postMessage(bt,Zt),0):LC(bt)}function KC(){return 65536}var jC=!0;function XC(){return jC}function Yd(M){Atomics.store(s(),M>>2,1),Wg()&&c_(M),Atomics.compareExchange(s(),M>>2,1,0)}l.executeNotifiedProxyingQueue=Yd;function YC(M,U,dt,Lt){if(M==U)setTimeout(()=>Yd(Lt));else if(I)postMessage({targetThread:M,cmd:"processProxyingQueue",queue:Lt});else{var Zt=Xt.pthreads[M];if(!Zt)return;Zt.postMessage({cmd:"processProxyingQueue",queue:Lt})}return 1}function ZC(M,U,dt){return-1}function JC(){oc("")}function ic(M){ic.shown||(ic.shown={}),ic.shown[M]||(ic.shown[M]=1,w&&(M="warning: "+M),X(M))}function QC(){w||b||ic("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function tv(){return Date.now()}function $g(){return 4294901760}function ev(){return $g()}var Zd;w?Zd=()=>{var M=process.hrtime();return M[0]*1e3+M[1]/1e6}:Zd=()=>performance.timeOrigin+performance.now();function rv(M,U,dt){n().copyWithin(M>>>0,U>>>0,U+dt>>>0)}function nv(){return w?zH().cpus().length:navigator.hardwareConcurrency}function ov(M){var U=a0(),dt=M();return Ug(U),dt}function Kl(M,U){var dt=arguments.length-2,Lt=arguments;return ov(()=>{for(var Zt=dt,Yt=Hg(Zt*8),bt=Yt>>3,$t=0;$t<dt;$t++){var nr=Lt[2+$t];u()[bt+$t>>>0]=nr}return u_(M,Zt,Yt,U)})}var Jd=[];function sv(M,U,dt){Jd.length=U;for(var Lt=dt>>3,Zt=0;Zt<U;Zt++)Jd[Zt]=u()[Lt+Zt>>>0];var Yt=M<0,bt=Yt?Ng[-M-1]:dv[M];return bt.apply(null,Jd)}function iv(M){try{return it.grow(M-re.byteLength+65535>>>16),je(it.buffer),1}catch(U){}}function av(M){var U=n().length;if(M=M>>>0,M<=U)return!1;var dt=$g();if(M>dt)return!1;let Lt=(nr,so)=>nr+(so-nr%so)%so;for(var Zt=1;Zt<=4;Zt*=2){var Yt=U*(1+.2/Zt);Yt=Math.min(Yt,M+100663296);var bt=Math.min(dt,Lt(Math.max(M,Yt),65536)),$t=iv(bt);if($t)return!0}return!1}function lv(){throw"unwind"}function Rg(M){return I?Kl(4,1,M):52}function Fg(M,U,dt,Lt,Zt){return I?Kl(5,1,M,U,dt,Lt,Zt):70}var uv=[null,[],[]];function cv(M,U){var dt=uv[M];U===0||U===10?((M===1?K:X)(Ht(dt,0)),dt.length=0):dt.push(U)}function Og(M,U,dt,Lt){if(I)return Kl(6,1,M,U,dt,Lt);for(var Zt=0,Yt=0;Yt<dt;Yt++){var bt=i()[U>>>2],$t=i()[U+4>>>2];U+=8;for(var nr=0;nr<$t;nr++)cv(M,n()[bt+nr>>>0]);Zt+=$t}return i()[Lt>>>2]=Zt,0}function Pg(M){var U=l["_"+M];return U}function pv(M,U){e().set(M,U>>>0)}function mv(M,U,dt,Lt,Zt){var Yt={string:zn=>{var Fp=0;if(zn!=null&&zn!==0){var h_=(zn.length<<2)+1;Fp=Hg(h_),ge(zn,Fp,h_)}return Fp},array:zn=>{var Fp=Hg(zn.length);return pv(zn,Fp),Fp}};function bt(zn){return U==="string"?qt(zn):U==="boolean"?!!zn:zn}var $t=Pg(M),nr=[],so=0;if(Lt)for(var Aa=0;Aa<Lt.length;Aa++){var d_=Yt[dt[Aa]];d_?(so===0&&(so=a0()),nr[Aa]=d_(Lt[Aa])):nr[Aa]=Lt[Aa]}var l0=$t.apply(null,nr);function _q(zn){return so!==0&&Ug(so),bt(zn)}return l0=_q(l0),l0}function fv(M,U,dt,Lt){dt=dt||[];var Zt=dt.every(bt=>bt==="number"||bt==="boolean"),Yt=U!=="string";return Yt&&Zt&&!Lt?Pg(M):function(){return mv(M,U,dt,arguments,Lt)}}Xt.init();var dv=[null,Tg,Eg,Ag,Rg,Fg,Og],Mg={__emscripten_init_main_thread_js:HC,__emscripten_thread_cleanup:qC,__pthread_create_js:Dg,_emscripten_default_pthread_stack_size:KC,_emscripten_get_now_is_monotonic:XC,_emscripten_notify_task_queue:YC,_emscripten_set_offscreencanvas_size:ZC,abort:JC,emscripten_check_blocking_allowed:QC,emscripten_date_now:tv,emscripten_get_heap_max:ev,emscripten_get_now:Zd,emscripten_memcpy_big:rv,emscripten_num_logical_cores:nv,emscripten_receive_on_main_thread_js:sv,emscripten_resize_heap:av,emscripten_unwind_to_js_event_loop:lv,exit:_g,fd_close:Rg,fd_seek:Fg,fd_write:Og,memory:it||l.wasmMemory},a_=OC(),hv=l.___wasm_call_ctors=function(){return(hv=l.___wasm_call_ctors=l.asm.__wasm_call_ctors).apply(null,arguments)},gv=l._init=function(){return(gv=l._init=l.asm.init).apply(null,arguments)},xv=l._init_with_threads_count=function(){return(xv=l._init_with_threads_count=l.asm.init_with_threads_count).apply(null,arguments)},yv=l._get_threads_count=function(){return(yv=l._get_threads_count=l.asm.get_threads_count).apply(null,arguments)},bv=l._register_tensor=function(){return(bv=l._register_tensor=l.asm.register_tensor).apply(null,arguments)},wv=l._dispose_data=function(){return(wv=l._dispose_data=l.asm.dispose_data).apply(null,arguments)},Iv=l._dispose=function(){return(Iv=l._dispose=l.asm.dispose).apply(null,arguments)},Cv=l._Abs=function(){return(Cv=l._Abs=l.asm.Abs).apply(null,arguments)},vv=l._Acos=function(){return(vv=l._Acos=l.asm.Acos).apply(null,arguments)},Sv=l._Acosh=function(){return(Sv=l._Acosh=l.asm.Acosh).apply(null,arguments)},Nv=l._Add=function(){return(Nv=l._Add=l.asm.Add).apply(null,arguments)},kv=l._AddN=function(){return(kv=l._AddN=l.asm.AddN).apply(null,arguments)},Tv=l._All=function(){return(Tv=l._All=l.asm.All).apply(null,arguments)},_v=l._Any=function(){return(_v=l._Any=l.asm.Any).apply(null,arguments)},Ev=l._ArgMax=function(){return(Ev=l._ArgMax=l.asm.ArgMax).apply(null,arguments)},Av=l._ArgMin=function(){return(Av=l._ArgMin=l.asm.ArgMin).apply(null,arguments)},Dv=l._Asin=function(){return(Dv=l._Asin=l.asm.Asin).apply(null,arguments)},$v=l._Asinh=function(){return($v=l._Asinh=l.asm.Asinh).apply(null,arguments)},Rv=l._Atan=function(){return(Rv=l._Atan=l.asm.Atan).apply(null,arguments)},Fv=l._Atan2=function(){return(Fv=l._Atan2=l.asm.Atan2).apply(null,arguments)},Ov=l._Atanh=function(){return(Ov=l._Atanh=l.asm.Atanh).apply(null,arguments)},Pv=l._AvgPool=function(){return(Pv=l._AvgPool=l.asm.AvgPool).apply(null,arguments)},Mv=l._AvgPool3D=function(){return(Mv=l._AvgPool3D=l.asm.AvgPool3D).apply(null,arguments)},Lv=l._AvgPool3DGrad=function(){return(Lv=l._AvgPool3DGrad=l.asm.AvgPool3DGrad).apply(null,arguments)},zv=l._AvgPoolGrad=function(){return(zv=l._AvgPoolGrad=l.asm.AvgPoolGrad).apply(null,arguments)},Bv=l._BatchMatMul=function(){return(Bv=l._BatchMatMul=l.asm.BatchMatMul).apply(null,arguments)},Vv=l._Bincount=function(){return(Vv=l._Bincount=l.asm.Bincount).apply(null,arguments)},Gv=l._BitwiseAnd=function(){return(Gv=l._BitwiseAnd=l.asm.BitwiseAnd).apply(null,arguments)},Wv=l._Ceil=function(){return(Wv=l._Ceil=l.asm.Ceil).apply(null,arguments)},Uv=l._ClipByValue=function(){return(Uv=l._ClipByValue=l.asm.ClipByValue).apply(null,arguments)},Hv=l._Conv2D=function(){return(Hv=l._Conv2D=l.asm.Conv2D).apply(null,arguments)},qv=l._Conv2DBackpropInput=function(){return(qv=l._Conv2DBackpropInput=l.asm.Conv2DBackpropInput).apply(null,arguments)},Kv=l._Conv3D=function(){return(Kv=l._Conv3D=l.asm.Conv3D).apply(null,arguments)},jv=l._Conv3DBackpropFilterV2=function(){return(jv=l._Conv3DBackpropFilterV2=l.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Xv=l._Conv3DBackpropInputV2=function(){return(Xv=l._Conv3DBackpropInputV2=l.asm.Conv3DBackpropInputV2).apply(null,arguments)},Yv=l._Cos=function(){return(Yv=l._Cos=l.asm.Cos).apply(null,arguments)},Zv=l._Cosh=function(){return(Zv=l._Cosh=l.asm.Cosh).apply(null,arguments)},Jv=l._CropAndResize=function(){return(Jv=l._CropAndResize=l.asm.CropAndResize).apply(null,arguments)},Qv=l._Cumprod=function(){return(Qv=l._Cumprod=l.asm.Cumprod).apply(null,arguments)},tS=l._Cumsum=function(){return(tS=l._Cumsum=l.asm.Cumsum).apply(null,arguments)},eS=l._DenseBincount=function(){return(eS=l._DenseBincount=l.asm.DenseBincount).apply(null,arguments)},rS=l._DepthToSpace=function(){return(rS=l._DepthToSpace=l.asm.DepthToSpace).apply(null,arguments)},nS=l._DepthwiseConv2dNative=function(){return(nS=l._DepthwiseConv2dNative=l.asm.DepthwiseConv2dNative).apply(null,arguments)},oS=l._Diag=function(){return(oS=l._Diag=l.asm.Diag).apply(null,arguments)},sS=l._Dilation2D=function(){return(sS=l._Dilation2D=l.asm.Dilation2D).apply(null,arguments)},iS=l._Dilation2DBackpropFilter=function(){return(iS=l._Dilation2DBackpropFilter=l.asm.Dilation2DBackpropFilter).apply(null,arguments)},aS=l._Dilation2DBackpropInput=function(){return(aS=l._Dilation2DBackpropInput=l.asm.Dilation2DBackpropInput).apply(null,arguments)},lS=l._Elu=function(){return(lS=l._Elu=l.asm.Elu).apply(null,arguments)},uS=l._EluGrad=function(){return(uS=l._EluGrad=l.asm.EluGrad).apply(null,arguments)},cS=l._Equal=function(){return(cS=l._Equal=l.asm.Equal).apply(null,arguments)},pS=l._Erf=function(){return(pS=l._Erf=l.asm.Erf).apply(null,arguments)},mS=l._Exp=function(){return(mS=l._Exp=l.asm.Exp).apply(null,arguments)},fS=l._Expm1=function(){return(fS=l._Expm1=l.asm.Expm1).apply(null,arguments)},dS=l._FlipLeftRight=function(){return(dS=l._FlipLeftRight=l.asm.FlipLeftRight).apply(null,arguments)},hS=l._Floor=function(){return(hS=l._Floor=l.asm.Floor).apply(null,arguments)},gS=l._FloorDiv=function(){return(gS=l._FloorDiv=l.asm.FloorDiv).apply(null,arguments)},xS=l._FusedBatchNorm=function(){return(xS=l._FusedBatchNorm=l.asm.FusedBatchNorm).apply(null,arguments)},yS=l._FusedConv2D=function(){return(yS=l._FusedConv2D=l.asm.FusedConv2D).apply(null,arguments)},bS=l._FusedDepthwiseConv2D=function(){return(bS=l._FusedDepthwiseConv2D=l.asm.FusedDepthwiseConv2D).apply(null,arguments)},wS=l._Gather=function(){return(wS=l._Gather=l.asm.Gather).apply(null,arguments)},IS=l._GatherNd=function(){return(IS=l._GatherNd=l.asm.GatherNd).apply(null,arguments)},CS=l._Greater=function(){return(CS=l._Greater=l.asm.Greater).apply(null,arguments)},vS=l._GreaterEqual=function(){return(vS=l._GreaterEqual=l.asm.GreaterEqual).apply(null,arguments)},SS=l._IsFinite=function(){return(SS=l._IsFinite=l.asm.IsFinite).apply(null,arguments)},NS=l._IsInf=function(){return(NS=l._IsInf=l.asm.IsInf).apply(null,arguments)},kS=l._IsNan=function(){return(kS=l._IsNan=l.asm.IsNan).apply(null,arguments)},TS=l._LRN=function(){return(TS=l._LRN=l.asm.LRN).apply(null,arguments)},_S=l._LRNGrad=function(){return(_S=l._LRNGrad=l.asm.LRNGrad).apply(null,arguments)},ES=l._LeakyRelu=function(){return(ES=l._LeakyRelu=l.asm.LeakyRelu).apply(null,arguments)},AS=l._Less=function(){return(AS=l._Less=l.asm.Less).apply(null,arguments)},DS=l._LessEqual=function(){return(DS=l._LessEqual=l.asm.LessEqual).apply(null,arguments)},$S=l._LinSpace=function(){return($S=l._LinSpace=l.asm.LinSpace).apply(null,arguments)},RS=l._Log=function(){return(RS=l._Log=l.asm.Log).apply(null,arguments)},FS=l._Log1p=function(){return(FS=l._Log1p=l.asm.Log1p).apply(null,arguments)},OS=l._LogicalAnd=function(){return(OS=l._LogicalAnd=l.asm.LogicalAnd).apply(null,arguments)},PS=l._LogicalNot=function(){return(PS=l._LogicalNot=l.asm.LogicalNot).apply(null,arguments)},MS=l._LogicalOr=function(){return(MS=l._LogicalOr=l.asm.LogicalOr).apply(null,arguments)},LS=l._LogicalXor=function(){return(LS=l._LogicalXor=l.asm.LogicalXor).apply(null,arguments)},zS=l._Max=function(){return(zS=l._Max=l.asm.Max).apply(null,arguments)},BS=l._MaxPool=function(){return(BS=l._MaxPool=l.asm.MaxPool).apply(null,arguments)},VS=l._MaxPool3D=function(){return(VS=l._MaxPool3D=l.asm.MaxPool3D).apply(null,arguments)},GS=l._MaxPool3DGrad=function(){return(GS=l._MaxPool3DGrad=l.asm.MaxPool3DGrad).apply(null,arguments)},WS=l._MaxPoolGrad=function(){return(WS=l._MaxPoolGrad=l.asm.MaxPoolGrad).apply(null,arguments)},US=l._MaxPoolWithArgmax=function(){return(US=l._MaxPoolWithArgmax=l.asm.MaxPoolWithArgmax).apply(null,arguments)},HS=l._Maximum=function(){return(HS=l._Maximum=l.asm.Maximum).apply(null,arguments)},qS=l._Mean=function(){return(qS=l._Mean=l.asm.Mean).apply(null,arguments)},KS=l._Min=function(){return(KS=l._Min=l.asm.Min).apply(null,arguments)},jS=l._Minimum=function(){return(jS=l._Minimum=l.asm.Minimum).apply(null,arguments)},XS=l._MirrorPad=function(){return(XS=l._MirrorPad=l.asm.MirrorPad).apply(null,arguments)},YS=l._Mod=function(){return(YS=l._Mod=l.asm.Mod).apply(null,arguments)},ZS=l._Multinomial=function(){return(ZS=l._Multinomial=l.asm.Multinomial).apply(null,arguments)},JS=l._Multiply=function(){return(JS=l._Multiply=l.asm.Multiply).apply(null,arguments)},QS=l._Neg=function(){return(QS=l._Neg=l.asm.Neg).apply(null,arguments)},t0=l._NonMaxSuppressionV3=function(){return(t0=l._NonMaxSuppressionV3=l.asm.NonMaxSuppressionV3).apply(null,arguments)},e0=l._NonMaxSuppressionV4=function(){return(e0=l._NonMaxSuppressionV4=l.asm.NonMaxSuppressionV4).apply(null,arguments)},Lg=l._NonMaxSuppressionV5=function(){return(Lg=l._NonMaxSuppressionV5=l.asm.NonMaxSuppressionV5).apply(null,arguments)},zg=l._NotEqual=function(){return(zg=l._NotEqual=l.asm.NotEqual).apply(null,arguments)},Qd=l._OneHot=function(){return(Qd=l._OneHot=l.asm.OneHot).apply(null,arguments)},r0=l._PadV2=function(){return(r0=l._PadV2=l.asm.PadV2).apply(null,arguments)},n0=l._Pow=function(){return(n0=l._Pow=l.asm.Pow).apply(null,arguments)},Dp=l._Prelu=function(){return(Dp=l._Prelu=l.asm.Prelu).apply(null,arguments)},Bg=l._Prod=function(){return(Bg=l._Prod=l.asm.Prod).apply(null,arguments)},$p=l._RealDiv=function(){return($p=l._RealDiv=l.asm.RealDiv).apply(null,arguments)},Rp=l._Reciprocal=function(){return(Rp=l._Reciprocal=l.asm.Reciprocal).apply(null,arguments)},o0=l._Relu=function(){return(o0=l._Relu=l.asm.Relu).apply(null,arguments)},j=l._Relu6=function(){return(j=l._Relu6=l.asm.Relu6).apply(null,arguments)},ut=l._ResizeBilinear=function(){return(ut=l._ResizeBilinear=l.asm.ResizeBilinear).apply(null,arguments)},Ft=l._ResizeBilinearGrad=function(){return(Ft=l._ResizeBilinearGrad=l.asm.ResizeBilinearGrad).apply(null,arguments)},pe=l._ResizeNearestNeighbor=function(){return(pe=l._ResizeNearestNeighbor=l.asm.ResizeNearestNeighbor).apply(null,arguments)},Xe=l._ResizeNearestNeighborGrad=function(){return(Xe=l._ResizeNearestNeighborGrad=l.asm.ResizeNearestNeighborGrad).apply(null,arguments)},Ye=l._Reverse=function(){return(Ye=l._Reverse=l.asm.Reverse).apply(null,arguments)},se=l._RotateWithOffset=function(){return(se=l._RotateWithOffset=l.asm.RotateWithOffset).apply(null,arguments)},ne=l._Round=function(){return(ne=l._Round=l.asm.Round).apply(null,arguments)},br=l._Rsqrt=function(){return(br=l._Rsqrt=l.asm.Rsqrt).apply(null,arguments)},oo=l._ScatterNd=function(){return(oo=l._ScatterNd=l.asm.ScatterNd).apply(null,arguments)},Ea=l._SearchSorted=function(){return(Ea=l._SearchSorted=l.asm.SearchSorted).apply(null,arguments)},Vg=l._SelectV2=function(){return(Vg=l._SelectV2=l.asm.SelectV2).apply(null,arguments)},th=l._Selu=function(){return(th=l._Selu=l.asm.Selu).apply(null,arguments)},s0=l._Sigmoid=function(){return(s0=l._Sigmoid=l.asm.Sigmoid).apply(null,arguments)},sn=l._Sign=function(){return(sn=l._Sign=l.asm.Sign).apply(null,arguments)},jl=l._Sin=function(){return(jl=l._Sin=l.asm.Sin).apply(null,arguments)},Gg=l._Sinh=function(){return(Gg=l._Sinh=l.asm.Sinh).apply(null,arguments)},YH=l._Softmax=function(){return(YH=l._Softmax=l.asm.Softmax).apply(null,arguments)},ZH=l._Softplus=function(){return(ZH=l._Softplus=l.asm.Softplus).apply(null,arguments)},JH=l._SparseFillEmptyRows=function(){return(JH=l._SparseFillEmptyRows=l.asm.SparseFillEmptyRows).apply(null,arguments)},QH=l._SparseReshape=function(){return(QH=l._SparseReshape=l.asm.SparseReshape).apply(null,arguments)},tq=l._SparseSegmentReduction=function(){return(tq=l._SparseSegmentReduction=l.asm.SparseSegmentReduction).apply(null,arguments)},eq=l._SparseToDense=function(){return(eq=l._SparseToDense=l.asm.SparseToDense).apply(null,arguments)},rq=l._Sqrt=function(){return(rq=l._Sqrt=l.asm.Sqrt).apply(null,arguments)},nq=l._Square=function(){return(nq=l._Square=l.asm.Square).apply(null,arguments)},oq=l._SquaredDifference=function(){return(oq=l._SquaredDifference=l.asm.SquaredDifference).apply(null,arguments)},sq=l._Step=function(){return(sq=l._Step=l.asm.Step).apply(null,arguments)},iq=l._StridedSlice=function(){return(iq=l._StridedSlice=l.asm.StridedSlice).apply(null,arguments)},aq=l._Sub=function(){return(aq=l._Sub=l.asm.Sub).apply(null,arguments)},lq=l._Sum=function(){return(lq=l._Sum=l.asm.Sum).apply(null,arguments)},uq=l._Tan=function(){return(uq=l._Tan=l.asm.Tan).apply(null,arguments)},cq=l._Tanh=function(){return(cq=l._Tanh=l.asm.Tanh).apply(null,arguments)},pq=l._TensorScatterUpdate=function(){return(pq=l._TensorScatterUpdate=l.asm.TensorScatterUpdate).apply(null,arguments)},mq=l._Tile=function(){return(mq=l._Tile=l.asm.Tile).apply(null,arguments)},fq=l._TopK=function(){return(fq=l._TopK=l.asm.TopK).apply(null,arguments)},dq=l._Transform=function(){return(dq=l._Transform=l.asm.Transform).apply(null,arguments)},hq=l._Transpose=function(){return(hq=l._Transpose=l.asm.Transpose).apply(null,arguments)},gq=l.__FusedMatMul=function(){return(gq=l.__FusedMatMul=l.asm._FusedMatMul).apply(null,arguments)},xq=l._malloc=function(){return(xq=l._malloc=l.asm.malloc).apply(null,arguments)},yq=l._free=function(){return(yq=l._free=l.asm.free).apply(null,arguments)},bq=l.__emscripten_tls_init=function(){return(bq=l.__emscripten_tls_init=l.asm._emscripten_tls_init).apply(null,arguments)},Wg=l._pthread_self=function(){return(Wg=l._pthread_self=l.asm.pthread_self).apply(null,arguments)},wq=l.___errno_location=function(){return(wq=l.___errno_location=l.asm.__errno_location).apply(null,arguments)},l_=l.__emscripten_thread_init=function(){return(l_=l.__emscripten_thread_init=l.asm._emscripten_thread_init).apply(null,arguments)},Iq=l.__emscripten_thread_crashed=function(){return(Iq=l.__emscripten_thread_crashed=l.asm._emscripten_thread_crashed).apply(null,arguments)},Cq=l._emscripten_main_thread_process_queued_calls=function(){return(Cq=l._emscripten_main_thread_process_queued_calls=l.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},vq=l._emscripten_main_browser_thread_id=function(){return(vq=l._emscripten_main_browser_thread_id=l.asm.emscripten_main_browser_thread_id).apply(null,arguments)},u_=l._emscripten_run_in_main_runtime_thread_js=function(){return(u_=l._emscripten_run_in_main_runtime_thread_js=l.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},Sq=l._emscripten_dispatch_to_thread_=function(){return(Sq=l._emscripten_dispatch_to_thread_=l.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},c_=l.__emscripten_proxy_execute_task_queue=function(){return(c_=l.__emscripten_proxy_execute_task_queue=l.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},i0=l.__emscripten_thread_free_data=function(){return(i0=l.__emscripten_thread_free_data=l.asm._emscripten_thread_free_data).apply(null,arguments)},p_=l.__emscripten_thread_exit=function(){return(p_=l.__emscripten_thread_exit=l.asm._emscripten_thread_exit).apply(null,arguments)},m_=l._emscripten_stack_set_limits=function(){return(m_=l._emscripten_stack_set_limits=l.asm.emscripten_stack_set_limits).apply(null,arguments)},a0=l.stackSave=function(){return(a0=l.stackSave=l.asm.stackSave).apply(null,arguments)},Ug=l.stackRestore=function(){return(Ug=l.stackRestore=l.asm.stackRestore).apply(null,arguments)},Hg=l.stackAlloc=function(){return(Hg=l.stackAlloc=l.asm.stackAlloc).apply(null,arguments)},Nq=l.dynCall_iijjiiii=function(){return(Nq=l.dynCall_iijjiiii=l.asm.dynCall_iijjiiii).apply(null,arguments)},kq=l.dynCall_jiji=function(){return(kq=l.dynCall_jiji=l.asm.dynCall_jiji).apply(null,arguments)};l.keepRuntimeAlive=Wo,l.wasmMemory=it,l.cwrap=fv,l.ExitStatus=sc,l.PThread=Xt;var qg;_a=function M(){qg||f_(),qg||(_a=M)};function f_(M){if(M=M||d,ql>0)return;if(I){c(l),Ar(),startWorker(l);return}if(Ei(),ql>0)return;function U(){qg||(qg=!0,l.calledRun=!0,!gt&&(Ar(),c(l),l.onRuntimeInitialized&&l.onRuntimeInitialized(),Ta()))}l.setStatus?(l.setStatus("Running..."),setTimeout(function(){setTimeout(function(){l.setStatus("")},1),U()},1)):U()}if(l.preInit)for(typeof l.preInit=="function"&&(l.preInit=[l.preInit]);l.preInit.length>0;)l.preInit.pop()();f_();var Kg;m&&(Kg={uncaughtException:process.listeners("uncaughtException").filter(function(M){return!m.uncaughtException.indexOf(M)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(M){return!m.unhandledRejection.indexOf(M)>-1})});var jg;if(typeof WasmBackendModule!="undefined")jg=WasmBackendModule;else if(typeof t!="undefined")jg=t;else throw new Error("Could not find wasm module in post.js");if(Kg){var Tq=jg._dispose;jg._dispose=function(){Tq(),Kg.uncaughtException.forEach(function(M){process.removeListener("uncaughtException",M)}),Kg.unhandledRejection.forEach(function(M){process.removeListener("unhandledRejection",M)})}}return t.ready}})();typeof EC=="object"&&typeof Z1=="object"?Z1.exports=Y1:typeof define=="function"&&define.amd?define([],function(){return Y1}):typeof EC=="object"&&(EC.WasmBackendModuleThreadedSimd=Y1)});var GH=wr((Mrr,VH)=>{VH.exports.wasmWorkerContents=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
| ");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`});var WH=wr((AC,Q1)=>{var J1=(()=>{var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(t){t=t||{};var e=typeof t!="undefined"?t:{},n,o;e.ready=new Promise(function(j,ut){n=j,o=ut});var s;typeof process!="undefined"&&process.listeners&&(s={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var i=Object.assign({},e),a=[],u="./this.program",l=(j,ut)=>{throw ut},c=typeof window=="object",p=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f="";function d(j){return e.locateFile?e.locateFile(j,f):f+j}var h,g,x,b;function w(j){if(j instanceof _p)return;A("exiting due to exception: "+j)}if(m){var I=pw(),N=X1();p?f=N.dirname(f)+"/":f=__dirname+"/",h=(j,ut)=>(j=Ei(j)?new URL(j):N.normalize(j),I.readFileSync(j,ut?void 0:"utf8")),x=j=>{var ut=h(j,!0);return ut.buffer||(ut=new Uint8Array(ut)),ut},g=(j,ut,Ft)=>{j=Ei(j)?new URL(j):N.normalize(j),I.readFile(j,function(pe,Xe){pe?Ft(pe):ut(Xe.buffer)})},process.argv.length>1&&(u=process.argv[1].replace(/\\/g,"/")),a=process.argv.slice(2),process.on("uncaughtException",function(j){if(!(j instanceof _p))throw j}),process.on("unhandledRejection",function(j){throw j}),l=(j,ut)=>{if(fe())throw process.exitCode=j,ut;w(ut),process.exit(j)},e.inspect=function(){return"[Emscripten Module object]"}}else(c||p)&&(p?f=self.location.href:typeof document!="undefined"&&document.currentScript&&(f=document.currentScript.src),r&&(f=r),f.indexOf("blob:")!==0?f=f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):f="",h=j=>{var ut=new XMLHttpRequest;return ut.open("GET",j,!1),ut.send(null),ut.responseText},p&&(x=j=>{var ut=new XMLHttpRequest;return ut.open("GET",j,!1),ut.responseType="arraybuffer",ut.send(null),new Uint8Array(ut.response)}),g=(j,ut,Ft)=>{var pe=new XMLHttpRequest;pe.open("GET",j,!0),pe.responseType="arraybuffer",pe.onload=()=>{if(pe.status==200||pe.status==0&&pe.response){ut(pe.response);return}Ft()},pe.onerror=Ft,pe.send(null)},b=j=>document.title=j);var E=e.print||console.log.bind(console),A=e.printErr||console.warn.bind(console);Object.assign(e,i),i=null,e.arguments&&(a=e.arguments),e.thisProgram&&(u=e.thisProgram),e.quit&&(l=e.quit);var D=4,F;e.wasmBinary&&(F=e.wasmBinary);var P=e.noExitRuntime||!0;typeof WebAssembly!="object"&&Qr("no native wasm support detected");var V,G=!1,W;function q(j,ut){j||Qr(ut)}var H=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function K(j,ut,Ft){ut>>>=0;for(var pe=ut+Ft,Xe=ut;j[Xe]&&!(Xe>=pe);)++Xe;if(Xe-ut>16&&j.buffer&&H)return H.decode(j.subarray(ut,Xe));for(var Ye="";ut<Xe;){var se=j[ut++];if(!(se&128)){Ye+=String.fromCharCode(se);continue}var ne=j[ut++]&63;if((se&224)==192){Ye+=String.fromCharCode((se&31)<<6|ne);continue}var br=j[ut++]&63;if((se&240)==224?se=(se&15)<<12|ne<<6|br:se=(se&7)<<18|ne<<12|br<<6|j[ut++]&63,se<65536)Ye+=String.fromCharCode(se);else{var oo=se-65536;Ye+=String.fromCharCode(55296|oo>>10,56320|oo&1023)}}return Ye}function X(j,ut){return j>>>=0,j?K(at,j,ut):""}function Z(j,ut,Ft,pe){if(Ft>>>=0,!(pe>0))return 0;for(var Xe=Ft,Ye=Ft+pe-1,se=0;se<j.length;++se){var ne=j.charCodeAt(se);if(ne>=55296&&ne<=57343){var br=j.charCodeAt(++se);ne=65536+((ne&1023)<<10)|br&1023}if(ne<=127){if(Ft>=Ye)break;ut[Ft++>>>0]=ne}else if(ne<=2047){if(Ft+1>=Ye)break;ut[Ft++>>>0]=192|ne>>6,ut[Ft++>>>0]=128|ne&63}else if(ne<=65535){if(Ft+2>=Ye)break;ut[Ft++>>>0]=224|ne>>12,ut[Ft++>>>0]=128|ne>>6&63,ut[Ft++>>>0]=128|ne&63}else{if(Ft+3>=Ye)break;ut[Ft++>>>0]=240|ne>>18,ut[Ft++>>>0]=128|ne>>12&63,ut[Ft++>>>0]=128|ne>>6&63,ut[Ft++>>>0]=128|ne&63}}return ut[Ft>>>0]=0,Ft-Xe}function et(j,ut,Ft){return Z(j,at,ut,Ft)}var nt,st,at,ot,it,mt,gt,Ct,Rt;function Dt(j){nt=j,e.HEAP8=st=new Int8Array(j),e.HEAP16=ot=new Int16Array(j),e.HEAP32=mt=new Int32Array(j),e.HEAPU8=at=new Uint8Array(j),e.HEAPU16=it=new Uint16Array(j),e.HEAPU32=gt=new Uint32Array(j),e.HEAPF32=Ct=new Float32Array(j),e.HEAPF64=Rt=new Float64Array(j)}var Ht=e.INITIAL_MEMORY||16777216,qt,ce=[],ge=[],re=[],xe=!1;function fe(){return P}function Ae(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)lr(e.preRun.shift());_a(ce)}function De(){xe=!0,_a(ge)}function Ln(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Vr(e.postRun.shift());_a(re)}function lr(j){ce.unshift(j)}function eo(j){ge.unshift(j)}function Vr(j){re.unshift(j)}var je=0,Gr=null,Wr=null;function ro(j){je++,e.monitorRunDependencies&&e.monitorRunDependencies(je)}function no(j){if(je--,e.monitorRunDependencies&&e.monitorRunDependencies(je),je==0&&(Gr!==null&&(clearInterval(Gr),Gr=null),Wr)){var ut=Wr;Wr=null,ut()}}function Qr(j){e.onAbort&&e.onAbort(j),j="Aborted("+j+")",A(j),G=!0,W=1,j+=". Build with -sASSERTIONS for more info.";var ut=new WebAssembly.RuntimeError(j);throw o(ut),ut}var ka="data:application/octet-stream;base64,";function Wo(j){return j.startsWith(ka)}function Ei(j){return j.startsWith("file://")}var Ar;Ar="tfjs-backend-wasm.wasm",Wo(Ar)||(Ar=d(Ar));function Ta(j){try{if(j==Ar&&F)return new Uint8Array(F);if(x)return x(j);throw"both async and sync fetching of the wasm failed"}catch(ut){Qr(ut)}}function qd(){if(!F&&(c||p)){if(typeof fetch=="function"&&!Ei(Ar))return fetch(Ar,{credentials:"same-origin"}).then(function(j){if(!j.ok)throw"failed to load wasm binary file at '"+Ar+"'";return j.arrayBuffer()}).catch(function(){return Ta(Ar)});if(g)return new Promise(function(j,ut){g(Ar,function(Ft){j(new Uint8Array(Ft))},ut)})}return Promise.resolve().then(function(){return Ta(Ar)})}function Kd(){var j={env:jd,wasi_snapshot_preview1:jd};function ut(se,ne){var br=se.exports;e.asm=br,V=e.asm.memory,Dt(V.buffer),qt=e.asm.__indirect_function_table,eo(e.asm.__wasm_call_ctors),no("wasm-instantiate")}ro("wasm-instantiate");function Ft(se){ut(se.instance)}function pe(se){return qd().then(function(ne){return WebAssembly.instantiate(ne,j)}).then(function(ne){return ne}).then(se,function(ne){A("failed to asynchronously prepare wasm: "+ne),Qr(ne)})}function Xe(){return!F&&typeof WebAssembly.instantiateStreaming=="function"&&!Wo(Ar)&&!Ei(Ar)&&!m&&typeof fetch=="function"?fetch(Ar,{credentials:"same-origin"}).then(function(se){var ne=WebAssembly.instantiateStreaming(se,j);return ne.then(Ft,function(br){return A("wasm streaming compile failed: "+br),A("falling back to ArrayBuffer instantiation"),pe(Ft)})}):pe(Ft)}if(e.instantiateWasm)try{var Ye=e.instantiateWasm(j,ut);return Ye}catch(se){A("Module.instantiateWasm callback failed with error: "+se),o(se)}return Xe().catch(o),{}}var o_,ql;function _p(j){this.name="ExitStatus",this.message="Program terminated with exit("+j+")",this.status=j}function _a(j){for(;j.length>0;)j.shift()(e)}function $C(){Qr("")}function Cg(){return 4294901760}function oc(){return Cg()}function RC(j,ut,Ft){at.copyWithin(j>>>0,ut>>>0,ut+Ft>>>0)}function vg(j){try{return V.grow(j-nt.byteLength+65535>>>16),Dt(V.buffer),1}catch(ut){}}function Ep(j){var ut=at.length;j=j>>>0;var Ft=Cg();if(j>Ft)return!1;let pe=(br,oo)=>br+(oo-br%oo)%oo;for(var Xe=1;Xe<=4;Xe*=2){var Ye=ut*(1+.2/Xe);Ye=Math.min(Ye,j+100663296);var se=Math.min(Ft,pe(Math.max(j,Ye),65536)),ne=vg(se);if(ne)return!0}return!1}var tn={varargs:void 0,get:function(){tn.varargs+=4;var j=mt[tn.varargs-4>>>2];return j},getStr:function(j){var ut=X(j);return ut}};function Sg(j){return 52}function FC(j,ut,Ft,pe,Xe){return 70}var OC=[null,[],[]];function s_(j,ut){var Ft=OC[j];ut===0||ut===10?((j===1?E:A)(K(Ft,0)),Ft.length=0):Ft.push(ut)}function i_(j,ut,Ft,pe){for(var Xe=0,Ye=0;Ye<Ft;Ye++){var se=gt[ut>>>2],ne=gt[ut+4>>>2];ut+=8;for(var br=0;br<ne;br++)s_(j,at[se+br>>>0]);Xe+=ne}return gt[pe>>>2]=Xe,0}function Ng(j){var ut=e["_"+j];return ut}function sc(j,ut){st.set(j,ut>>>0)}function PC(j,ut,Ft,pe,Xe){var Ye={string:sn=>{var jl=0;if(sn!=null&&sn!==0){var Gg=(sn.length<<2)+1;jl=Qd(Gg),et(sn,jl,Gg)}return jl},array:sn=>{var jl=Qd(sn.length);return sc(sn,jl),jl}};function se(sn){return ut==="string"?X(sn):ut==="boolean"?!!sn:sn}var ne=Ng(j),br=[],oo=0;if(pe)for(var Ea=0;Ea<pe.length;Ea++){var Vg=Ye[Ft[Ea]];Vg?(oo===0&&(oo=Lg()),br[Ea]=Vg(pe[Ea])):br[Ea]=pe[Ea]}var th=ne.apply(null,br);function s0(sn){return oo!==0&&zg(oo),se(sn)}return th=s0(th),th}function MC(j,ut,Ft,pe){Ft=Ft||[];var Xe=Ft.every(se=>se==="number"||se==="boolean"),Ye=ut!=="string";return Ye&&Xe&&!pe?Ng(j):function(){return PC(j,ut,Ft,arguments,pe)}}var jd={abort:$C,emscripten_get_heap_max:oc,emscripten_memcpy_big:RC,emscripten_resize_heap:Ep,fd_close:Sg,fd_seek:FC,fd_write:i_},LC=Kd(),kg=e.___wasm_call_ctors=function(){return(kg=e.___wasm_call_ctors=e.asm.__wasm_call_ctors).apply(null,arguments)},Tg=e._init=function(){return(Tg=e._init=e.asm.init).apply(null,arguments)},zC=e._init_with_threads_count=function(){return(zC=e._init_with_threads_count=e.asm.init_with_threads_count).apply(null,arguments)},_g=e._get_threads_count=function(){return(_g=e._get_threads_count=e.asm.get_threads_count).apply(null,arguments)},BC=e._register_tensor=function(){return(BC=e._register_tensor=e.asm.register_tensor).apply(null,arguments)},Xt=e._dispose_data=function(){return(Xt=e._dispose_data=e.asm.dispose_data).apply(null,arguments)},Xd=e._dispose=function(){return(Xd=e._dispose=e.asm.dispose).apply(null,arguments)},VC=e._Abs=function(){return(VC=e._Abs=e.asm.Abs).apply(null,arguments)},Eg=e._Acos=function(){return(Eg=e._Acos=e.asm.Acos).apply(null,arguments)},Ap=e._Acosh=function(){return(Ap=e._Acosh=e.asm.Acosh).apply(null,arguments)},GC=e._Add=function(){return(GC=e._Add=e.asm.Add).apply(null,arguments)},WC=e._AddN=function(){return(WC=e._AddN=e.asm.AddN).apply(null,arguments)},UC=e._All=function(){return(UC=e._All=e.asm.All).apply(null,arguments)},HC=e._Any=function(){return(HC=e._Any=e.asm.Any).apply(null,arguments)},qC=e._ArgMax=function(){return(qC=e._ArgMax=e.asm.ArgMax).apply(null,arguments)},Ag=e._ArgMin=function(){return(Ag=e._ArgMin=e.asm.ArgMin).apply(null,arguments)},Dg=e._Asin=function(){return(Dg=e._Asin=e.asm.Asin).apply(null,arguments)},KC=e._Asinh=function(){return(KC=e._Asinh=e.asm.Asinh).apply(null,arguments)},jC=e._Atan=function(){return(jC=e._Atan=e.asm.Atan).apply(null,arguments)},XC=e._Atan2=function(){return(XC=e._Atan2=e.asm.Atan2).apply(null,arguments)},Yd=e._Atanh=function(){return(Yd=e._Atanh=e.asm.Atanh).apply(null,arguments)},YC=e._AvgPool=function(){return(YC=e._AvgPool=e.asm.AvgPool).apply(null,arguments)},ZC=e._AvgPool3D=function(){return(ZC=e._AvgPool3D=e.asm.AvgPool3D).apply(null,arguments)},JC=e._AvgPool3DGrad=function(){return(JC=e._AvgPool3DGrad=e.asm.AvgPool3DGrad).apply(null,arguments)},ic=e._AvgPoolGrad=function(){return(ic=e._AvgPoolGrad=e.asm.AvgPoolGrad).apply(null,arguments)},QC=e._BatchMatMul=function(){return(QC=e._BatchMatMul=e.asm.BatchMatMul).apply(null,arguments)},tv=e._Bincount=function(){return(tv=e._Bincount=e.asm.Bincount).apply(null,arguments)},$g=e._BitwiseAnd=function(){return($g=e._BitwiseAnd=e.asm.BitwiseAnd).apply(null,arguments)},ev=e._Ceil=function(){return(ev=e._Ceil=e.asm.Ceil).apply(null,arguments)},Zd=e._ClipByValue=function(){return(Zd=e._ClipByValue=e.asm.ClipByValue).apply(null,arguments)},rv=e._Conv2D=function(){return(rv=e._Conv2D=e.asm.Conv2D).apply(null,arguments)},nv=e._Conv2DBackpropInput=function(){return(nv=e._Conv2DBackpropInput=e.asm.Conv2DBackpropInput).apply(null,arguments)},ov=e._Conv3D=function(){return(ov=e._Conv3D=e.asm.Conv3D).apply(null,arguments)},Kl=e._Conv3DBackpropFilterV2=function(){return(Kl=e._Conv3DBackpropFilterV2=e.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Jd=e._Conv3DBackpropInputV2=function(){return(Jd=e._Conv3DBackpropInputV2=e.asm.Conv3DBackpropInputV2).apply(null,arguments)},sv=e._Cos=function(){return(sv=e._Cos=e.asm.Cos).apply(null,arguments)},iv=e._Cosh=function(){return(iv=e._Cosh=e.asm.Cosh).apply(null,arguments)},av=e._CropAndResize=function(){return(av=e._CropAndResize=e.asm.CropAndResize).apply(null,arguments)},lv=e._Cumprod=function(){return(lv=e._Cumprod=e.asm.Cumprod).apply(null,arguments)},Rg=e._Cumsum=function(){return(Rg=e._Cumsum=e.asm.Cumsum).apply(null,arguments)},Fg=e._DenseBincount=function(){return(Fg=e._DenseBincount=e.asm.DenseBincount).apply(null,arguments)},uv=e._DepthToSpace=function(){return(uv=e._DepthToSpace=e.asm.DepthToSpace).apply(null,arguments)},cv=e._DepthwiseConv2dNative=function(){return(cv=e._DepthwiseConv2dNative=e.asm.DepthwiseConv2dNative).apply(null,arguments)},Og=e._Diag=function(){return(Og=e._Diag=e.asm.Diag).apply(null,arguments)},Pg=e._Dilation2D=function(){return(Pg=e._Dilation2D=e.asm.Dilation2D).apply(null,arguments)},pv=e._Dilation2DBackpropFilter=function(){return(pv=e._Dilation2DBackpropFilter=e.asm.Dilation2DBackpropFilter).apply(null,arguments)},mv=e._Dilation2DBackpropInput=function(){return(mv=e._Dilation2DBackpropInput=e.asm.Dilation2DBackpropInput).apply(null,arguments)},fv=e._Elu=function(){return(fv=e._Elu=e.asm.Elu).apply(null,arguments)},dv=e._EluGrad=function(){return(dv=e._EluGrad=e.asm.EluGrad).apply(null,arguments)},Mg=e._Equal=function(){return(Mg=e._Equal=e.asm.Equal).apply(null,arguments)},a_=e._Erf=function(){return(a_=e._Erf=e.asm.Erf).apply(null,arguments)},hv=e._Exp=function(){return(hv=e._Exp=e.asm.Exp).apply(null,arguments)},gv=e._Expm1=function(){return(gv=e._Expm1=e.asm.Expm1).apply(null,arguments)},xv=e._FlipLeftRight=function(){return(xv=e._FlipLeftRight=e.asm.FlipLeftRight).apply(null,arguments)},yv=e._Floor=function(){return(yv=e._Floor=e.asm.Floor).apply(null,arguments)},bv=e._FloorDiv=function(){return(bv=e._FloorDiv=e.asm.FloorDiv).apply(null,arguments)},wv=e._FusedBatchNorm=function(){return(wv=e._FusedBatchNorm=e.asm.FusedBatchNorm).apply(null,arguments)},Iv=e._FusedConv2D=function(){return(Iv=e._FusedConv2D=e.asm.FusedConv2D).apply(null,arguments)},Cv=e._FusedDepthwiseConv2D=function(){return(Cv=e._FusedDepthwiseConv2D=e.asm.FusedDepthwiseConv2D).apply(null,arguments)},vv=e._Gather=function(){return(vv=e._Gather=e.asm.Gather).apply(null,arguments)},Sv=e._GatherNd=function(){return(Sv=e._GatherNd=e.asm.GatherNd).apply(null,arguments)},Nv=e._Greater=function(){return(Nv=e._Greater=e.asm.Greater).apply(null,arguments)},kv=e._GreaterEqual=function(){return(kv=e._GreaterEqual=e.asm.GreaterEqual).apply(null,arguments)},Tv=e._IsFinite=function(){return(Tv=e._IsFinite=e.asm.IsFinite).apply(null,arguments)},_v=e._IsInf=function(){return(_v=e._IsInf=e.asm.IsInf).apply(null,arguments)},Ev=e._IsNan=function(){return(Ev=e._IsNan=e.asm.IsNan).apply(null,arguments)},Av=e._LRN=function(){return(Av=e._LRN=e.asm.LRN).apply(null,arguments)},Dv=e._LRNGrad=function(){return(Dv=e._LRNGrad=e.asm.LRNGrad).apply(null,arguments)},$v=e._LeakyRelu=function(){return($v=e._LeakyRelu=e.asm.LeakyRelu).apply(null,arguments)},Rv=e._Less=function(){return(Rv=e._Less=e.asm.Less).apply(null,arguments)},Fv=e._LessEqual=function(){return(Fv=e._LessEqual=e.asm.LessEqual).apply(null,arguments)},Ov=e._LinSpace=function(){return(Ov=e._LinSpace=e.asm.LinSpace).apply(null,arguments)},Pv=e._Log=function(){return(Pv=e._Log=e.asm.Log).apply(null,arguments)},Mv=e._Log1p=function(){return(Mv=e._Log1p=e.asm.Log1p).apply(null,arguments)},Lv=e._LogicalAnd=function(){return(Lv=e._LogicalAnd=e.asm.LogicalAnd).apply(null,arguments)},zv=e._LogicalNot=function(){return(zv=e._LogicalNot=e.asm.LogicalNot).apply(null,arguments)},Bv=e._LogicalOr=function(){return(Bv=e._LogicalOr=e.asm.LogicalOr).apply(null,arguments)},Vv=e._LogicalXor=function(){return(Vv=e._LogicalXor=e.asm.LogicalXor).apply(null,arguments)},Gv=e._Max=function(){return(Gv=e._Max=e.asm.Max).apply(null,arguments)},Wv=e._MaxPool=function(){return(Wv=e._MaxPool=e.asm.MaxPool).apply(null,arguments)},Uv=e._MaxPool3D=function(){return(Uv=e._MaxPool3D=e.asm.MaxPool3D).apply(null,arguments)},Hv=e._MaxPool3DGrad=function(){return(Hv=e._MaxPool3DGrad=e.asm.MaxPool3DGrad).apply(null,arguments)},qv=e._MaxPoolGrad=function(){return(qv=e._MaxPoolGrad=e.asm.MaxPoolGrad).apply(null,arguments)},Kv=e._MaxPoolWithArgmax=function(){return(Kv=e._MaxPoolWithArgmax=e.asm.MaxPoolWithArgmax).apply(null,arguments)},jv=e._Maximum=function(){return(jv=e._Maximum=e.asm.Maximum).apply(null,arguments)},Xv=e._Mean=function(){return(Xv=e._Mean=e.asm.Mean).apply(null,arguments)},Yv=e._Min=function(){return(Yv=e._Min=e.asm.Min).apply(null,arguments)},Zv=e._Minimum=function(){return(Zv=e._Minimum=e.asm.Minimum).apply(null,arguments)},Jv=e._MirrorPad=function(){return(Jv=e._MirrorPad=e.asm.MirrorPad).apply(null,arguments)},Qv=e._Mod=function(){return(Qv=e._Mod=e.asm.Mod).apply(null,arguments)},tS=e._Multinomial=function(){return(tS=e._Multinomial=e.asm.Multinomial).apply(null,arguments)},eS=e._Multiply=function(){return(eS=e._Multiply=e.asm.Multiply).apply(null,arguments)},rS=e._Neg=function(){return(rS=e._Neg=e.asm.Neg).apply(null,arguments)},nS=e._NonMaxSuppressionV3=function(){return(nS=e._NonMaxSuppressionV3=e.asm.NonMaxSuppressionV3).apply(null,arguments)},oS=e._NonMaxSuppressionV4=function(){return(oS=e._NonMaxSuppressionV4=e.asm.NonMaxSuppressionV4).apply(null,arguments)},sS=e._NonMaxSuppressionV5=function(){return(sS=e._NonMaxSuppressionV5=e.asm.NonMaxSuppressionV5).apply(null,arguments)},iS=e._NotEqual=function(){return(iS=e._NotEqual=e.asm.NotEqual).apply(null,arguments)},aS=e._OneHot=function(){return(aS=e._OneHot=e.asm.OneHot).apply(null,arguments)},lS=e._PadV2=function(){return(lS=e._PadV2=e.asm.PadV2).apply(null,arguments)},uS=e._Pow=function(){return(uS=e._Pow=e.asm.Pow).apply(null,arguments)},cS=e._Prelu=function(){return(cS=e._Prelu=e.asm.Prelu).apply(null,arguments)},pS=e._Prod=function(){return(pS=e._Prod=e.asm.Prod).apply(null,arguments)},mS=e._RealDiv=function(){return(mS=e._RealDiv=e.asm.RealDiv).apply(null,arguments)},fS=e._Reciprocal=function(){return(fS=e._Reciprocal=e.asm.Reciprocal).apply(null,arguments)},dS=e._Relu=function(){return(dS=e._Relu=e.asm.Relu).apply(null,arguments)},hS=e._Relu6=function(){return(hS=e._Relu6=e.asm.Relu6).apply(null,arguments)},gS=e._ResizeBilinear=function(){return(gS=e._ResizeBilinear=e.asm.ResizeBilinear).apply(null,arguments)},xS=e._ResizeBilinearGrad=function(){return(xS=e._ResizeBilinearGrad=e.asm.ResizeBilinearGrad).apply(null,arguments)},yS=e._ResizeNearestNeighbor=function(){return(yS=e._ResizeNearestNeighbor=e.asm.ResizeNearestNeighbor).apply(null,arguments)},bS=e._ResizeNearestNeighborGrad=function(){return(bS=e._ResizeNearestNeighborGrad=e.asm.ResizeNearestNeighborGrad).apply(null,arguments)},wS=e._Reverse=function(){return(wS=e._Reverse=e.asm.Reverse).apply(null,arguments)},IS=e._RotateWithOffset=function(){return(IS=e._RotateWithOffset=e.asm.RotateWithOffset).apply(null,arguments)},CS=e._Round=function(){return(CS=e._Round=e.asm.Round).apply(null,arguments)},vS=e._Rsqrt=function(){return(vS=e._Rsqrt=e.asm.Rsqrt).apply(null,arguments)},SS=e._ScatterNd=function(){return(SS=e._ScatterNd=e.asm.ScatterNd).apply(null,arguments)},NS=e._SearchSorted=function(){return(NS=e._SearchSorted=e.asm.SearchSorted).apply(null,arguments)},kS=e._SelectV2=function(){return(kS=e._SelectV2=e.asm.SelectV2).apply(null,arguments)},TS=e._Selu=function(){return(TS=e._Selu=e.asm.Selu).apply(null,arguments)},_S=e._Sigmoid=function(){return(_S=e._Sigmoid=e.asm.Sigmoid).apply(null,arguments)},ES=e._Sign=function(){return(ES=e._Sign=e.asm.Sign).apply(null,arguments)},AS=e._Sin=function(){return(AS=e._Sin=e.asm.Sin).apply(null,arguments)},DS=e._Sinh=function(){return(DS=e._Sinh=e.asm.Sinh).apply(null,arguments)},$S=e._Softmax=function(){return($S=e._Softmax=e.asm.Softmax).apply(null,arguments)},RS=e._Softplus=function(){return(RS=e._Softplus=e.asm.Softplus).apply(null,arguments)},FS=e._SparseFillEmptyRows=function(){return(FS=e._SparseFillEmptyRows=e.asm.SparseFillEmptyRows).apply(null,arguments)},OS=e._SparseReshape=function(){return(OS=e._SparseReshape=e.asm.SparseReshape).apply(null,arguments)},PS=e._SparseSegmentReduction=function(){return(PS=e._SparseSegmentReduction=e.asm.SparseSegmentReduction).apply(null,arguments)},MS=e._SparseToDense=function(){return(MS=e._SparseToDense=e.asm.SparseToDense).apply(null,arguments)},LS=e._Sqrt=function(){return(LS=e._Sqrt=e.asm.Sqrt).apply(null,arguments)},zS=e._Square=function(){return(zS=e._Square=e.asm.Square).apply(null,arguments)},BS=e._SquaredDifference=function(){return(BS=e._SquaredDifference=e.asm.SquaredDifference).apply(null,arguments)},VS=e._Step=function(){return(VS=e._Step=e.asm.Step).apply(null,arguments)},GS=e._StridedSlice=function(){return(GS=e._StridedSlice=e.asm.StridedSlice).apply(null,arguments)},WS=e._Sub=function(){return(WS=e._Sub=e.asm.Sub).apply(null,arguments)},US=e._Sum=function(){return(US=e._Sum=e.asm.Sum).apply(null,arguments)},HS=e._Tan=function(){return(HS=e._Tan=e.asm.Tan).apply(null,arguments)},qS=e._Tanh=function(){return(qS=e._Tanh=e.asm.Tanh).apply(null,arguments)},KS=e._TensorScatterUpdate=function(){return(KS=e._TensorScatterUpdate=e.asm.TensorScatterUpdate).apply(null,arguments)},jS=e._Tile=function(){return(jS=e._Tile=e.asm.Tile).apply(null,arguments)},XS=e._TopK=function(){return(XS=e._TopK=e.asm.TopK).apply(null,arguments)},YS=e._Transform=function(){return(YS=e._Transform=e.asm.Transform).apply(null,arguments)},ZS=e._Transpose=function(){return(ZS=e._Transpose=e.asm.Transpose).apply(null,arguments)},JS=e.__FusedMatMul=function(){return(JS=e.__FusedMatMul=e.asm._FusedMatMul).apply(null,arguments)},QS=e._malloc=function(){return(QS=e._malloc=e.asm.malloc).apply(null,arguments)},t0=e._free=function(){return(t0=e._free=e.asm.free).apply(null,arguments)},e0=e.___errno_location=function(){return(e0=e.___errno_location=e.asm.__errno_location).apply(null,arguments)},Lg=e.stackSave=function(){return(Lg=e.stackSave=e.asm.stackSave).apply(null,arguments)},zg=e.stackRestore=function(){return(zg=e.stackRestore=e.asm.stackRestore).apply(null,arguments)},Qd=e.stackAlloc=function(){return(Qd=e.stackAlloc=e.asm.stackAlloc).apply(null,arguments)},r0=e.dynCall_iijjiiii=function(){return(r0=e.dynCall_iijjiiii=e.asm.dynCall_iijjiiii).apply(null,arguments)},n0=e.dynCall_jiji=function(){return(n0=e.dynCall_jiji=e.asm.dynCall_jiji).apply(null,arguments)};e.cwrap=MC;var Dp;Wr=function j(){Dp||Bg(),Dp||(Wr=j)};function Bg(j){if(j=j||a,je>0||(Ae(),je>0))return;function ut(){Dp||(Dp=!0,e.calledRun=!0,!G&&(De(),n(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),Ln()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),ut()},1)):ut()}if(e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();Bg();var $p;s&&($p={uncaughtException:process.listeners("uncaughtException").filter(function(j){return!s.uncaughtException.indexOf(j)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(j){return!s.unhandledRejection.indexOf(j)>-1})});var Rp;if(typeof t!="undefined")Rp=t;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Rp=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if($p){var o0=Rp._dispose;Rp._dispose=function(){o0(),$p.uncaughtException.forEach(function(j){process.removeListener("uncaughtException",j)}),$p.unhandledRejection.forEach(function(j){process.removeListener("unhandledRejection",j)})}}return t.ready}})();typeof AC=="object"&&typeof Q1=="object"?Q1.exports=J1:typeof define=="function"&&define.amd?define([],function(){return J1}):typeof AC=="object"&&(AC.WasmBackendModule=J1)});var Da=class{constructor(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}get(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)}set(t,e){this.dataIdsCount++,this.data.set(t,e)}has(t){return this.data.has(t)}delete(t){return this.dataIdsCount--,this.data.delete(t)}numDataIds(){return this.dataIdsCount}},Uo=class{refCount(t){return Bn("refCount")}incRef(t){return Bn("incRef")}timerAvailable(){return!0}time(t){return Bn("time")}read(t){return Bn("read")}readSync(t){return Bn("readSync")}readToGPU(t,e){return Bn("readToGPU")}numDataIds(){return Bn("numDataIds")}disposeData(t,e){return Bn("disposeData")}write(t,e,n){return Bn("write")}move(t,e,n,o,s){return Bn("move")}createTensorFromGPUData(t,e,n){return Bn("createTensorFromGPUData")}memory(){return Bn("memory")}floatPrecision(){return Bn("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return Bn("dispose")}};function Bn(r){throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function g_(r){let t=r.length,e=0;for(;t>0;)e=Math.random()*t|0,t--,Xg(r,t,e)}function Oq(r,t){if(r.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${r.length}Second array length was ${t.length}`);let e=r.length,n=0;for(;e>0;)n=Math.random()*e|0,e--,Xg(r,e,n),Xg(t,e,n)}function Op(r,t,e){return Math.max(r,Math.min(t,e))}function Pq(r){return r%2===0?r:r+1}function Xg(r,t,e){let n=r[t];r[t]=r[e],r[e]=n}function Mq(r){let t=0;for(let e=0;e<r.length;e++)t+=r[e];return t}function Lq(r,t){let e=Math.random();return t*e+(1-e)*r}function zq(r,t){let e=0;for(let n=0;n<r.length;n++){let o=Number(r[n])-Number(t[n]);e+=o*o}return e}function _(r,t){if(!r)throw new Error(typeof t=="string"?t:t())}function Re(r,t,e=""){_(an(r,t),()=>e+` Shapes ${r} and ${t} must match`)}function io(r){_(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function te(r){if(r.length===0)return 1;let t=r[0];for(let e=1;e<r.length;e++)t*=r[e];return t}function Bq(r){return r.length===0}function c0(r,t){if(r===t)return!0;if(r==null||t==null||r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==null&&t[e]!==null&&r[e]!==t[e])return!1;return!0}function an(r,t){if(r===t)return!0;if(r==null||t==null||r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0}function $a(r){return r%1===0}function Vq(r){if(Math.tanh!=null)return Math.tanh(r);if(r===1/0)return 1;if(r===-1/0)return-1;{let t=Math.exp(2*r);return(t-1)/(t+1)}}function Gq(r){let t=Math.ceil(Math.sqrt(r));return[t,Math.ceil(r/t)]}function Wq(r){let t=new Uint32Array(r);for(let e=0;e<r;++e)t[e]=e;return g_(t),t}function lc(r,t){return t<=r.length?r:r+" ".repeat(t-r.length)}function Uq(r,t=o=>0,e,n){return new Promise((o,s)=>{let i=0,a=()=>{if(r()){o();return}i++;let u=t(i);if(e!=null&&i>=e){s();return}n!=null?n(a,u):setTimeout(a,u)};a()})}function Hq(r,t){let e=1,n=-1;for(let s=0;s<r.length;++s)if(r[s]>=0)e*=r[s];else if(r[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(r[s]<0)throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`);if(n===-1){if(t>0&&t!==e)throw Error(`Size(${t}) must match the product of shape ${r}`);return r}if(e===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(t%e!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${e}`);let o=r.slice();return o[n]=t/e,o}function fr(r,t){let e=t.length;return r=r==null?t.map((n,o)=>o):[].concat(r),_(r.every(n=>n>=-e&&n<e),()=>`All values in axis param must be in range [-${e}, ${e}) but got axis ${r}`),_(r.every(n=>$a(n)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(n=>n<0?e+n:n)}function p0(r,t){let e=[],n=[],o=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||o?null:fr(t,r).sort(),i=0;for(let a=0;a<r.length;++a){if(s!=null){if(s[i]===a&&r[a]!==1)throw new Error(`Can't squeeze axis ${a} since its dim '${r[a]}' is not 1`);(s[i]==null||s[i]>a)&&r[a]===1&&(e.push(r[a]),n.push(a)),s[i]<=a&&i++}r[a]!==1&&(e.push(r[a]),n.push(a))}return{newShape:e,keptDims:n}}function m0(r,t){return Yg(r,t)}function Yg(r,t){let e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else if(r==="bool")e=new Uint8Array(t);else if(r==="string")e=new Array(t);else throw new Error(`Unknown data type ${r}`);return e}function f0(r,t){for(let e=0;e<r.length;e++){let n=r[e];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function d0(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function qq(r,t){return!(t==="complex64"||t==="float32"&&r!=="complex64"||t==="int32"&&r!=="float32"&&r!=="complex64"||t==="bool"&&r==="bool")}function Pp(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error(`Unknown dtype ${r}`)}function h0(r){if(r==null)return 0;let t=0;return r.forEach(e=>t+=e.length),t}function Ho(r){return typeof r=="string"||r instanceof String}function x_(r){return typeof r=="boolean"}function y_(r){return typeof r=="number"}function Yl(r){return Array.isArray(r)?Yl(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array||r instanceof Uint8ClampedArray?"int32":y_(r)?"float32":Ho(r)?"string":x_(r)?"bool":"float32"}function Ai(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Mp(r,t){for(let e=t;e<r;++e)if(r%e===0)return e;return r}function Di(r){let t=r.length;if(t<2)return[];let e=new Array(t-1);e[t-2]=r[t-1];for(let n=t-3;n>=0;--n)e[n]=e[n+1]*r[n+1];return e}function b_(r,t,e,n=!1){let o=new Array;if(t.length===1){let s=t[0]*(n?2:1);for(let i=0;i<s;i++)o[i]=e[r+i]}else{let s=t[0],i=t.slice(1),a=i.reduce((u,l)=>u*l)*(n?2:1);for(let u=0;u<s;u++)o[u]=b_(r+u*a,i,e,n)}return o}function ac(r,t,e=!1){if(r.length===0)return t[0];let n=r.reduce((o,s)=>o*s)*(e?2:1);if(n===0)return[];if(n!==t.length)throw new Error(`[${r}] does not match the input size ${t.length}${e?" for a complex tensor":""}.`);return b_(0,r,t,e)}function Kq(r,t){if(Array.isArray(r))return r;if(t==="float32")return r instanceof Float32Array?r:new Float32Array(r);if(t==="int32")return r instanceof Int32Array?r:new Int32Array(r);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(r));throw new Error(`Unknown dtype ${t}`)}function eh(r,t){let e=Lp(r,t);for(let n=0;n<e.length;n++)e[n]=1;return e}function Lp(r,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(r);if(t==="int32")return new Int32Array(r);if(t==="bool")return new Uint8Array(r);throw new Error(`Unknown data type ${t}`)}function jq(r,t){let e=r.reduce((n,o)=>n*o,1);if(t==null||t==="float32")return ac(r,new Float32Array(e));if(t==="int32")return ac(r,new Int32Array(e));if(t==="bool")return ac(r,new Uint8Array(e));throw new Error(`Unknown data type ${t}`)}function Me(r){r.forEach(t=>{_(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function Xq(r,t,e){if(t===0)return 0;if(t===1)return r[0];let n=r[r.length-1];for(let o=0;o<r.length-1;++o)n+=e[o]*r[o];return n}function Yq(r,t,e){if(t===0)return[];if(t===1)return[r];let n=new Array(t);for(let o=0;o<n.length-1;++o)n[o]=Math.floor(r/e[o]),r-=n[o]*e[o];return n[n.length-1]=r,n}function uc(r){return r&&r.then&&typeof r.then=="function"}var w_="tfjsflags",rh=class{constructor(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Jq,this.populateURLFlags()}setPlatform(t,e){this.platform!=null&&(L().getBool("IS_TEST")||L().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`)),this.platformName=t,this.platform=e}registerFlag(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},this.urlFlags[t]!=null){let o=this.urlFlags[t];L().getBool("IS_TEST")||L().getBool("PROD")||console.warn(`Setting feature override from URL ${t}: ${o}.`),this.set(t,o)}}async getAsync(t){return t in this.flags?this.flags[t]:(this.flags[t]=await this.evaluateFlag(t),this.flags[t])}get(t){if(t in this.flags)return this.flags[t];let e=this.evaluateFlag(t);if(uc(e))throw new Error(`Flag ${t} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[t]=e,this.flags[t]}getNumber(t){return this.get(t)}getBool(t){return this.get(t)}getString(t){return this.get(t)}getFlags(){return this.flags}get features(){return this.flags}set(t,e){if(this.flagRegistry[t]==null)throw new Error(`Cannot set flag ${t} as it has not been registered.`);this.flags[t]=e,this.flagRegistry[t].setHook!=null&&this.flagRegistry[t].setHook(e)}evaluateFlag(t){if(this.flagRegistry[t]==null)throw new Error(`Cannot evaluate flag '${t}': no evaluation function found.`);return this.flagRegistry[t].evaluationFn()}setFlags(t){this.flags=Object.assign({},t)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let t=this.getQueryParams(this.global.location.search);w_ in t&&t[w_].split(",").forEach(n=>{let[o,s]=n.split(":");this.urlFlags[o]=tK(o,s)})}};function Jq(r){let t={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(Qq(t,n[0],n[1]),n.join("="))),t}function Qq(r,t,e){r[decodeURIComponent(t)]=decodeURIComponent(e||"")}function tK(r,t){let e=t.toLowerCase();return e==="true"||e==="false"?e==="true":`${+e}`===e?+e:t}function L(){return g0}var g0=null;function I_(r){g0=r}var x0;function y0(){if(x0==null){let r;if(typeof window!="undefined")r=window;else if(typeof global!="undefined")r=global;else if(typeof process!="undefined")r=process;else if(typeof self!="undefined")r=self;else throw new Error("Could not find a global object");x0=r}return x0}function eK(){let r=y0();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function nh(r,t){let e=eK();if(e.has(r))return e.get(r);{let n=t();return e.set(r,n),e.get(r)}}var $i="Abs",qo="Acos",Ko="Acosh",ao="Add",jo="AddN",Ra="All",Fa="Any",Ri="ArgMax",Fi="ArgMin",Xo="Asin",Yo="Asinh",Zo="Atan",Jo="Atanh",Qo="Atan2",ts="AvgPool",Zl="AvgPoolGrad",Oi="AvgPool3D",Jl="AvgPool3DGrad",es="BatchMatMul",Pi="BatchToSpaceND",Oa="Bincount",Pa="BitwiseAnd",C_="BroadcastTo",Ql="BroadcastArgs",xo="Cast",rs="Ceil",yo="ClipByValue",zp="Complex",tu="ComplexAbs",Mi="Concat",ns="Conv2D",Bp="Conv2DBackpropFilter",os="Conv2DBackpropInput",ss="Conv3D",Ma="Conv3DBackpropFilterV2",La="Conv3DBackpropInputV2",is="Cos",as="Cosh",za="Cumprod",ls="Cumsum",Ba="CropAndResize",eu="DenseBincount",Va="DepthToSpace",us="DepthwiseConv2dNative",Vp="DepthwiseConv2dNativeBackpropFilter",Gp="DepthwiseConv2dNativeBackpropInput",ru="Diag",cs="Dilation2D",nu="Dilation2DBackpropInput",ou="Dilation2DBackpropFilter",Zg="Draw",ps="RealDiv",Wp="Einsum",ms="Elu",Ga="EluGrad",fs="Erf",Wa="Equal",ds="Exp",Li="ExpandDims",hs="Expm1",Up="FFT",su="Fill",Ua="FlipLeftRight",gs="Floor",xs="FloorDiv",ys="FusedBatchNorm",zi="GatherV2",Ha="GatherNd",qa="Greater",bs="GreaterEqual",bo="Identity",Hp="IFFT",qp="Imag",ws="IsFinite",Is="IsInf",Cs="IsNan",vs="LeakyRelu",Ka="Less",ja="LessEqual",Xa="LinSpace",Ss="Log",Ns="Log1p",Ya="LogicalAnd",Za="LogicalNot",Ja="LogicalOr",v_="LogicalXor",S_="LogSoftmax",Lmt="LowerBound",ks="LRN",Qa="LRNGrad",zmt="MatrixBandPart",Ts="Max",_s="Maximum",Es="MaxPool",iu="MaxPoolGrad",Bi="MaxPool3D",au="MaxPool3DGrad",lu="MaxPoolWithArgmax",As="Mean",Ds="Min",$s="Minimum",Rs="MirrorPad",Fs="Mod",tl="Multinomial",Os="Multiply",Vi="Neg",el="NotEqual",rl="NonMaxSuppressionV3",nl="NonMaxSuppressionV4",ol="NonMaxSuppressionV5",Gi="OnesLike",Ps="OneHot",Wi="Pack",Ms="PadV2",Bmt="Pool",Ls="Pow",zs="Prelu",Bs="Prod",Kp="RaggedGather",jp="RaggedRange",Xp="RaggedTensorToTensor",uu="Range",Yp="Real",Vs="Reciprocal",Gs="Relu",Ui="Reshape",Ws="ResizeNearestNeighbor",sl="ResizeNearestNeighborGrad",Us="ResizeBilinear",il="ResizeBilinearGrad",Hs="Relu6",qs="Reverse",Ks="Round",js="Rsqrt",al="ScatterNd",ll="TensorScatterUpdate",ul="SearchSorted",Hi="Select",Xs="Selu",qi="Slice",Ys="Sin",Zs="Sinh",Js="Sign",Qs="Sigmoid",ti="Softplus",ei="Sqrt",ri="Sum",Ki="SpaceToBatchND",ji="SplitV",ni="Softmax",cu="SparseFillEmptyRows",cl="SparseReshape",pu="SparseSegmentMean",mu="SparseSegmentSum",pl="SparseToDense",oi="SquaredDifference",fu="Square",cc="StaticRegexReplace",ml="StridedSlice",du="StringNGrams",hu="StringSplit",gu="StringToHashBucketFast",si="Sub",ii="Tan",ai="Tanh",lo="Tile",fl="TopK",dl="Transform",uo="Transpose",xu="Unique",Xi="Unpack",yu="UnsortedSegmentSum",Vmt="UpperBound",Yi="ZerosLike",wo="Step",oh="FromPixels",hl="RotateWithOffset",Zi="_FusedMatMul",Ji="FusedConv2D",Qi="FusedDepthwiseConv2D";function ta(...r){L().getBool("IS_TEST")||L().getBool("PROD")||console.warn(...r)}function rK(...r){L().getBool("IS_TEST")||L().getBool("PROD")||console.log(...r)}var Zp=nh("kernelRegistry",()=>new Map),sh=nh("gradRegistry",()=>new Map);function ih(r,t){let e=w0(r,t);return Zp.get(e)}function b0(r){return sh.get(r)}function Jg(r){let t=Zp.entries(),e=[];for(;;){let{done:n,value:o}=t.next();if(n)break;let[s,i]=o,[a]=s.split("_");a===r&&e.push(i)}return e}function pc(r){let{kernelName:t,backendName:e}=r,n=w0(t,e);Zp.has(n)&&ta(`The kernel '${t}' for backend '${e}' is already registered`),Zp.set(n,r)}function k_(r){let{kernelName:t}=r;sh.has(t)&&L().getBool("DEBUG")&&ta(`Overriding the gradient for '${t}'`),sh.set(t,r)}function qmt(r,t){let e=w0(r,t);if(!Zp.has(e))throw new Error(`The kernel '${r}' for backend '${t}' is not registered`);Zp.delete(e)}function Kmt(r){if(!sh.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);sh.delete(r)}function jmt(r,t){Jg(r).forEach(n=>{let o=Object.assign({},n,{backendName:t});pc(o)})}function w0(r,t){return`${t}_${r}`}var y={};Kt(y,{arraysEqual:()=>an,arraysEqualWithNull:()=>c0,assert:()=>_,assertNonNegativeIntegerDimensions:()=>Me,assertNonNull:()=>io,assertShapesMatch:()=>Re,bytesFromStringArray:()=>h0,bytesPerElement:()=>Pp,checkConversionForErrors:()=>f0,clamp:()=>Op,computeStrides:()=>Di,convertBackendValuesAndArrayBuffer:()=>Kq,createScalarValue:()=>uK,createShuffledIndices:()=>Wq,decodeString:()=>em,distSquared:()=>zq,encodeString:()=>wu,fetch:()=>pK,fingerPrint64:()=>lK,flatten:()=>ui,getArrayFromDType:()=>Yg,getTypedArrayFromDType:()=>m0,hasEncodingLoss:()=>qq,hexToLong:()=>ah,indexToLoc:()=>Yq,inferDtype:()=>Yl,inferFromImplicitShape:()=>Hq,isBoolean:()=>x_,isFunction:()=>Ai,isInt:()=>$a,isNumber:()=>y_,isPromise:()=>uc,isScalarShape:()=>Bq,isString:()=>Ho,isTypedArray:()=>or,isValidDtype:()=>d0,locToIndex:()=>Xq,makeOnesTypedArray:()=>eh,makeZerosNestedTypedArray:()=>jq,makeZerosTypedArray:()=>Lp,nearestDivisor:()=>Mp,nearestLargerEven:()=>Pq,now:()=>gc,parseAxisParam:()=>fr,randUniform:()=>Lq,repeatedTry:()=>Uq,rightPad:()=>lc,shuffle:()=>g_,shuffleCombo:()=>Oq,sizeFromShape:()=>te,sizeToSquarishShape:()=>Gq,squeezeShape:()=>p0,sum:()=>Mq,swap:()=>Xg,tanh:()=>Vq,toNestedArray:()=>ac,toTypedArray:()=>tm});function Qg(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array||r instanceof Uint8ClampedArray}var S0=Xl(M_());var hc=S0.default||S0;function ah(r){return hc.fromString(r,!0,16)}var z_=ah("c3a5c85c97cb3127"),dc=ah("b492b66fbe98f273"),ln=ah("9ae16a3b2f90404f");function v0(r){return r.xor(r.shru(47))}function B_(r,t,e){let n=r.slice(t,t+e);return hc.fromBytes(Array.from(n),!0,!0)}function Le(r,t){return B_(r,t,8)}function L_(r,t){return B_(r,t,4)}function Dr(r,t){return t===0?r:r.shru(t).or(r.shl(64-t))}function bu(r,t,e=ah("9ddfea08eb382d69")){let n=r.xor(t).mul(e);n=n.xor(n.shru(47));let o=t.xor(n).mul(e);return o=o.xor(o.shru(47)),o=o.mul(e),o}function oK(r,t,e,n,o,s){o=o.add(r),s=Dr(s.add(o).add(n),21);let i=o;return o=o.add(t),o=o.add(e),s=s.add(Dr(o,44)),[o.add(n),s.add(i)]}function ex(r,t,e,n){return oK(Le(r,t),Le(r,t+8),Le(r,t+16),Le(r,t+24),e,n)}function sK(r,t=r.length){if(t>=8){let e=ln.add(t*2),n=Le(r,0).add(ln),o=Le(r,t-8),s=Dr(o,37).mul(e).add(n),i=Dr(n,25).add(o).mul(e);return bu(s,i,e)}if(t>=4){let e=ln.add(t*2),n=L_(r,0);return bu(n.shl(3).add(t),L_(r,t-4),e)}if(t>0){let e=r[0],n=r[t>>1],o=r[t-1],s=e+(n<<8),i=t+(o<<2);return v0(ln.mul(s).xor(z_.mul(i))).mul(ln)}return ln}function iK(r,t=r.length){let e=ln.add(t*2),n=Le(r,0).mul(dc),o=Le(r,8),s=Le(r,t-8).mul(e),i=Le(r,t-16).mul(ln);return bu(Dr(n.add(o),43).add(Dr(s,30)).add(i),n.add(Dr(o.add(ln),18)).add(s),e)}function aK(r,t=r.length){let e=ln.add(t*2),n=Le(r,0).mul(ln),o=Le(r,8),s=Le(r,t-8).mul(e),i=Le(r,t-16).mul(ln),a=Dr(n.add(o),43).add(Dr(s,30)).add(i),u=bu(a,n.add(Dr(o.add(ln),18)).add(s),e),l=Le(r,16).mul(e),c=Le(r,24),p=a.add(Le(r,t-32)).mul(e),m=u.add(Le(r,t-24)).mul(e);return bu(Dr(l.add(c),43).add(Dr(p,30)).add(m),l.add(Dr(c.add(n),18)).add(p),e)}function lK(r,t=r.length){let e=hc.fromNumber(81,!0);if(t<=32)return t<=16?sK(r,t):iK(r,t);if(t<=64)return aK(r,t);let n=e,o=e.mul(dc).add(113),s=v0(o.mul(ln).add(113)).mul(ln),i=[hc.UZERO,hc.UZERO],a=[hc.UZERO,hc.UZERO];n=n.mul(ln).add(Le(r,0));let u=0,l=(t-1>>6)*64,c=l+(t-1&63)-63;do n=Dr(n.add(o).add(i[0]).add(Le(r,u+8)),37).mul(dc),o=Dr(o.add(i[1]).add(Le(r,u+48)),42).mul(dc),n=n.xor(a[1]),o=o.add(i[0]).add(Le(r,u+40)),s=Dr(s.add(a[0]),33).mul(dc),i=ex(r,u,i[1].mul(dc),n.add(a[0])),a=ex(r,u+32,s.add(a[1]),o.add(Le(r,u+16))),[s,n]=[n,s],u+=64;while(u!==l);let p=dc.add(s.and(255).shl(1));return u=c,a[0]=a[0].add(t-1&63),i[0]=i[0].add(a[0]),a[0]=a[0].add(i[0]),n=Dr(n.add(o).add(i[0]).add(Le(r,u+8)),37).mul(p),o=Dr(o.add(i[1]).add(Le(r,u+48)),42).mul(p),n=n.xor(a[1].mul(9)),o=o.add(i[0].mul(9).add(Le(r,u+40))),s=Dr(s.add(a[0]),33).mul(p),i=ex(r,u,i[1].mul(p),n.add(a[0])),a=ex(r,u+32,s.add(a[1]),o.add(Le(r,u+16))),[s,n]=[n,s],bu(bu(i[0],a[0],p).add(v0(o).mul(z_)).add(s),bu(i[1],a[1],p).add(n),p)}function uK(r,t){return t==="string"?wu(r):tm([r],t)}function cK(r,t){return r instanceof Float32Array&&t==="float32"||r instanceof Int32Array&&t==="int32"||r instanceof Uint8Array&&t==="bool"}function tm(r,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=ui(r)),L().getBool("DEBUG")&&f0(r,t),cK(r,t))return r;if(t==null||t==="float32"||t==="complex64")return new Float32Array(r);if(t==="int32")return new Int32Array(r);if(t==="bool"){let e=new Uint8Array(r.length);for(let n=0;n<e.length;++n)Math.round(r[n])!==0&&(e[n]=1);return e}else throw new Error(`Unknown data type ${t}`)}function gc(){return L().platform.now()}function pK(r,t){return L().platform.fetch(r,t)}function wu(r,t="utf-8"){return t=t||"utf-8",L().platform.encode(r,t)}function em(r,t="utf-8"){return t=t||"utf-8",L().platform.decode(r,t)}function or(r){return L().platform.isTypedArray!=null?L().platform.isTypedArray(r):Qg(r)}function ui(r,t=[],e=!1){if(t==null&&(t=[]),typeof r=="boolean"||typeof r=="number"||typeof r=="string"||uc(r)||r==null||or(r)&&e)t.push(r);else if(Array.isArray(r)||or(r))for(let n=0;n<r.length;++n)ui(r[n],t,e);else{let n=-1;for(let o of Object.keys(r))/^([1-9]+[0-9]*|0)$/.test(o)&&(n=Math.max(n,Number(o)));for(let o=0;o<=n;o++)ui(r[o],t,e)}return t}var rx=class{constructor(t,e){this.backendTimer=t,this.logger=e,e==null&&(this.logger=new N0)}profileKernel(t,e,n){let o,s=()=>{o=n()},i,a=gc();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(s);else{s();for(let l of o)l.dataSync();i=Promise.resolve({kernelMs:gc()-a})}if(L().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l<o.length;l++){let c=o[l];c.data().then(p=>{mK(p,c.dtype,t)})}return{kernelName:t,outputs:o,inputs:e,timeMs:i.then(l=>l.kernelMs),extraInfo:i.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(t){let{kernelName:e,outputs:n,timeMs:o,inputs:s,extraInfo:i}=t;n.forEach(a=>{Promise.all([a.data(),o,i]).then(u=>{this.logger.logKernelProfile(e,a,u[0],u[1],s,u[2])})})}};function mK(r,t,e){if(t!=="float32")return!1;for(let n=0;n<r.length;n++){let o=r[n];if(isNaN(o)||!isFinite(o))return console.warn(`Found ${o} in the result of '${e}'`),!0}return!1}var N0=class{logKernelProfile(t,e,n,o,s,i){let a=typeof o=="number"?lc(`${o}ms`,9):o.error,u=lc(t,25),l=e.rank,c=e.size,p=lc(e.shape.toString(),14),m="";for(let f in s){let d=s[f];if(d!=null){let h=d.shape||e.shape,g=h.length;m+=`${f}: ${g}D ${g>0?h:""} `}}console.log(`%c${u} %c${a} %c${l}D ${p} %c${c} %c${m} %c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function V_(r,t,e){let n={},o={};for(let u=0;u<t.length;u++)n[t[u].id]=!0;for(let u=0;u<r.length;u++){let l=r[u],c=l.inputs;for(let p in c){let m=c[p],f=!1;for(let d=0;d<t.length;d++)if(n[m.id]){l.outputs.forEach(h=>n[h.id]=!0),f=!0,o[l.id]=!0;break}if(f)break}}let s={};s[e.id]=!0;let i={};for(let u=r.length-1;u>=0;u--){let l=r[u],c=l.inputs;for(let p=0;p<l.outputs.length;p++)if(s[l.outputs[p].id]){for(let m in c)s[c[m].id]=!0,i[l.id]=!0;break}}let a=[];for(let u=0;u<r.length;u++){let l=r[u];if(o[l.id]&&i[l.id]){let c={};for(let m in l.inputs){let f=l.inputs[m];n[f.id]&&(c[m]=f)}let p=Object.assign({},l);p.inputs=c,p.outputs=l.outputs,a.push(p)}}return a}function G_(r,t,e,n){for(let o=t.length-1;o>=0;o--){let s=t[o],i=[];if(s.outputs.forEach(u=>{let l=r[u.id];l!=null?i.push(l):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let a=s.gradient(i);for(let u in s.inputs){if(!(u in a))throw new Error(`Cannot backprop through input ${u}. Available gradients found: ${Object.keys(a)}.`);let l=e(()=>a[u]());if(l.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${u} must have 'float32' dtype, but has '${l.dtype}'`);let c=s.inputs[u];if(!an(l.shape,c.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${u}' has shape '${l.shape}', which does not match the shape of the input '${c.shape}'`);if(r[c.id]==null)r[c.id]=l;else{let p=r[c.id];r[c.id]=n(p,l),p.dispose()}}}}var W_=20,lh=3,k0=7;function U_(r,t,e,n){let o=Di(t),s=fK(r,t,e,o),i=t.length,a=nx(r,t,e,o,s),u=["Tensor"];return n&&(u.push(` dtype: ${e}`),u.push(` rank: ${i}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(a.map(l=>" "+l).join(`
| `)),u.join(`
| `)}function fK(r,t,e,n){let o=te(t),s=n[n.length-1],i=new Array(s).fill(0),a=t.length,u=e==="complex64"?ch(r):r;if(a>1)for(let l=0;l<o/s;l++){let c=l*s;for(let p=0;p<s;p++)i[p]=Math.max(i[p],uh(u[c+p],0,e).length)}return i}function uh(r,t,e){let n;return Array.isArray(r)?n=`${parseFloat(r[0].toFixed(k0))} + ${parseFloat(r[1].toFixed(k0))}j`:Ho(r)?n=`'${r}'`:e==="bool"?n=H_(r):n=parseFloat(r.toFixed(k0)).toString(),lc(n,t)}function H_(r){return r===0?"false":"true"}function nx(r,t,e,n,o,s=!0){let i=e==="complex64"?2:1,a=t[0],u=t.length;if(u===0){if(e==="complex64"){let h=ch(r);return[uh(h[0],0,e)]}return e==="bool"?[H_(r[0])]:[r[0].toString()]}if(u===1){if(a>W_){let g=lh*i,x=Array.from(r.slice(0,g)),b=Array.from(r.slice((a-lh)*i,a*i));return e==="complex64"&&(x=ch(x),b=ch(b)),["["+x.map((w,I)=>uh(w,o[I],e)).join(", ")+", ..., "+b.map((w,I)=>uh(w,o[a-lh+I],e)).join(", ")+"]"]}return["["+(e==="complex64"?ch(r):Array.from(r)).map((g,x)=>uh(g,o[x],e)).join(", ")+"]"]}let l=t.slice(1),c=n.slice(1),p=n[0]*i,m=[];if(a>W_){for(let h=0;h<lh;h++){let g=h*p,x=g+p;m.push(...nx(r.slice(g,x),l,e,c,o,!1))}m.push("...");for(let h=a-lh;h<a;h++){let g=h*p,x=g+p;m.push(...nx(r.slice(g,x),l,e,c,o,h===a-1))}}else for(let h=0;h<a;h++){let g=h*p,x=g+p;m.push(...nx(r.slice(g,x),l,e,c,o,h===a-1))}let f=u===2?",":"";m[0]="["+(a>0?m[0]+f:"");for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d=`,
| `;for(let h=2;h<u;h++)d+=`
| `;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function ch(r){let t=[];for(let e=0;e<r.length;e+=2)t.push([r[e],r[e+1]]);return t}var le=class{constructor(t,e,n){if(this.dtype=e,this.shape=t.slice(),this.size=te(t),n!=null){let o=n.length;_(o===this.size,()=>`Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`)}if(e==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Yg(e,this.size),this.strides=Di(t)}set(t,...e){e.length===0&&(e=[0]),_(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);let n=this.locToIndex(e);this.values[n]=t}get(...t){t.length===0&&(t=[0]);let e=0;for(let o of t){if(o<0||o>=this.shape[e]){let s=`Requested out of range element at ${t}. Buffer shape=${this.shape}`;throw new Error(s)}e++}let n=t[t.length-1];for(let o=0;o<t.length-1;++o)n+=this.strides[o]*t[o];return this.values[n]}locToIndex(t){if(this.rank===0)return 0;if(this.rank===1)return t[0];let e=t[t.length-1];for(let n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e}indexToLoc(t){if(this.rank===0)return[];if(this.rank===1)return[t];let e=new Array(this.shape.length);for(let n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e}get rank(){return this.shape.length}toTensor(){return ci().makeTensor(this.values,this.shape,this.dtype)}},ci=null,rm=null,dK=null;function q_(r){ci=r}function K_(r){rm=r}function j_(r){dK=r}var Ot=class{constructor(t,e,n,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=te(t),this.strides=Di(t),this.dataId=n,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let t=await this.data();return rm.buffer(this.shape,this.dtype,t)}bufferSync(){return rm.buffer(this.shape,this.dtype,this.dataSync())}async array(){let t=await this.data();return ac(this.shape,t,this.dtype==="complex64")}arraySync(){return ac(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let t=ci().read(this.dataId);if(this.dtype==="string"){let e=await t;try{return e.map(n=>em(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t}dataToGPU(t){return this.throwIfDisposed(),ci().readToGPU(this.dataId,t)}dataSync(){this.throwIfDisposed();let t=ci().readSync(this.dataId);if(this.dtype==="string")try{return t.map(e=>em(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}async bytes(){this.throwIfDisposed();let t=await ci().read(this.dataId);return this.dtype==="string"?t:new Uint8Array(t.buffer)}dispose(){this.isDisposed||(ci().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return rm.print(this,t)}clone(){return this.throwIfDisposed(),rm.clone(this)}toString(t=!1){let e=this.dataSync();return U_(e,this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),rm.cast(this,t)}variable(t=!0,e,n){return this.throwIfDisposed(),ci().makeVariable(this,t,e,n)}};Object.defineProperty(Ot,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function O(){return nh("Tensor",()=>Ot)}O();var gl=class extends Ot{constructor(t,e,n,o){super(t.shape,t.dtype,t.dataId,o),this.trainable=e,this.name=n}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!an(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);ci().disposeTensor(this),this.dataId=t.dataId,ci().incRef(this,null)}dispose(){ci().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(gl,Symbol.hasInstance,{value:r=>r instanceof Ot&&r.assign!=null&&r.assign instanceof Function});var So={};Kt(So,{assertTypesMatch:()=>$0,getTensorsInContainer:()=>ph,isTensorInList:()=>gK,makeTypesMatch:()=>jt});var T0;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(T0||(T0={}));var _0;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(_0||(_0={}));var E0;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(E0||(E0={}));var A0;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(A0||(A0={}));var D0;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(D0||(D0={}));var hK={float32:A0,int32:_0,bool:E0,complex64:D0};function ur(r,t){if(r==="string"||t==="string"){if(r==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${r} with ${t}`)}return hK[r][t]}function xc(r){return ur(r,"int32")}function ox(r){return r!=null&&typeof r=="object"&&"texture"in r&&r.texture instanceof WebGLTexture}function sx(r){return typeof GPUBuffer!="undefined"&&r!=null&&typeof r=="object"&&"buffer"in r&&r.buffer instanceof GPUBuffer}function jt(r,t){if(r.dtype===t.dtype)return[r,t];let e=ur(r.dtype,t.dtype);return[r.cast(e),t.cast(e)]}function $0(r,t){_(r.dtype===t.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${t.dtype}) input must match`)}function gK(r,t){return t.some(e=>e.id===r.id)}function ph(r){let t=[];return X_(r,t,new Set),t}function X_(r,t,e){if(r==null)return;if(r instanceof Ot){t.push(r);return}if(!xK(r))return;let n=r;for(let o in n){let s=n[o];e.has(s)||(e.add(s),X_(s,t,e))}}function xK(r){return Array.isArray(r)||typeof r=="object"}function R0(r){return r.kernelName!=null}var ix=class{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(t=>t.name)))}}}dispose(){for(let t in this.registeredVariables)this.registeredVariables[t].dispose()}},Iu=class{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ix}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let t=this.getSortedBackends();for(let e=0;e<t.length;e++){let n=t[e];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:t,asyncInit:e}=this.initializeBackendsAndReturnBest();if(e)throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(t){if(!(t in this.registry))if(t in this.registryFactory){let{asyncInit:e}=this.initializeBackend(t);if(e)return null}else return null;return this.registry[t]}findBackendFactory(t){return t in this.registryFactory?this.registryFactory[t].factory:null}registerBackend(t,e,n=1){return t in this.registryFactory?(ta(`${t} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[t]={factory:e,priority:n},!0)}async setBackend(t){if(this.registryFactory[t]==null)throw new Error(`Backend name '${t}' not found in registry`);if(this.backendName=t,this.registry[t]==null){this.backendInstance=null;let{success:e,asyncInit:n}=this.initializeBackend(t);if(!(n?await e:e))return!1}return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new rx(this.backendInstance),!0}setupRegisteredKernels(){Jg(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){Jg(t).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[t])})}initializeBackend(t){let e=this.registryFactory[t];if(e==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{let n=e.factory();if(n&&!(n instanceof Uo)&&typeof n.then=="function"){let o=++this.pendingBackendInitId,s=n.then(i=>o<this.pendingBackendInitId?!1:(this.registry[t]=i,this.pendingBackendInit=null,!0)).catch(i=>(o<this.pendingBackendInitId||(this.pendingBackendInit=null,ta(`Initialization of backend ${t} failed`),ta(i.stack||i.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[t]=n,{success:!0,asyncInit:!1}}catch(n){return ta(`Initialization of backend ${t} failed`),ta(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(t){if(!(t in this.registryFactory))throw new Error(`${t} backend not found in registry`);this.backendName===t&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((t,e)=>this.registryFactory[e].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){let t=this.getSortedBackends();for(let e=0;e<t.length;e++){let n=t[e],{success:o,asyncInit:s}=this.initializeBackend(n);if(s||o)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(t,e){let n=this.state.tensorInfo.get(e),o=n.backend,s=this.readSync(e),i=o.refCount(e);o.disposeData(e,!0),n.backend=t,t.move(e,s,n.shape,n.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(t,e){let n=null;if(e==null){if(typeof t!="function")throw new Error("Please provide a function to tidy()");e=t}else{if(typeof t!="string"&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof e!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=t}let o;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(o),()=>(o=e(),o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o))}scopedRun(t,e,n){t();try{let o=n();return e(),o}catch(o){throw e(),o}}nextTensorId(){return Iu.nextTensorId++}nextVariableId(){return Iu.nextVariableId++}clone(t){let e=T.runKernel(bo,{x:t}),n={x:t},o=i=>({x:()=>{let a="float32",u={x:i},l={dtype:a};return T.runKernel(xo,u,l)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[e],o,s,{}),e}runKernel(t,e,n){if(this.backendName==null&&this.backend,!(ih(t,this.backendName)!=null))throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:e,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,e,n){let o=this.backend.numDataIds(),s=0;n.forEach(u=>{s+=u.dtype==="complex64"?3:1});let i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=o-e-s-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${t}'`)}runKernelFunc(t){let e,n=[],o=this.isTapeOn(),s=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let u,l=R0(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(R0(t)){let{kernelName:d,inputs:h,attrs:g}=t;this.backendName==null&&this.backend;let x=ih(d,this.backendName);_(x!=null,()=>`Cannot find registered kernel '${d}' for backend '${this.backendName}'`),a=()=>{let b=this.backend.numDataIds();u=x.kernelFunc({inputs:h,attrs:g,backend:this.backend});let w=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,b,w);let I=w.map(N=>N.rank!=null?N:this.makeTensorFromTensorInfo(N));if(o){let N=this.getTensorsForGradient(d,h,I);n=this.saveTensorsForBackwardMode(N)}return I}}else{let{forwardFunc:d}=t,h=g=>{o&&(n=g.map(x=>this.keep(this.clone(x))))};a=()=>{let g=this.backend.numDataIds();u=this.tidy(()=>d(this.backend,h));let x=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,g,x),x}}let{inputs:c,attrs:p}=t,m=R0(t)?null:t.backwardsFunc,f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?e=a():(f=this.profiler.profileKernel(l,c,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),e=f.outputs)}),o&&this.addTapeNode(l,c,e,m,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(d=>c[d]!=null?c[d].shape:null),outputShapes:e.map(d=>d.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(u)?e:e[0]}saveTensorsForBackwardMode(t){return t.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(t,e,n){let o=b0(t);if(o!=null){let s=o.inputsToSave||[],i=o.outputsToSave||[],a;o.saveAllInputs?(_(Array.isArray(e),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(e).map(l=>e[l])):a=s.map(l=>e[l]);let u=n.filter((l,c)=>i[c]);return a.concat(u)}return[]}makeTensor(t,e,n,o){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;let s=t;n==="string"&&Ho(t[0])&&(s=t.map(u=>wu(u)));let i=o.write(s,e,n),a=new Ot(e,n,i,this.nextTensorId());if(this.trackTensor(a,o),n==="string"){let u=this.state.tensorInfo.get(i),l=h0(s);this.state.numBytes+=l-u.bytes,u.bytes=l}return a}makeTensorFromDataId(t,e,n,o){n=n||"float32";let s={dataId:t,shape:e,dtype:n};return this.makeTensorFromTensorInfo(s,o)}makeTensorFromTensorInfo(t,e){let{dataId:n,shape:o,dtype:s}=t,i=new Ot(o,s,n,this.nextTensorId());return this.trackTensor(i,e),i}makeVariable(t,e=!0,n,o){n=n||this.nextVariableId().toString(),o!=null&&o!==t.dtype&&(t=t.cast(o));let s=new gl(t,e,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(t,e){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let n=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(n=t.size*Pp(t.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:n})),t instanceof gl||this.track(t)}incRef(t,e){this.trackTensor(t,e),this.backend.incRef(t.dataId)}removeDataId(t,e){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===e&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;let e=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=e.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){let n=t.size*Pp(t.dtype);this.state.numBytes-=n}e.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,e.backend)}disposeVariables(){for(let t in this.state.registeredVariables){let e=this.state.registeredVariables[t];this.disposeVariable(e)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){let t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;let e=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(o=>o.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let o of this.state.activeProfile.kernels)o.kernelTimeMs=await o.kernelTimeMs,o.extraInfo=await o.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(t,e,n,o,s,i){let a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:s},u=b0(t);u!=null&&(o=u.gradFunc),o!=null&&(a.gradient=l=>(l=l.map((c,p)=>{if(c==null){let m=n[p],f=Lp(m.size,m.dtype);return this.makeTensor(f,m.shape,m.dtype)}return c}),o(l.length>1?l:l[0],s,i))),this.state.activeTape.push(a)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){let e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e}endScope(t){let e=ph(t),n=new Set(e.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let i=this.state.activeScope.track[s];!i.kept&&!n.has(i.id)&&i.dispose()}let o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],e.forEach(s=>{!s.kept&&s.scopeId===o.id&&this.track(s)})}gradients(t,e,n,o=!1){if(_(e.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));_(s instanceof Ot,()=>"The result y returned by f() must be a tensor.");let i=V_(this.state.activeTape,e,s);if(!o&&i.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let a={};a[s.id]=n==null?yK(s.shape):n,G_(a,i,l=>this.tidy(l),bK);let u=e.map(l=>a[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:s,grads:u}})}customGrad(t){return _(Ai(t),()=>"The f passed in customGrad(f) must be a function."),(...e)=>{_(e.every(a=>a instanceof Ot),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,o={};e.forEach((a,u)=>{o[u]=a});let s=(a,u)=>(n=t(...e,u),_(n.value instanceof Ot,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),_(Ai(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),i=(a,u)=>{let l=n.gradFunc(a,u),c=Array.isArray(l)?l:[l];_(c.length===e.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),_(c.every(m=>m instanceof Ot),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let p={};return c.forEach((m,f)=>{p[f]=()=>m}),p};return this.runKernelFunc({forwardFunc:s,backwardsFunc:i,inputs:o})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,e){return this.state.tensorInfo.get(t).backend.readToGPU(t,e)}async time(t){let e=gc(),n=await this.backend.time(t);return n.wallMs=gc()-e,n}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new ix;for(let t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};Iu.nextTensorId=0;Iu.nextVariableId=0;function yK(r){let t=eh(te(r),"float32");return T.makeTensor(t,r,"float32")}function F0(){let r=y0();if(r._tfengine==null){let t=new rh(r);r._tfengine=new Iu(t)}return I_(r._tfengine.ENV),q_(()=>r._tfengine),r._tfengine}var T=F0();function bK(r,t){let e={a:r,b:t};return T.runKernel(ao,e)}var Cu={};Kt(Cu,{isBrowser:()=>P0,isMobile:()=>CK,mockIsMobile:()=>IK});function wK(){return typeof navigator!="undefined"&&navigator!=null}var O0;function IK(r){O0=r}function CK(r){if(O0!==void 0)return O0;if(r||wK()){if(r||(r=navigator),r.product==="ReactNative")return!0;let t=r.userAgent||r.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let e=r;return e.userAgentData&&e.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function P0(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Nn=L();Nn.registerFlag("DEBUG",()=>!1,r=>{r&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Nn.registerFlag("IS_BROWSER",()=>P0());Nn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Nn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Nn.registerFlag("IS_SAFARI",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));Nn.registerFlag("PROD",()=>!1);Nn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Nn.getBool("DEBUG"));Nn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Nn.registerFlag("IS_TEST",()=>!1);Nn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Nn.getBool("DEBUG"));Nn.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Nn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Nn.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function Ur(r,t){let e=r;if(or(r))return t==="string"?[]:[r.length];if(ox(r)){let o=r.channels||"RGBA";return[r.height,r.width*o.length]}else if(sx(r))return[r.buffer.size/(t==null?4:Pp(t))];if(!Array.isArray(r))return[];let n=[];for(;Array.isArray(e)||or(e)&&t!=="string";)n.push(e.length),e=e[0];return Array.isArray(r)&&L().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Z_(r,n,[]),n}function Z_(r,t,e){if(e=e||[],!Array.isArray(r)&&!or(r)){_(t.length===0,()=>`Element arr[${e.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}_(t.length>0,()=>`Element arr[${e.join("][")}] should be a primitive, but is an array of ${r.length} elements`),_(r.length===t[0],()=>`Element arr[${e.join("][")}] should have ${t[0]} elements, but has ${r.length} elements`);let n=t.slice(1);for(let o=0;o<r.length;++o)Z_(r[o],n,e.concat(o))}function Y_(r,t,e,n){if(r!=="string_or_numeric"){if(r==null)throw new Error("Expected dtype cannot be null.");if(r!=="numeric"&&r!==t||r==="numeric"&&t==="string")throw new Error(`Argument '${e}' passed to '${n}' must be ${r} tensor, but got ${t} tensor`)}}function C(r,t,e,n="numeric"){if(r instanceof Ot)return Y_(n,r.dtype,t,e),r;let o=Yl(r);if(o!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(o=n),Y_(n,o,t,e),r==null||!or(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){let u=r==null?"null":r.constructor.name;throw new Error(`Argument '${t}' passed to '${e}' must be a Tensor or TensorLike, but got '${u}'`)}let s=Ur(r,o);!or(r)&&!Array.isArray(r)&&(r=[r]);let a=o!=="string"?tm(r,o):ui(r,[],!0);return T.makeTensor(a,s,o)}function xl(r,t,e,n="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${t} passed to ${e} must be a \`Tensor[]\` or \`TensorLike[]\``);return r.map((s,i)=>C(s,`${t}[${i}]`,e,n))}var M0="__op";function k(r){let t=Object.keys(r);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let e=t[0],n=r[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e=e+M0;let o=(...s)=>{T.startScope(e);try{let i=n(...s);return uc(i)&&console.error("Cannot return a Promise inside of tidy."),T.endScope(i),i}catch(i){throw T.endScope(null),i}};return Object.defineProperty(o,"name",{value:e,configurable:!0}),o}function vK(r,t){let e=C(r,"real","complex"),n=C(t,"imag","complex");Re(e.shape,n.shape,`real and imag shapes, ${e.shape} and ${n.shape}, must match in call to tf.complex().`);let o={real:e,imag:n};return T.runKernel(zp,o)}var kn=k({complex_:vK});function un(r,t,e,n){if(n==null)n=Yl(r);else if(n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(sx(r)||ox(r)){if(n!=="float32"&&n!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${n}.`);return T.backend.createTensorFromGPUData(r,t||e,n)}if(!or(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){Me(t);let o=te(t),s=te(e);_(o===s,()=>`Based on the provided shape, [${t}], the tensor should have ${o} values but has ${s}`);for(let i=0;i<e.length;++i){let a=e[i],u=i===e.length-1?a!==te(t.slice(i)):!0;_(e[i]===t[i]||!u,()=>`Error creating a new Tensor. Inferred shape (${e}) does not match the provided shape (${t}). `)}}return!or(r)&&!Array.isArray(r)&&(r=[r]),t=t||e,r=n!=="string"?tm(r,n):ui(r,[],!0),T.makeTensor(r,t,n)}function sr(r,t,e){let n=Ur(r,e);return un(r,t,n,e)}var mh={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var vr=class{static join(t){return new vr(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,t==null||(t instanceof Array||(t=[t]),t=t.map(n=>or(n)?n.buffer:n),t.length===0))return;this.bufferUniformSize=t[0].byteLength;let e=0;for(let n=0;n<t.length;n++){let o=t[n];n!==t.length-1&&o.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);let s=e+o.byteLength;this.shards.push({buffer:o,start:e,end:s}),e=s}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(t=0,e=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(t=isNaN(Number(t))?0:t,e=isNaN(Number(e))?0:e,t=Math.max(0,t),e=Math.min(this.byteLength,e),e<=t)return new ArrayBuffer(0);let n=this.findShardForByte(t);if(n===-1)throw new Error(`Could not find start shard for byte ${t}`);let o=e-t,s=new ArrayBuffer(o),i=new Uint8Array(s),a=0;for(let u=n;u<this.shards.length;u++){let l=this.shards[u],p=t+a-l.start,m=a,d=Math.min(e,l.end)-l.start,h=new Uint8Array(l.buffer,p,d-p);if(i.set(h,m),a+=h.length,e<l.end)break}return s}findShardForByte(t){if(this.shards.length===0||t<0||t>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function e(o){return t<o.start?-1:t>=o.end?1:0}if(e(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;let n=SK(this.shards,e);return n===-1?-1:(this.previousShardIndex=n,this.previousShardIndex)}};function SK(r,t){let e=0,n=r.length;for(;e<=n;){let o=Math.floor((n-e)/2)+e,s=t(r[o]);if(s===0)return o;s<0?n=o:e=o+1}return-1}var ax=4;async function Q_(r,t){let e=[],n=[],o=Array.isArray(r)?r.map(i=>i.name):Object.keys(r);for(let i=0;i<o.length;++i){let a=o[i],u=Array.isArray(r)?r[i].tensor:r[a];if(u.dtype!=="float32"&&u.dtype!=="int32"&&u.dtype!=="bool"&&u.dtype!=="string"&&u.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${a}': ${u.dtype}`);let l={name:a,shape:u.shape,dtype:u.dtype};if(u.dtype==="string"){let c=new Promise(async p=>{let m=await u.bytes(),f=m.reduce((g,x)=>g+x.length,0)+ax*m.length,d=new Uint8Array(f),h=0;for(let g=0;g<m.length;g++){let x=m[g],b=new Uint8Array(new Uint32Array([x.length]).buffer);d.set(b,h),h+=ax,d.set(x,h),h+=x.length}p(d)});n.push(c)}else n.push(u.data());t!=null&&(l.group=t),e.push(l)}let s=await Promise.all(n);return{data:NK(s),specs:e}}function lx(r,t){let e=new vr(r),n={},o,s=0;for(let i of t){let a=i.name,u=i.dtype,l=i.shape,c=te(l),p;if("quantization"in i){let m=i.quantization;if(m.dtype==="uint8"||m.dtype==="uint16"){if(!("min"in m&&"scale"in m))throw new Error(`Weight ${i.name} with quantization ${m.dtype} doesn't have corresponding metadata min and scale.`)}else if(m.dtype==="float16"){if(u!=="float32")throw new Error(`Weight ${i.name} is quantized with ${m.dtype} which only supports weights of type float32 not ${u}.`)}else throw new Error(`Weight ${i.name} has unknown quantization dtype ${m.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let f=mh[m.dtype],d=e.slice(s,s+c*f),h=m.dtype==="uint8"?new Uint8Array(d):new Uint16Array(d);if(u==="float32")if(m.dtype==="uint8"||m.dtype==="uint16"){p=new Float32Array(h.length);for(let g=0;g<h.length;g++){let x=h[g];p[g]=x*m.scale+m.min}}else if(m.dtype==="float16")o===void 0&&(o=EK()),p=o(h);else throw new Error(`Unsupported quantization type ${m.dtype} for weight type float32.`);else if(u==="int32"){if(m.dtype!=="uint8"&&m.dtype!=="uint16")throw new Error(`Unsupported quantization type ${m.dtype} for weight type int32.`);p=new Int32Array(h.length);for(let g=0;g<h.length;g++){let x=h[g];p[g]=Math.round(x*m.scale+m.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${u}`);s+=c*f}else if(u==="string"){let m=te(i.shape);p=[];for(let f=0;f<m;f++){let d=new Uint32Array(e.slice(s,s+ax))[0];s+=ax;let h=new Uint8Array(e.slice(s,s+d));p.push(h),s+=d}}else{let m=mh[u],f=e.slice(s,s+c*m);if(u==="float32")p=new Float32Array(f);else if(u==="int32")p=new Int32Array(f);else if(u==="bool")p=new Uint8Array(f);else if(u==="complex64"){p=new Float32Array(f);let d=new Float32Array(p.length/2),h=new Float32Array(p.length/2);for(let b=0;b<d.length;b++)d[b]=p[b*2],h[b]=p[b*2+1];let g=sr(d,l,"float32"),x=sr(h,l,"float32");n[a]=kn(g,x),g.dispose(),x.dispose()}else throw new Error(`Unsupported dtype in weight '${a}': ${u}`);s+=c*m}u!=="complex64"&&(n[a]=sr(p,l,u))}return n}function NK(r){if(r===null)throw new Error(`Invalid input value: ${JSON.stringify(r)}`);let t=0,e=[];r.forEach(s=>{if(t+=s.byteLength,e.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let n=new Uint8Array(t),o=0;return e.forEach(s=>{n.set(new Uint8Array(s.buffer),o),o+=s.byteLength}),n.buffer}var L0=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function J_(r){return L0?Buffer.byteLength(r,"utf8"):new Blob([r]).size}function tE(r){if(L0)return Buffer.from(r).toString("base64");let t=new Uint8Array(r),e="";for(let n=0,o=t.length;n<o;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function eE(r){if(L0){let n=Buffer.from(r,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let t=atob(r),e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e.set([t.charCodeAt(n)],n);return e.buffer}function rE(r){return vr.join(r)}function z0(r){let t="/";for(r=r.trim();r.endsWith(t);)r=r.slice(0,r.length-1);let e=r.split(t);return e[e.length-1]}function ux(r,t){let e={modelTopology:r.modelTopology,format:r.format,generatedBy:r.generatedBy,convertedBy:r.convertedBy,weightsManifest:t};return r.signature!=null&&(e.signature=r.signature),r.userDefinedMetadata!=null&&(e.userDefinedMetadata=r.userDefinedMetadata),r.modelInitializer!=null&&(e.modelInitializer=r.modelInitializer),r.initializerSignature!=null&&(e.initializerSignature=r.initializerSignature),r.trainingConfig!=null&&(e.trainingConfig=r.trainingConfig),e}function B0(r,t,e){let n={modelTopology:r.modelTopology,format:r.format,generatedBy:r.generatedBy,convertedBy:r.convertedBy};if(r.trainingConfig!=null&&(n.trainingConfig=r.trainingConfig),r.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!e)throw new Error("modelJSON has weightsManifest but weightData is null");n.weightSpecs=t,n.weightData=e}return r.signature!=null&&(n.signature=r.signature),r.userDefinedMetadata!=null&&(n.userDefinedMetadata=r.userDefinedMetadata),r.modelInitializer!=null&&(n.modelInitializer=r.modelInitializer),r.initializerSignature!=null&&(n.initializerSignature=r.initializerSignature),n}async function nm(r,t){let e,n;return r.weightsManifest!=null&&([e,n]=await t(r.weightsManifest)),B0(r,e,n)}function ea(r){if(r.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:r.modelTopology==null?0:J_(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:J_(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:new vr(r.weightData).byteLength}}function cx(r){let t=[];for(let e of r)t.push(...e.weights);return t}function kK(){let r=e=>{let n=e<<13,o=0;for(;!(n&8388608);)o-=8388608,n<<=1;return n&=-8388609,o+=947912704,n|o},t=new Uint32Array(2048);t[0]=0;for(let e=1;e<1024;e++)t[e]=r(e);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}function TK(){let r=new Uint32Array(64);r[0]=0,r[31]=1199570944,r[32]=2147483648,r[63]=3347054592;for(let t=1;t<31;t++)r[t]=t<<23;for(let t=33;t<63;t++)r[t]=2147483648+(t-32<<23);return r}function _K(){let r=new Uint32Array(64);for(let t=0;t<64;t++)r[t]=1024;return r[0]=r[32]=0,r}function EK(){let r=kK(),t=TK(),e=_K();return n=>{let o=new ArrayBuffer(4*n.length),s=new Uint32Array(o);for(let i=0;i<n.length;i++){let a=n[i],u=r[e[a>>10]+(a&1023)]+t[a>>10];s[i]=u}return new Float32Array(o)}}var ve=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return ve.instance==null&&(ve.instance=new ve),ve.instance}static registerSaveRouter(t){ve.getInstance().saveRouters.push(t)}static registerLoadRouter(t){ve.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return ve.getHandlers(t,"save")}static getLoadHandlers(t,e){return ve.getHandlers(t,"load",e)}static getHandlers(t,e,n){let o=[];return(e==="load"?ve.getInstance().loadRouters:ve.getInstance().saveRouters).forEach(i=>{let a=i(t,n);a!==null&&o.push(a)}),o}},nE=r=>ve.registerSaveRouter(r),oE=r=>ve.registerLoadRouter(r),sE=r=>ve.getSaveHandlers(r),iE=(r,t)=>ve.getLoadHandlers(r,t);var V0="tensorflowjs",G0=1,yc="models_store",vu="model_info_store";function aE(){if(!L().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let r=typeof window=="undefined"?self:window,t=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function W0(r){let t=r.result;t.createObjectStore(yc,{keyPath:"modelPath"}),t.createObjectStore(vu,{keyPath:"modelPath"})}var ra=class{constructor(t){if(this.indexedDB=aE(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,t)}async load(){return this.databaseAction(this.modelPath)}databaseAction(t,e){return new Promise((n,o)=>{let s=this.indexedDB.open(V0,G0);s.onupgradeneeded=()=>W0(s),s.onsuccess=()=>{let i=s.result;if(e==null){let a=i.transaction(yc,"readonly"),l=a.objectStore(yc).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return i.close(),o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(i.close(),o(l.error)),a.oncomplete=()=>i.close()}else{e.weightData=vr.join(e.weightData);let a=ea(e),u=i.transaction(vu,"readwrite"),l=u.objectStore(vu),c;try{c=l.put({modelPath:this.modelPath,modelArtifactsInfo:a})}catch(m){return o(m)}let p;c.onsuccess=()=>{p=i.transaction(yc,"readwrite");let m=p.objectStore(yc),f;try{f=m.put({modelPath:this.modelPath,modelArtifacts:e,modelArtifactsInfo:a})}catch(d){return o(d)}f.onsuccess=()=>n({modelArtifactsInfo:a}),f.onerror=d=>{l=u.objectStore(vu);let h=l.delete(this.modelPath);h.onsuccess=()=>(i.close(),o(f.error)),h.onerror=g=>(i.close(),o(f.error))}},c.onerror=m=>(i.close(),o(c.error)),u.oncomplete=()=>{p==null?i.close():p.oncomplete=()=>i.close()}}},s.onerror=i=>o(s.error)})}};ra.URL_SCHEME="indexeddb://";var lE=r=>L().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ra.URL_SCHEME)?AK(r.slice(ra.URL_SCHEME.length)):null;ve.registerSaveRouter(lE);ve.registerLoadRouter(lE);function AK(r){return new ra(r)}function DK(r){return r.startsWith(ra.URL_SCHEME)?r.slice(ra.URL_SCHEME.length):r}var px=class{constructor(){this.indexedDB=aE()}async listModels(){return new Promise((t,e)=>{let n=this.indexedDB.open(V0,G0);n.onupgradeneeded=()=>W0(n),n.onsuccess=()=>{let o=n.result,s=o.transaction(vu,"readonly"),a=s.objectStore(vu).getAll();a.onsuccess=()=>{let u={};for(let l of a.result)u[l.modelPath]=l.modelArtifactsInfo;t(u)},a.onerror=u=>(o.close(),e(a.error)),s.oncomplete=()=>o.close()},n.onerror=o=>e(n.error)})}async removeModel(t){return t=DK(t),new Promise((e,n)=>{let o=this.indexedDB.open(V0,G0);o.onupgradeneeded=()=>W0(o),o.onsuccess=()=>{let s=o.result,i=s.transaction(vu,"readwrite"),a=i.objectStore(vu),u=a.get(t),l;u.onsuccess=()=>{if(u.result==null)return s.close(),n(new Error(`Cannot find model with path '${t}' in IndexedDB.`));{let c=a.delete(t),p=()=>{l=s.transaction(yc,"readwrite");let f=l.objectStore(yc).delete(t);f.onsuccess=()=>e(u.result.modelArtifactsInfo),f.onerror=d=>n(u.error)};c.onsuccess=p,c.onerror=m=>(p(),s.close(),n(u.error))}},u.onerror=c=>(s.close(),n(u.error)),i.oncomplete=()=>{l==null?s.close():l.oncomplete=()=>s.close()}},o.onerror=s=>n(o.error)})}};var yl="/",om="tensorflowjs_models",uE="info",$K="model_topology",RK="weight_specs",FK="weight_data",OK="model_metadata";function cE(r){return{info:[om,r,uE].join(yl),topology:[om,r,$K].join(yl),weightSpecs:[om,r,RK].join(yl),weightData:[om,r,FK].join(yl),modelMetadata:[om,r,OK].join(yl)}}function pE(r){for(let t of Object.values(r))window.localStorage.removeItem(t)}function PK(r){let t=r.split(yl);if(t.length<3)throw new Error(`Invalid key format: ${r}`);return t.slice(1,t.length-1).join(yl)}function MK(r){return r.startsWith(na.URL_SCHEME)?r.slice(na.URL_SCHEME.length):r}var na=class{constructor(t){if(!L().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,t==null||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=cE(this.modelPath)}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),o=ea(t),s=vr.join(t.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,tE(s));let i={format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,signature:t.signature!=null?t.signature:void 0,userDefinedMetadata:t.userDefinedMetadata!=null?t.userDefinedMetadata:void 0,modelInitializer:t.modelInitializer!=null?t.modelInitializer:void 0,initializerSignature:t.initializerSignature!=null?t.initializerSignature:void 0,trainingConfig:t.trainingConfig!=null?t.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(i)),{modelArtifactsInfo:o}}catch(i){throw pE(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`)}}}async load(){let t=JSON.parse(this.LS.getItem(this.keys.info));if(t==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(t.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let e={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);e.modelTopology=n;let o=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(o==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);e.weightSpecs=o;let s=this.LS.getItem(this.keys.modelMetadata);if(s!=null){let a=JSON.parse(s);e.format=a.format,e.generatedBy=a.generatedBy,e.convertedBy=a.convertedBy,a.signature!=null&&(e.signature=a.signature),a.userDefinedMetadata!=null&&(e.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(e.modelInitializer=a.modelInitializer),a.initializerSignature!=null&&(e.initializerSignature=a.initializerSignature),a.trainingConfig!=null&&(e.trainingConfig=a.trainingConfig)}let i=this.LS.getItem(this.keys.weightData);if(i==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return e.weightData=eE(i),e}};na.URL_SCHEME="localstorage://";var mE=r=>L().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(na.URL_SCHEME)?LK(r.slice(na.URL_SCHEME.length)):null;ve.registerSaveRouter(mE);ve.registerLoadRouter(mE);function LK(r){return new na(r)}var mx=class{constructor(){_(L().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),_(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let t={},e=om+yl,n=yl+uE;for(let o=0;o<this.LS.length;++o){let s=this.LS.key(o);if(s.startsWith(e)&&s.endsWith(n)){let i=PK(s);t[i]=JSON.parse(this.LS.getItem(s))}}return t}async removeModel(t){t=MK(t);let e=cE(t);if(this.LS.getItem(e.info)==null)throw new Error(`Cannot find model at path '${t}'`);let n=JSON.parse(this.LS.getItem(e.info));return pE(e),n}};var sm="://",$r=class{constructor(){this.managers={}}static getInstance(){return $r.instance==null&&($r.instance=new $r),$r.instance}static registerManager(t,e){_(t!=null,()=>"scheme must not be undefined or null."),t.endsWith(sm)&&(t=t.slice(0,t.indexOf(sm))),_(t.length>0,()=>"scheme must not be an empty string.");let n=$r.getInstance();_(n.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),n.managers[t]=e}static getManager(t){let e=$r.getInstance().managers[t];if(e==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return e}static getSchemes(){return Object.keys($r.getInstance().managers)}};function fx(r){if(r.indexOf(sm)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${$r.getSchemes().join(",")}`);return{scheme:r.split(sm)[0],path:r.split(sm)[1]}}async function fE(r,t,e=!1){_(r!==t,()=>`Old path and new path are the same: '${r}'`);let n=ve.getLoadHandlers(r);_(n.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),_(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${r}.`);let o=n[0],s=ve.getSaveHandlers(t);_(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),_(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);let i=s[0],a=fx(r).scheme,u=fx(r).path,l=a===fx(r).scheme,c=await o.load();e&&l&&await $r.getManager(a).removeModel(u);let p=await i.save(c);return e&&!l&&await $r.getManager(a).removeModel(u),p.modelArtifactsInfo}async function dE(){let r=$r.getSchemes(),t={};for(let e of r){let n=await $r.getManager(e).listModels();for(let o in n){let s=e+sm+o;t[s]=n[o]}}return t}async function hE(r){let t=fx(r);return $r.getManager(t.scheme).removeModel(t.path)}async function gE(r,t){return fE(r,t,!1)}async function xE(r,t){return fE(r,t,!0)}var U0=class{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(t,e){return fetch(t,e)}now(){return performance.now()}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${e}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)}decode(t,e){return new TextDecoder(e).decode(t)}setTimeoutCustom(t,e){if(typeof window=="undefined"||!L().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(t,e);return}this.functionRefs.push(t),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},e),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",n=>{if(n.source===window&&n.data.name===this.messageName){n.stopPropagation();let o=this.functionRefs[n.data.index];o(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(t){return Qg(t)}};if(L().get("IS_BROWSER")){L().setPlatform("browser",new U0);try{$r.registerManager(na.URL_SCHEME,new mx)}catch(r){}try{$r.registerManager(ra.URL_SCHEME,new px)}catch(r){}}var zK={importFetch:()=>yE()},H0;var q0=class{constructor(){this.util=bE(),this.textEncoder=new this.util.TextEncoder}fetch(t,e){return L().global.fetch!=null?L().global.fetch(t,e):(H0==null&&(H0=zK.importFetch()),H0(t,e))}now(){let t=process.hrtime();return t[0]*1e3+t[1]/1e6}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);return this.textEncoder.encode(t)}decode(t,e){return t.length===0?"":new this.util.TextDecoder(e).decode(t)}isTypedArray(t){return this.util.types.isFloat32Array(t)||this.util.types.isInt32Array(t)||this.util.types.isUint8Array(t)||this.util.types.isUint8ClampedArray(t)}};L().get("IS_NODE")&&!L().get("IS_BROWSER")&&L().setPlatform("node",new q0);function wt(r,t="float32",e){return t=t||"float32",Me(r),new le(r,t,e)}function BK(r,t){let e=C(r,"x","cast");if(!d0(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");let n={x:e},o={dtype:t};return T.runKernel(xo,n,o)}var Q=k({cast_:BK});function VK(r){let e={x:C(r,"x","clone","string_or_numeric")};return T.runKernel(bo,e)}var cn=k({clone_:VK});function dx(r,t=!1){console.log(r.toString(t))}F0();var GK={buffer:wt,cast:Q,clone:cn,print:dx};K_(GK);function aht(){L().set("PROD",!0)}function lht(){L().set("DEBUG",!0)}function uht(){L().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function K0(r){L().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}j_(K0);function cht(){T.disposeVariables()}function Wn(){return T}function fh(){return T.memory()}function pht(r){return T.profile(r)}function B(r,t){return T.tidy(r,t)}function Tt(r){ph(r).forEach(e=>e.dispose())}function $e(r){return T.keep(r)}function mht(r){return T.time(r)}function WK(r){return T.setBackend(r)}function fht(){return T.ready()}function dht(){return T.backendName}function hht(r){T.removeBackend(r)}function ght(r){return T.findBackend(r)}function xht(r){return T.findBackendFactory(r)}function im(r,t,e=1){return T.registerBackend(r,t,e)}function wE(){return T.backend}function yht(r,t){L().setPlatform(r,t)}function UK(r,t){let e=C(r,"a","add"),n=C(t,"b","add");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(ao,o)}var Y=k({add_:UK});function HK(r,t){let e=C(r,"a","floorDiv"),n=C(t,"b","floorDiv");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(xs,o)}var am=k({floorDiv_:HK});function qK(r,t){let e=C(r,"a","div"),n=C(t,"b","div");if([e,n]=jt(e,n),e.dtype==="int32"&&n.dtype==="int32")return am(e,n);let o={a:e,b:n},s={};return T.runKernel(ps,o,s)}var ct=k({div_:qK});function KK(r,t){let e=C(r,"a","mul"),n=C(t,"b","mul");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(Os,o)}var $=k({mul_:KK});function jK(r){let t=C(r,"x","abs");if(t.dtype==="complex64"){let e={x:t};return T.runKernel(tu,e)}else{let e={x:t};return T.runKernel($i,e)}}var Ee=k({abs_:jK});function XK(r){let e={x:C(r,"x","acos")};return T.runKernel(qo,e)}var hx=k({acos_:XK});function YK(r){let e={x:C(r,"x","acosh")};return T.runKernel(Ko,e)}var gx=k({acosh_:YK});function ZK(r){_(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),_(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let t=r.map((o,s)=>C(o,`tensors${s}`,"addN")),e=t[0];t.forEach(o=>{if(o.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!an(o.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return T.runKernel(jo,n)}var IE=k({addN_:ZK});function JK(r,t=null,e=!1){let o={x:C(r,"x","all","bool")},s={axis:t,keepDims:e};return T.runKernel(Ra,o,s)}var lm=k({all_:JK});function QK(r,t=null,e=!1){let o={x:C(r,"x","any","bool")},s={axis:t,keepDims:e};return T.runKernel(Fa,o,s)}var bc=k({any_:QK});function tj(r,t=0){let n={x:C(r,"x","argMax")},o={axis:t};return T.runKernel(Ri,n,o)}var oa=k({argMax_:tj});function ej(r,t=0){let n={x:C(r,"x","argMin")},o={axis:t};return T.runKernel(Fi,n,o)}var xx=k({argMin_:ej});function rj(r){let e={x:C(r,"x","asin")};return T.runKernel(Xo,e)}var yx=k({asin_:rj});function nj(r){let e={x:C(r,"x","asinh")};return T.runKernel(Yo,e)}var bx=k({asinh_:nj});function oj(r){let e={x:C(r,"x","atan")};return T.runKernel(Zo,e)}var wx=k({atan_:oj});function sj(r,t){let e=C(r,"a","atan2"),n=C(t,"b","atan2");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(Qo,o)}var Ix=k({atan2_:sj});function ij(r){let e={x:C(r,"x","atanh")};return T.runKernel(Jo,e)}var Cx=k({atanh_:ij});function aj(r,t,e,n,o="NHWC",s){let i=r[3],a=[...t,i],u=vE(o);return wc(r,a,e,s,n,null,null,u)}function X0(r,t,e,n,o,s,i="channelsLast"){let[a,u]=dh(t),l;if(i==="channelsLast")l=[a,u,r[3],r[3]];else if(i==="channelsFirst")l=[a,u,r[1],r[1]];else throw new Error(`Unknown dataFormat ${i}`);return wc(r,l,e,n,o,s,!1,i)}function lj(r,t,e,n,o,s,i="NDHWC"){let[a,u,l]=j0(t),c,p;if(i==="NDHWC")p="channelsLast",c=[a,u,l,r[4],r[4]];else if(i==="NCDHW")p="channelsFirst",c=[a,u,l,r[1],r[1]];else throw new Error(`Unknown dataFormat ${i}`);return CE(r,c,e,n,o,!1,p,s)}function wc(r,t,e,n,o,s,i=!1,a="channelsLast"){let[u,l,c,p]=[-1,-1,-1,-1];if(a==="channelsLast")[u,l,c,p]=r;else if(a==="channelsFirst")[u,p,l,c]=r;else throw new Error(`Unknown dataFormat ${a}`);let[m,f,,d]=t,[h,g]=dh(e),[x,b]=dh(n),w=um(m,x),I=um(f,b),{padInfo:N,outHeight:E,outWidth:A}=pj(o,l,c,h,g,w,I,s,a),D=i?d*p:d,F;return a==="channelsFirst"?F=[u,D,E,A]:a==="channelsLast"&&(F=[u,E,A,D]),{batchSize:u,dataFormat:a,inHeight:l,inWidth:c,inChannels:p,outHeight:E,outWidth:A,outChannels:D,padInfo:N,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:w,effectiveFilterWidth:I,dilationHeight:x,dilationWidth:b,inShape:r,outShape:F,filterShape:t}}function CE(r,t,e,n,o,s=!1,i="channelsLast",a){let[u,l,c,p,m]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[u,l,c,p,m]=r;else if(i==="channelsFirst")[u,m,l,c,p]=r;else throw new Error(`Unknown dataFormat ${i}`);let[f,d,h,,g]=t,[x,b,w]=j0(e),[I,N,E]=j0(n),A=um(f,I),D=um(d,N),F=um(h,E),{padInfo:P,outDepth:V,outHeight:G,outWidth:W}=mj(o,l,c,p,x,b,w,A,D,F,a),q=s?g*m:g,H;return i==="channelsFirst"?H=[u,q,V,G,W]:i==="channelsLast"&&(H=[u,V,G,W,q]),{batchSize:u,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:m,outDepth:V,outHeight:G,outWidth:W,outChannels:q,padInfo:P,strideDepth:x,strideHeight:b,strideWidth:w,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:A,effectiveFilterHeight:D,effectiveFilterWidth:F,dilationDepth:I,dilationHeight:N,dilationWidth:E,inShape:r,outShape:H,filterShape:t}}function uj(r,t,e,n,o){n==null&&(n=Y0(r,t,e));let s=r[0],i=r[1],a=hh((s-t+2*n)/e+1,o),u=hh((i-t+2*n)/e+1,o);return[a,u]}function cj(r,t,e,n,o,s){o==null&&(o=Y0(r,t[0],n[0]));let i=[0,0,0,e];for(let a=0;a<3;a++)r[a]+2*o>=t[a]&&(i[a]=hh((r[a]-t[a]+2*o)/n[a]+1,s));return i}function Y0(r,t,e,n=1){let o=um(t,n);return Math.floor((r[0]*(e-1)-e+o)/2)}function dh(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function j0(r){return typeof r=="number"?[r,r,r]:r}function um(r,t){return t<=1?r:r+(r-1)*(t-1)}function pj(r,t,e,n,o,s,i,a,u){let l,c,p;if(typeof r=="number"){l={top:r,bottom:r,left:r,right:r,type:r===0?"VALID":"NUMBER"};let f=uj([t,e],s,n,r,a);c=f[0],p=f[1]}else if(r==="same"){c=Math.ceil(t/n),p=Math.ceil(e/o);let m=Math.max(0,(c-1)*n+s-t),f=Math.max(0,(p-1)*o+i-e),d=Math.floor(m/2),h=m-d,g=Math.floor(f/2),x=f-g;l={top:d,bottom:h,left:g,right:x,type:"SAME"}}else if(r==="valid")l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/n),p=Math.ceil((e-i+1)/o);else if(typeof r=="object"){let m=u==="channelsLast"?r[1][0]:r[2][0],f=u==="channelsLast"?r[1][1]:r[2][1],d=u==="channelsLast"?r[2][0]:r[3][0],h=u==="channelsLast"?r[2][1]:r[3][1];l={top:m,bottom:f,left:d,right:h,type:m===0&&f===0&&d===0&&h===0?"VALID":"EXPLICIT"},c=hh((t-s+m+f)/n+1,a),p=hh((e-i+d+h)/o+1,a)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:l,outHeight:c,outWidth:p}}function mj(r,t,e,n,o,s,i,a,u,l,c){let p,m,f,d;if(r==="valid"&&(r=0),typeof r=="number"){p={top:r,bottom:r,left:r,right:r,front:r,back:r,type:r===0?"VALID":"NUMBER"};let g=cj([t,e,n,1],[a,u,l],1,[o,s,i],r,c);m=g[0],f=g[1],d=g[2]}else if(r==="same"){m=Math.ceil(t/o),f=Math.ceil(e/s),d=Math.ceil(n/i);let h=(m-1)*o+a-t,g=(f-1)*s+u-e,x=(d-1)*i+l-n,b=Math.floor(h/2),w=h-b,I=Math.floor(g/2),N=g-I,E=Math.floor(x/2),A=x-E;p={top:I,bottom:N,left:E,right:A,front:b,back:w,type:"SAME"}}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:p,outDepth:m,outHeight:f,outWidth:d}}function hh(r,t){if(!t)return Math.trunc(r);switch(t){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error(`Unknown roundingMode ${t}`)}}function co(r){let[t,e,n]=dh(r);return t===1&&e===1&&n===1}function Rr(r,t){return co(r)||co(t)}function sa(r){return dh(r).every(t=>t>0)}function vE(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function Se(r,t,e){if(e!=null){if(typeof t=="string")throw Error(`Error in ${r}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);if(typeof t=="number")_($a(t),()=>`Error in ${r}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);else if(typeof t=="object")t.forEach(n=>{n.forEach(o=>{_($a(o),()=>`Error in ${r}: pad must be an integer when using dimRoundingMode ${e} but got pad ${o}.`)})});else throw Error(`Error in ${r}: Unknown padding parameter: ${t}`)}}function fj(r,t){let n={x:C(r,"x","reshape","string_or_numeric")},o={shape:t};return T.runKernel(Ui,n,o)}var R=k({reshape_:fj});function dj(r,t,e,n,o){let s=C(r,"x","avgPool","float32"),i=1;_(Rr(e,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`);let a=s,u=!1;s.rank===3&&(u=!0,a=R(s,[1,s.shape[0],s.shape[1],s.shape[2]])),_(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),Se("avgPool",n,o);let l={x:a},c={filterSize:t,strides:e,pad:n,dimRoundingMode:o},p=T.runKernel(ts,l,c);return p=Q(p,s.dtype),u?R(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Su=k({avgPool_:dj});function hj(r,t,e,n,o,s="NDHWC"){let i=C(r,"x","avgPool3d","float32"),a=i,u=!1;i.rank===4&&(u=!0,a=R(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),_(a.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`),_(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),_(typeof e=="number"&&e>0||Array.isArray(e)&&e[0]>0&&e[1]>0&&e[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${e}'`),Se("avgPool3d",n,o);let l={x:a},c={filterSize:t,strides:e,pad:n,dimRoundingMode:o,dataFormat:s},p=T.runKernel(Oi,l,c);return p=Q(p,a.dtype),u?R(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var vx=k({avgPool3d_:hj});function gj(r,t=0){_(r.length>=1,()=>"Pass at least one tensor to concat");let e=xl(r,"tensors","concat","string_or_numeric");if(e[0].dtype==="complex64"&&e.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
| with dtype ${s.dtype}. `)}),e.length===1)return cn(e[0]);let n=e,o={axis:t};return T.runKernel(Mi,n,o)}var ie=k({concat_:gj});function xj(r,t,e=!1,n=!1){let o=C(r,"a","matMul"),s=C(t,"b","matMul");[o,s]=jt(o,s);let i={a:o,b:s},a={transposeA:e,transposeB:n};return T.runKernel(es,i,a)}var Bt=k({matMul_:xj});function yj(r){let e={x:C(r,"x","sigmoid","float32")};return T.runKernel(Qs,e)}var en=k({sigmoid_:yj});function bj(r,t,e){let n=C(r,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let o={x:n},s={begin:t,size:e};return T.runKernel(qi,o,s)}var Pt=k({slice_:bj});function wj(r){let e={x:C(r,"x","tanh","float32")};return T.runKernel(ai,e)}var ia=k({tanh_:wj});function Ij(r,t,e,n,o,s){let i=C(r,"forgetBias","basicLSTMCell"),a=C(t,"lstmKernel","basicLSTMCell"),u=C(e,"lstmBias","basicLSTMCell"),l=C(n,"data","basicLSTMCell"),c=C(o,"c","basicLSTMCell"),p=C(s,"h","basicLSTMCell"),m=ie([l,p],1),f=Bt(m,a),d=Y(f,u),h=d.shape[0],g=d.shape[1]/4,x=[h,g],b=Pt(d,[0,0],x),w=Pt(d,[0,g],x),I=Pt(d,[0,g*2],x),N=Pt(d,[0,g*3],x),E=Y($(en(b),ia(w)),$(c,en(Y(i,I)))),A=$(ia(E),en(N));return[E,A]}var SE=k({basicLSTMCell_:Ij});function Cj(r,t,e){let n=C(r,"x","batchToSpaceND"),o=t.reduce((a,u)=>a*u);_(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),_(e.length===t.length,()=>`crops.length is ${e.length} but should be equal to blockShape.length ${t.length}`),_(n.shape[0]%o===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);let s={x:n},i={blockShape:t,crops:e};return T.runKernel(Pi,s,i)}var Nu=k({batchToSpaceND_:Cj});function NE(r){let t;return r.rank===0||r.rank===1?t=R(r,[1,1,1,r.size]):r.rank===2?t=R(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?t=R(r,[1,r.shape[0],r.shape[1],r.shape[2]]):t=r,t}function vj(r,t,e,n,o,s){s==null&&(s=.001);let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;n!=null&&(c=C(n,"offset","batchNorm")),_(a.rank===u.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),_(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),_(l==null||a.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:NE(i),scale:l,offset:c,mean:a,variance:u},f={varianceEpsilon:s},d=T.runKernel(ys,m,f);return R(d,i.shape)}var aa=k({batchNorm_:vj});function Sj(r,t,e,n,o,s){let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;return n!=null&&(c=C(n,"offset","batchNorm")),_(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),_(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),_(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`),l!=null&&_(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&_(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),aa(i,a,u,c,l,s)}var Sx=k({batchNorm2d_:Sj});function Nj(r,t,e,n,o,s){let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;return n!=null&&(c=C(n,"offset","batchNorm")),_(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),_(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),_(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`),l!=null&&_(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&_(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),aa(i,a,u,c,l,s)}var Nx=k({batchNorm3d_:Nj});function kj(r,t,e,n,o,s){let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;return n!=null&&(c=C(n,"offset","batchNorm")),_(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),_(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),_(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`),l!=null&&_(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&_(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),aa(i,a,u,c,l,s)}var kx=k({batchNorm4d_:kj});function Tj(r,t,e){let n=C(r,"x","bincount"),o=C(t,"weights","bincount");_(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),_(e>=0,()=>`size must be non-negative, but got ${e}.`),_(o.size===n.size||o.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${o.shape}.`);let s={x:n,weights:o},i={size:e};return T.runKernel(Oa,s,i)}var Tx=k({bincount_:Tj});function _j(r,t){let e=C(r,"x","bitwiseAnd"),n=C(t,"y","bitwiseAnd");if(!an(e.shape,n.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${e.shape}, y: ${n.shape}`);if(e.dtype!=="int32"||n.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${e.dtype} and type of y: ${n.dtype}`);let o={a:e,b:n};return T.runKernel(Pa,o)}var kE=k({bitwiseAnd_:_j});function Ej(r,t){let e=C(r,"s0","broadcastArgs","int32"),n=C(t,"s1","broadcastArgs","int32");if(e.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${e.rank}`);if(n.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${n.rank}`);let o={s0:e,s1:n};return T.runKernel(Ql,o)}var TE=k({broadcastArgs_:Ej});function Aj(r,t){let e=C(r,"broadcastTo","x"),n=e.shape;if(Me(t),t.length<e.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${e.rank}.`);if(t.length>e.rank){let l=e.shape.slice();for(;l.length<t.length;)l.unshift(1);e=R(e,l)}let o=e.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(o[l]===t[l])s[l]=1;else if(e.shape[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);if(s.map((l,c)=>l>1?c:-1).filter(l=>l>=0).length===0)return cn(e);let a={x:e},u={reps:s};return T.runKernel(lo,a,u)}var la=k({broadcastTo_:Aj});function Dj(r){let e={x:C(r,"x","ceil","float32")};return T.runKernel(rs,e)}var _x=k({ceil_:Dj});function No(r,t,e){Me(r),e=e||Yl(t);let n={shape:r,value:t,dtype:e};return T.runKernel(su,{},n)}function $j(r,t,e){let n=C(r,"x","clipByValue");if(_(t<=e,()=>`Error in clip: min (${t}) must be less than or equal to max (${e}).`),t===e)return No(n.shape,t,n.dtype);let o={x:n},s={clipValueMin:t,clipValueMax:e};return T.runKernel(yo,o,s)}var Sr=k({clipByValue_:$j});function Rj(r){return ie(r,0)}var Ex=k({concat1d_:Rj});function Fj(r,t){return ie(r,t)}var Ax=k({concat2d_:Fj});function Oj(r,t){return ie(r,t)}var Dx=k({concat3d_:Oj});function Pj(r,t){return ie(r,t)}var $x=k({concat4d_:Pj});function Mj(r,t,e,n,o="NHWC",s=[1,1],i){let a=C(r,"x","conv2d","float32"),u=C(t,"filter","conv2d","float32"),l=a,c=!1;a.rank===3&&(c=!0,l=R(a,[1,a.shape[0],a.shape[1],a.shape[2]])),_(l.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`),_(u.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`),Se("conv2d",n,i);let p=o==="NHWC"?l.shape[3]:l.shape[1];_(p===u.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${u.shape[2]}.`),_(Rr(e,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${s}'`),_(sa(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),_(sa(e),()=>"Error in conv2D: Strides should be larger than 0.");let m={x:l,filter:u},f={strides:e,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},d=T.runKernel(ns,m,f);return c?R(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Tn=k({conv2d_:Mj});function Lj(r,t,e,n,o="NWC",s=1,i){let a=C(r,"x","conv1d"),u=C(t,"filter","conv1d"),l=a,c=!1;a.rank===2&&(c=!0,l=R(a,[1,a.shape[0],a.shape[1]])),_(l.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`),_(u.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`),Se("conv1d",n,i),_(l.shape[2]===u.shape[1],()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`),_(Rr(e,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${e} and dilation '${s}'`),_(sa(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),_(sa(e),()=>"Error in conv1D: Stride should be larger than 0."),_(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);let p=R(u,[1,u.shape[0],u.shape[1],u.shape[2]]),m=R(l,[l.shape[0],1,l.shape[1],l.shape[2]]),g=Tn(m,p,[1,e],n,"NHWC",[1,s],i);return c?R(g,[g.shape[2],g.shape[3]]):R(g,[g.shape[0],g.shape[2],g.shape[3]])}var cm=k({conv1d_:Lj});function zj(r,t,e,n,o,s="NHWC",i){_(r.length===t.rank,()=>`Length of inShape (${r.length}) and rank of dy (${t.rank}) must match`);let a=r,u=t,l=!1;t.rank===3&&(l=!0,u=R(t,[1,t.shape[0],t.shape[1],t.shape[2]]),a=[1,r[0],r[1],r[2]]),_(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),_(u.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`),_(e.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${e.rank}`);let c=s==="NHWC"?a[3]:a[1],p=s==="NHWC"?u.shape[3]:u.shape[1];_(c===e.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${e.shape[2]}.`),_(p===e.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${e.shape[3]}.`),Se("conv2dDerInput",o,i);let m={dy:u,filter:e},f={strides:n,pad:o,dataFormat:s,dimRoundingMode:i,inputShape:a},d=T.runKernel(os,m,f);return l?R(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var pm=k({conv2DBackpropInput_:zj});function Bj(r,t,e,n,o,s){let i=C(r,"x","conv2dTranspose"),a=C(t,"filter","conv2dTranspose");return pm(e,i,a,n,o,"NHWC",s)}var mm=k({conv2dTranspose_:Bj});function Vj(r,t,e,n,o="NDHWC",s=[1,1,1]){let i=C(r,"x","conv3d"),a=C(t,"filter","conv3d"),u=i,l=!1;i.rank===4&&(l=!0,u=R(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),_(u.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`),_(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),_(u.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${a.shape[3]}.`),_(Rr(e,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${e} and dilations '${s}'`),_(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`),_(sa(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),_(sa(e),()=>"Error in conv3D: Strides should be larger than 0.");let c={x:u,filter:a},p={strides:e,pad:n,dataFormat:o,dilations:s},m=T.runKernel(ss,c,p);return l?R(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Rx=k({conv3d_:Vj});function Gj(r,t,e,n,o){_(r.length===t.rank,()=>`Length of inShape (${r.length}) and rank of dy (${t.rank}) must match`);let s=r,i=t,a=!1;t.rank===4&&(a=!0,i=R(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,r[0],r[1],r[2],r[3]]);let u=s[4],l=i.shape[4];_(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),_(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),_(e.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${e.rank}`),_(u===e.shape[3],()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${e.shape[3]}.`),_(l===e.shape[4],()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${e.shape[4]}.`);let c={dy:i,filter:e},p={pad:o,strides:n,inputShape:s},m=T.runKernel(La,c,p);return a?R(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Fx=k({conv3DBackpropInput_:Gj});function Wj(r,t,e,n,o){let s=C(r,"x","conv3dTranspose"),i=C(t,"filter","conv3dTranspose");return Fx(e,s,i,n,o)}var Ox=k({conv3dTranspose_:Wj});function Uj(r){let e={x:C(r,"x","cos","float32")};return T.runKernel(is,e)}var ku=k({cos_:Uj});function Hj(r){let e={x:C(r,"x","cosh","float32")};return T.runKernel(as,e)}var fm=k({cosh_:Hj});function qj(r,t=0,e=!1,n=!1){let s={x:C(r,"x","cumprod")},i={axis:t,exclusive:e,reverse:n};return T.runKernel(za,s,i)}var Ic=k({cumprod_:qj});function Kj(r,t=0,e=!1,n=!1){let s={x:C(r,"x","cumsum")},i={axis:t,exclusive:e,reverse:n};return T.runKernel(ls,s,i)}var dm=k({cumsum_:Kj});function jj(r,t,e,n=!1){let o=C(r,"x","denseBincount"),s=C(t,"weights","denseBincount");_(o.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${o.dtype}`),_(o.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`),_(e>=0,()=>`size must be non-negative, but got ${e}.`),_(s.size===o.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${s.shape}.`);let i={x:o,weights:s},a={size:e,binaryOutput:n};return T.runKernel(eu,i,a)}var gh=k({denseBincount_:jj});function Xj(r,t,e="NHWC"){let n=C(r,"x","depthToSpace","float32"),o=e==="NHWC"?n.shape[1]:n.shape[2],s=e==="NHWC"?n.shape[2]:n.shape[3],i=e==="NHWC"?n.shape[3]:n.shape[1];_(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),_(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
| ${o} and ${t} for depthToSpace with input shape
| ${n.shape}`),_(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
| ${s} and ${t} for depthToSpace with input shape
| ${n.shape}`),_(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${n.shape}`);let a={x:n},u={blockSize:t,dataFormat:e};return T.runKernel(Va,a,u)}var Px=k({depthToSpace_:Xj});function Yj(r,t,e,n,o="NHWC",s=[1,1],i){let a=C(r,"x","depthwiseConv2d","float32"),u=C(t,"filter","depthwiseConv2d","float32"),l=a,c=!1;a.rank===3&&(c=!0,l=R(a,[1,a.shape[0],a.shape[1],a.shape[2]])),_(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),_(u.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`);let p=o==="NHWC"?l.shape[3]:l.shape[1];_(p===u.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${u.shape[2]}.`),Se("depthwiseConv2d",n,i);let m={x:l,filter:u},f={strides:e,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},d=T.runKernel(us,m,f);return c?R(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var ua=k({depthwiseConv2d_:Yj});function Zj(r){let e={x:C(r,"x","diag")};return T.runKernel(ru,e)}var _E=k({diag_:Zj});function Jj(r,t,e,n,o=[1,1],s="NHWC"){let i=C(r,"x","dilation2d"),a=C(t,"filter","dilation2d");_(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),_(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),_(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let u=i,l=!1;i.rank===3&&(u=R(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=!0),_(u.shape[3]===a.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${u.shape[3]} vs ${a.shape[2]}`);let c={x:u,filter:a},p={strides:e,pad:n,dilations:o},m=T.runKernel(cs,c,p);return l?R(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Mx=k({dilation2d_:Jj});var Hr={};Kt(Hr,{assertAndGetBroadcastShape:()=>Mt,getBroadcastDims:()=>EE,getReductionAxes:()=>ye});function EE(r,t){let e=r.length,n=[];for(let o=0;o<e;o++){let s=e-1-o,i=r[s]||1;(t[t.length-1-o]||1)>1&&i===1&&n.unshift(s)}return n}function ye(r,t){let e=[];for(let n=0;n<t.length;n++){let o=r[r.length-n-1],s=t.length-n-1,i=t[s];(o==null||o===1&&i>1)&&e.unshift(s)}return e}function Mt(r,t){let e=Math.max(r.length,t.length),n=new Array(e);for(let o=0;o<e;o++){let s=r[r.length-o-1];s==null&&(s=1);let i=t[t.length-o-1];if(i==null&&(i=1),s===1)n[e-o-1]=i;else if(i===1)n[e-o-1]=s;else if(s!==i){let a=`Operands could not be broadcast together with shapes ${r} and ${t}.`;throw Error(a)}else n[e-o-1]=s}return n}function Qj(r,t){let e=C(r,"a","equal","string_or_numeric"),n=C(t,"b","equal","string_or_numeric");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(Wa,o)}var Fr=k({equal_:Qj});function t6(r,t,e){let n=C(t,"a","where"),o=C(e,"b","where"),s=C(r,"condition","where","bool"),i=Mt(Mt(s.shape,n.shape),o.shape),a=la(s,i),u=la(n,i),l=la(o,i),c={condition:a,t:u,e:l};return T.runKernel(Hi,c)}var be=k({where_:t6});function e6(r){let e={x:C(r,"x","zerosLike")};return T.runKernel(Yi,e)}var vt=k({zerosLike_:e6});function r6(r,t){let e=C(r,"a","div"),n=C(t,"b","div");[e,n]=jt(e,n);let o=ct(e,n),s=vt(o),i=Fr(n,s);return be(i,s,o)}var Lx=k({divNoNan_:r6});function n6(r,t){let e=C(r,"t1","dot"),n=C(t,"t2","dot");_((e.rank===1||e.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${n.rank}.`);let o=e.rank===1?e.size:e.shape[1],s=n.rank===1?n.size:n.shape[0];if(_(o===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${s}.`),e.rank===1&&n.rank===1){let i=R(e,[1,-1]),a=R(n,[-1,1]),u=Bt(i,a);return R(u,[])}else if(e.rank===1&&n.rank===2){let i=R(e,[1,-1]),a=R(n,[n.shape[0],n.shape[1]]),u=Bt(i,a);return R(u,[u.size])}else if(e.rank===2&&n.rank===1){let i=R(n,[-1,1]),a=Bt(e,i);return R(a,[a.size])}else{let i=R(n,[n.shape[0],n.shape[1]]);return Bt(e,i)}}var zx=k({dot_:n6});function o6(r,...t){let e=t.map((o,s)=>C(o,`tensors${s}`,"einsum")),n={equation:r};return T.runKernel(Wp,e,n)}var AE=k({einsum_:o6});function s6(r){let e={x:C(r,"x","elu","float32")};return T.runKernel(ms,e)}var ca=k({elu_:s6});function i6(r,t){let e=C(r,"x","ensureShape","string_or_numeric");if(!c0(e.shape,t))throw new Error(`EnsureShape: Shape of tensor ${e.shape} is not compatible with expected shape ${t}`);return r}var DE=k({ensureShape_:i6});function a6(r){let t=C(r,"x","erf");_(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=Q(t,"float32"));let e={x:t};return T.runKernel(fs,e)}var Bx=k({erf_:a6});function Z0(r,t){for(let e=0;e<r.length;++e)if(r[r.length-e-1]!==t-1-e)return!1;return!0}function $E(r,t,e){let n=r.length+t.length,o=[],s=0,i=0;for(let a=0;a<n;a++)e.indexOf(a)===-1?o.push(r[s++]):o.push(t[i++]);return o}function J0(r,t){let e=[],n=r.length;for(let s=0;s<n;s++)t.indexOf(s)===-1&&e.push(r[s]);let o=t.map(s=>r[s]);return[e,o]}function ko(r,t){let e=t.map(n=>1);return $E(r,e,t)}function l6(r,t,e){_(Z0(t,e),()=>`${r} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`)}function Q0(r,t){if(Z0(r,t))return null;let e=[];for(let n=0;n<t;++n)r.indexOf(n)===-1&&e.push(n);return r.forEach(n=>e.push(n)),e}function xh(r){return r.map((t,e)=>[e,t]).sort((t,e)=>t[1]-e[1]).map(t=>t[0])}function u6(r,t){let e=[];for(let n=t-r;n<t;++n)e.push(n);return e}function c6(r,t=null,e=!1){let o={x:C(r,"x","max")},s={reductionIndices:t,keepDims:e};return T.runKernel(Ts,o,s)}var Nr=k({max_:c6});function p6(r,t=null,e=!1){let o={x:C(r,"x","min")},s={axis:t,keepDims:e};return T.runKernel(Ds,o,s)}var bl=k({min_:p6});function m6(r,t){let e=C(r,"base","pow"),n=C(t,"exp","pow");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(Ls,o)}var pn=k({pow_:m6});function ft(r,t){if((or(r)&&t!=="string"||Array.isArray(r))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&or(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return un(r,[],[],t)}function f6(r){let e={x:C(r,"x","sqrt","float32")};return T.runKernel(ei,e)}var Ne=k({sqrt_:f6});function d6(r){let t=C(r,"x","square"),e={};return T.runKernel("Square",{x:t},e)}var Wt=k({square_:d6});function h6(r,t=null,e=!1){let n=C(r,"x","sum");n.dtype==="bool"&&(n=Q(n,"int32"));let o={x:n},s={axis:t,keepDims:e};return T.runKernel(ri,o,s)}var pt=k({sum_:h6});function g6(r,t="euclidean",e=null,n=!1){r=C(r,"x","norm");let o=RE(r,t,e),s=o.shape;if(n){let i=fr(e,r.shape);s=ko(o.shape,i)}return R(o,s)}function RE(r,t,e=null){if(r.rank===0)return Ee(r);if(r.rank!==1&&e===null)return RE(R(r,[-1]),t,e);if(r.rank===1||typeof e=="number"||Array.isArray(e)&&e.length===1){if(t===1)return pt(Ee(r),e);if(t===1/0)return Nr(Ee(r),e);if(t===-1/0)return bl(Ee(r),e);if(t==="euclidean"||t===2)return Ne(pt(pn(Ee(r),ft(2,"int32")),e));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(e)&&e.length===2){if(t===1)return Nr(pt(Ee(r),e[0]),e[1]-1);if(t===1/0)return Nr(pt(Ee(r),e[1]),e[0]);if(t===-1/0)return bl(pt(Ee(r),e[1]),e[0]);if(t==="fro"||t==="euclidean")return Ne(pt(Wt(r),e));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${e}`)}var wl=k({norm_:g6});function x6(r,t=null,e=!1){return wl(r,"euclidean",t,e)}var Vx=k({euclideanNorm_:x6});function y6(r){let e={x:C(r,"x","exp")};return T.runKernel(ds,e)}var ir=k({exp_:y6});function b6(r,t=0){let e=C(r,"x","expandDims","string_or_numeric");_(t<=e.rank,()=>"Axis must be <= rank of the tensor");let n={input:e},o={dim:t};return T.runKernel(Li,n,o)}var ar=k({expandDims_:b6});function w6(r){let e={x:C(r,"x","expm1")};return T.runKernel(hs,e)}var Gx=k({expm1_:w6});function I6(r,t){let e=C(r,"x","tile","string_or_numeric");_(e.rank===t.length,()=>`Error in transpose: rank of input ${e.rank} must match length of reps ${t}.`);let n={x:e},o={reps:t};return T.runKernel(lo,n,o)}var Or=k({tile_:I6});function C6(r,t,e,n="float32"){t==null&&(t=r);let o=wt([r,t],n),s=r<=t?r:t;for(let a=0;a<s;++a)o.set(1,a,a);let i=R(o.toTensor(),[r,t]);if(e==null)return i;if(e.length===1)return Or(ar(i,0),[e[0],1,1]);if(e.length===2)return Or(ar(ar(i,0),0),[e[0],e[1],1,1]);if(e.length===3)return Or(ar(ar(ar(i,0),0),0),[e[0],e[1],e[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${e.length}D.`)}var Cc=k({eye_:C6});function v6(r){let e={x:C(r,"x","floor","float32")};return T.runKernel(gs,e)}var pa=k({floor_:v6});function S6(r,t,e=0,n=0){let o=C(r,"x","gather"),s=C(t,"indices","gather","int32"),i={x:o,indices:s},a={axis:e,batchDims:n};return T.runKernel(zi,i,a)}var ma=k({gather_:S6});function N6(r,t){let e=C(r,"a","greater","string_or_numeric"),n=C(t,"b","greater","string_or_numeric");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(qa,o)}var Fe=k({greater_:N6});function k6(r,t){let e=C(r,"a","greaterEqual","string_or_numeric"),n=C(t,"b","greaterEqual","string_or_numeric");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(bs,o)}var mn=k({greaterEqual_:k6});function T6(r){let e={input:C(r,"input","imag")};return T.runKernel(qp,e)}var Tu=k({imag_:T6});function _6(r){let e={x:C(r,"x","isFinite")};return T.runKernel(ws,e)}var Wx=k({isFinite_:_6});function E6(r){let e={x:C(r,"x","isInf")};return T.runKernel(Is,e)}var Ux=k({isInf_:E6});function A6(r){let e={x:C(r,"x","isNaN")};return T.runKernel(Cs,e)}var Hx=k({isNaN_:A6});function D6(r,t=.2){let n={x:C(r,"x","leakyRelu")},o={alpha:t};return T.runKernel(vs,n,o)}var _u=k({leakyRelu_:D6});function $6(r,t){let e=C(r,"a","less","string_or_numeric"),n=C(t,"b","less","string_or_numeric");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(Ka,o)}var Il=k({less_:$6});function R6(r,t){let e=C(r,"a","lessEqual","string_or_numeric"),n=C(t,"b","lessEqual","string_or_numeric");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(ja,o)}var Un=k({lessEqual_:R6});function FE(r,t,e){if(e<=0)throw new Error("The number of values should be positive.");let n={start:r,stop:t,num:e};return T.runKernel(Xa,{},n)}function F6(r,t=5,e=1,n=1,o=.5){let s=C(r,"x","localResponseNormalization");_(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
| rank ${s.rank}.`),_($a(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,a=!1;s.rank===3&&(a=!0,i=R(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let u={x:i},l={depthRadius:t,bias:e,alpha:n,beta:o},c=T.runKernel(ks,u,l);return a?R(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var qx=k({localResponseNormalization_:F6});function O6(r){let e={x:C(r,"x","log","float32")};return T.runKernel(Ss,e)}var kr=k({log_:O6});function P6(r){let e={x:C(r,"x","log1p")};return T.runKernel(Ns,e)}var Eu=k({log1p_:P6});function M6(r){return _(Ai(r),()=>"The f passed in grad(f) must be a function"),(t,e)=>{let n=C(t,"x","tf.grad","string_or_numeric"),o=e!=null?C(e,"dy","tf.grad"):null;return T.tidy(()=>{let{value:s,grads:i}=T.gradients(()=>r(n),[n],o);return o!=null&&Re(s.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),jx(i),i[0]})}}function L6(r){return _(Ai(r),()=>"The f passed in grads(f) must be a function"),(t,e)=>{_(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=xl(t,"args","tf.grads","string_or_numeric"),o=e!=null?C(e,"dy","tf.grads"):null;return T.tidy(()=>{let{value:s,grads:i}=T.gradients(()=>r(...n),n,o);return o!=null&&Re(s.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),jx(i),i})}}function z6(r){return _(Ai(r),()=>"The f passed in valueAndGrad(f) must be a function"),(t,e)=>{_(t instanceof Ot,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),_(e==null||e instanceof Ot,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:o}=T.gradients(()=>r(t),[t],e);return jx(n),{grad:n[0],value:o}}}function B6(r){return _(Ai(r),()=>"The f passed in valueAndGrads(f) must be a function"),(t,e)=>{_(Array.isArray(t)&&t.every(o=>o instanceof Ot),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),_(e==null||e instanceof Ot,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=T.gradients(()=>r(...t),t,e);return e!=null&&Re(n.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),jx(n.grads),n}}function Kx(r,t){_(Ai(r),()=>"The f passed in variableGrads(f) must be a function"),_(t==null||Array.isArray(t)&&t.every(l=>l instanceof gl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let e=t!=null;if(!e){t=[];for(let l in T.registeredVariables)t.push(T.registeredVariables[l])}let n=e?t.filter(l=>!l.trainable):null,o=t.length;t=t.filter(l=>l.trainable),_(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);let s=!0,{value:i,grads:a}=T.gradients(r,t,null,s);_(a.some(l=>l!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),_(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let u={};return t.forEach((l,c)=>{a[c]!=null&&(u[l.name]=a[c])}),n!=null&&n.forEach(l=>u[l.name]=null),{value:i,grads:u}}function fn(r){return T.customGrad(r)}function jx(r){if(r.filter(e=>e==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
| the f you passed encloses all operations that lead from x to y.`)}function V6(r){let e={x:C(r,"x","neg")};return T.runKernel(Vi,e)}var Ut=k({neg_:V6});function G6(r){let e={x:C(r,"x","softplus")};return T.runKernel(ti,e)}var pi=k({softplus_:G6});function W6(r){let t=C(r,"x","logSigmoid");return fn(n=>({value:Ut(pi(Ut(n))),gradFunc:i=>$(i,en(Ut(n)))}))(t)}var Xx=k({logSigmoid_:W6});function U6(r,t){let e=C(r,"a","sub"),n=C(t,"b","sub");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(si,o)}var lt=k({sub_:U6});function H6(r,t=-1){let e=C(r,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and axis was ${t}`);return fn((o,s)=>{let a=Nr(o,t,!0),u=lt(o,a),l=lt(Q(u,"float32"),kr(pt(ir(u),t,!0)));return s([l]),{value:l,gradFunc:(p,m)=>{let[f]=m,d=!0,h=ir(f);return lt(p,$(pt(p,t,d),h))}}})(e)}var hm=k({logSoftmax_:H6});function q6(r,t=null,e=!1){let n=C(r,"x","logSumExp"),o=fr(t,n.shape),s=Nr(n,o,!0),i=lt(n,s),a=ir(i),u=pt(a,o),l=kr(u),c=Y(R(s,l.shape),l);if(e){let p=ko(c.shape,o);return R(c,p)}return c}var gm=k({logSumExp_:q6});function K6(r,t){let e=C(r,"a","logicalAnd","bool"),n=C(t,"b","logicalAnd","bool");Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(Ya,o)}var Pr=k({logicalAnd_:K6});function j6(r){let e={x:C(r,"x","logicalNot","bool")};return T.runKernel(Za,e)}var Au=k({logicalNot_:j6});function X6(r,t){let e=C(r,"a","logicalOr","bool"),n=C(t,"b","logicalOr","bool");Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(Ja,o)}var xm=k({logicalOr_:X6});function Y6(r,t){let e=C(r,"a","logicalXor","bool"),n=C(t,"b","logicalXor","bool");return Mt(e.shape,n.shape),Pr(xm(r,t),Au(Pr(r,t)))}var Yx=k({logicalXor_:Y6});var Zx=2147483648;function Z6(r,t,e="left"){let n=C(r,"sortedSequence","searchSorted"),o=C(t,"values","searchSorted"),s=n.shape[n.shape.length-1],i=o.shape[o.shape.length-1],a=R(n,[-1,s]),u=R(o,[-1,i]);if(a.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(a.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(te(u.shape)>=Zx)throw new Error(`values tensor size must less than ${Zx}`);if(a.shape[1]>=Zx)throw new Error(`trailing dim_size must less than ${Zx} for int32 output type, was ${a.shape[1]}`);let l={sortedSequence:a,values:u},c={side:e};return T.runKernel(ul,l,c)}var yh=k({searchSorted_:Z6});function OE(r,t){return yh(r,t,"left")}function J6(r,t,e,n,o){let s=C(r,"x","maxPool"),i=1,a=s,u=!1;s.rank===3&&(u=!0,a=R(s,[1,s.shape[0],s.shape[1],s.shape[2]])),_(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),_(Rr(e,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`),Se("maxPool",n,o);let l={x:a},c={filterSize:t,strides:e,pad:n,dimRoundingMode:o},p=T.runKernel(Es,l,c);return u?R(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Du=k({maxPool_:J6});function Q6(r,t=[1,1,1],e,n,o,s="NDHWC"){let i=C(r,"x","maxPool3d"),a=i,u=!1;i.rank===4&&(u=!0,a=R(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),_(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),_(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Se("maxPool3d",n,o);let l={x:a},c={filterSize:t,strides:e,pad:n,dimRoundingMode:o,dataFormat:s},p=T.runKernel(Bi,l,c);return u?R(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Jx=k({maxPool3d_:Q6});function tX(r,t,e,n,o=!1){let i={x:C(r,"x","maxPoolWithArgmax")},a={filterSize:t,strides:e,pad:n,includeBatchInIndex:o},u=T.runKernel(lu,i,a);return{result:u[0],indexes:u[1]}}var PE=k({maxPoolWithArgmax_:tX});function eX(r,t){let e=C(r,"a","maximum"),n=C(t,"b","maximum");[e,n]=jt(e,n),e.dtype==="bool"&&(e=Q(e,"int32"),n=Q(n,"int32")),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(_s,o)}var _n=k({maximum_:eX});function rX(r,t=null,e=!1){let o={x:C(r,"x","mean")},s={axis:t,keepDims:e};return T.runKernel(As,o,s)}var ke=k({mean_:rX});function Te(r,t="float32"){if(Me(r),t==="complex64"){let n=Te(r,"float32"),o=Te(r,"float32");return kn(n,o)}let e=Lp(te(r),t);return T.makeTensor(e,r,t)}function dr(r,t="float32"){if(Me(r),t==="complex64"){let n=dr(r,"float32"),o=Te(r,"float32");return kn(n,o)}let e=eh(te(r),t);return T.makeTensor(e,r,t)}function ME(r,t,{indexing:e="xy"}={}){if(e!=="xy"&&e!=="ij")throw new TypeError(`${e} is not a valid third argument to meshgrid`);if(r===void 0)return[];let n=C(r,"x","meshgrid",r instanceof Ot?r.dtype:"float32");if(t===void 0)return[n];let o=C(t,"y","meshgrid",t instanceof Ot?t.dtype:"float32"),s=te(n.shape),i=te(o.shape);return e==="xy"?(n=R(n,[1,-1]),o=R(o,[-1,1]),[Bt(dr([i,1],n.dtype),n),Bt(o,dr([1,s],o.dtype))]):(n=R(n,[-1,1]),o=R(o,[1,-1]),[Bt(n,dr([1,i],n.dtype)),Bt(dr([s,1],o.dtype),o)])}function nX(r,t){let e=C(r,"a","minimum"),n=C(t,"b","minimum");[e,n]=jt(e,n),e.dtype==="bool"&&(e=Q(e,"int32"),n=Q(n,"int32")),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel($s,o)}var mo=k({minimum_:nX});function oX(r,t,e){_(e==="reflect"||e==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${e}.`);let n=C(r,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");_(t.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${t.length}.`);let o=e==="reflect"?1:0;for(let a=0;a<n.rank;a++)_(t[a].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),_(t[a][0]>=0&&t[a][0]<=n.shape[a]-o&&t[a][1]>=0&&t[a][1]<=n.shape[a]-o,()=>`Padding in dimension ${a} cannot be greater than or equal to ${n.shape[a]-o} or less than 0 for input of shape ${n.shape}`);let s={paddings:t,mode:e},i={x:n};return T.runKernel(Rs,i,s)}var Qx=k({mirrorPad_:oX});function sX(r,t){let e=C(r,"a","mod"),n=C(t,"b","mod");[e,n]=jt(e,n);let o={a:e,b:n};return T.runKernel(Fs,o)}var ty=k({mod_:sX});function iX(r,t=null,e=!1){r=C(r,"x","moments");let n=fr(t,r.shape),o=ke(r,n,e),s=o.shape;e||(s=ko(o.shape,n));let i=Wt(lt(Q(r,"float32"),R(o,s))),a=ke(i,n,e);return{mean:o,variance:a}}var vc=k({moments_:iX});function aX(r,t,e,n){let o=C(t,"data","multiRNNCell"),s=xl(e,"c","multiRNNCell"),i=xl(n,"h","multiRNNCell"),a=o,u=[];for(let p=0;p<r.length;p++){let m=r[p](a,s[p],i[p]);u.push(m[0]),u.push(m[1]),a=m[1]}let l=[],c=[];for(let p=0;p<u.length;p+=2)l.push(u[p]),c.push(u[p+1]);return[l,c]}var LE=k({multiRNNCell_:aX});function lX(r,t,e,n=!1){let o=C(r,"logits","multinomial"),s=o.size,i=o.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);e=e||Math.random();let u={logits:i===1?R(o,[1,-1]):o},l={numSamples:t,seed:e,normalized:n},c=T.runKernel(tl,u,l);return i===1?R(c,[c.size]):c}var zE=k({multinomial_:lX});function uX(r,t){let e=C(r,"a","notEqual","string_or_numeric"),n=C(t,"b","notEqual","string_or_numeric");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n};return T.runKernel(el,o)}var mi=k({notEqual_:uX});function cX(r,t,e=1,n=0,o="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let i={indices:C(r,"indices","oneHot","int32")},a={dtype:o,depth:t,onValue:e,offValue:n};return T.runKernel(Ps,i,a)}var fa=k({oneHot_:cX});function pX(r){let e={x:C(r,"x","onesLike")};return T.runKernel(Gi,e)}var Ir=k({onesLike_:pX});function mX(r,t){let e=C(r,"v1","outerProduct"),n=C(t,"v2","outerProduct");_(e.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${e.rank} and ${n.rank}.`);let o=R(e,[-1,1]),s=R(n,[1,-1]);return Bt(o,s)}var BE=k({outerProduct_:mX});function fX(r,t,e=0){let n=C(r,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let o={paddings:t,constantValue:e},s={x:n};return T.runKernel(Ms,s,o)}var dn=k({pad_:fX});function dX(r,t,e=0){return _(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),dn(r,[t],e)}var VE=k({pad1d_:dX});function hX(r,t,e=0){return _(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),dn(r,t,e)}var GE=k({pad2d_:hX});function gX(r,t,e=0){return _(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),dn(r,t,e)}var WE=k({pad3d_:gX});function xX(r,t,e=0){return _(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),dn(r,t,e)}var UE=k({pad4d_:xX});function yX(r,t,e){let n=C(r,"x","spaceToBatchND");_(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),_(e.length===t.length,()=>`paddings.shape[0] ${e.length} must be equal to [blockShape] ${t.length}`),_(n.shape.reduce((i,a,u)=>u>0&&u<=t.length?i&&(a+e[u-1][0]+e[u-1][1])%t[u-1]===0:i,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${e.toString()} must be divisible by blockShapes ${t.toString()}`);let o={x:n},s={blockShape:t,paddings:e};return T.runKernel(Ki,o,s)}var $u=k({spaceToBatchND_:yX});function bX(r,t,e,n,o,s,i){o==null&&(o=[1,1]),s==null&&(s=1),n===0&&(n="valid");let a=C(r,"x","maxPool"),u=a,l=!1;a.rank===3&&(l=!0,u=R(a,[1,a.shape[0],a.shape[1],a.shape[2]])),_(Rr(s,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);let c=X0(u.shape,t,s,o,n),p=[c.dilationHeight,c.dilationWidth],m;n==="same"?m=IX([c.filterHeight,c.filterWidth],p):m=[[0,0],[0,0]];let f=p[0]===1&&p[1]===1,[d,h]=wX([c.inHeight,c.inWidth],p,m),g=f?n:"valid",x=f?u:$u(u,p,d),w=(e==="avg"?()=>Su(x,t,s,g,i):()=>Du(x,t,s,g,i))(),I=f?w:Nu(w,p,h);return l?R(I,[I.shape[1],I.shape[2],I.shape[3]]):I}function wX(r,t,e){let n=e.map(c=>c[0]),o=e.map(c=>c[1]),s=r.concat(n,o),i=t.map((c,p)=>(c-s[p]%c)%c),a=o.map((c,p)=>c+i[p]),u=t.map((c,p)=>[n[p],a[p]]),l=t.map((c,p)=>[0,i[p]]);return[u,l]}function IX(r,t){let n=r.map((i,a)=>i+(i-1)*(t[a]-1)).map(i=>i-1),o=n.map(i=>Math.floor(i/2)),s=n.map((i,a)=>i-o[a]);return n.map((i,a)=>[o[a],s[a]])}var ey=k({pool_:bX});function CX(r,t){let e=C(r,"x","prelu"),n=C(t,"alpha","prelu"),o={x:e,alpha:n};return T.runKernel(zs,o)}var Ru=k({prelu_:CX});function vX(r,t=null,e=!1){let n=C(r,"x","prod");n.dtype==="bool"&&(n=Q(n,"int32"));let o={x:n},s={axis:t,keepDims:e};return T.runKernel(Bs,o,s)}var ry=k({prod_:vX});function SX(r,t,e,n){let o=r.map((c,p)=>C(c,`tensors${p}`,"raggedGather","int32")),s=C(t,"paramsDenseValues","raggedGather"),i=C(e,"indices","raggedGather","int32"),a={paramsNestedSplits:o,paramsDenseValues:s,indices:i},u={outputRaggedRank:n},l=T.runKernel(Kp,a,u);return{outputNestedSplits:l.slice(0,l.length-1),outputDenseValues:l[l.length-1]}}var HE=k({raggedGather_:SX});function NX(r,t,e){let n=C(r,"starts","raggedRange"),o=C(t,"limits","raggedRange",n.dtype),s=C(e,"deltas","raggedRange",n.dtype),i={starts:n,limits:o,deltas:s},a=T.runKernel(jp,i);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}var qE=k({raggedRange_:NX});function kX(r,t,e,n,o){let s=C(r,"shape","raggedTensorToTensor","int32"),i=C(t,"values","raggedTensorToTensor"),a=C(e,"defaultValue","raggedTensorToTensor",i.dtype),u=n.map((p,m)=>C(p,`tensors${m}`,"raggedTensorToTensor","int32")),l={shape:s,values:i,defaultValue:a,rowPartitionTensors:u},c={rowPartitionTypes:o};return T.runKernel(Xp,l,c)}var KE=k({raggedTensorToTensor_:kX});function TX(r,t,e){Me(r);let n=te(r),o=null;if(e==null||e==="float32")o=new Float32Array(n);else if(e==="int32")o=new Int32Array(n);else if(e==="bool")o=new Uint8Array(n);else throw new Error(`Unknown data type ${e}`);for(let s=0;s<n;s++)o[s]=t();return T.makeTensor(o,r,e)}var jE=k({rand_:TX});var ay=Xl(bh());var dA={};Kt(dA,{TEST_EPSILON_FLOAT16:()=>pA,createVideoElement:()=>BX,encodeStrings:()=>fA,expectArrayBuffersEqual:()=>zX,expectArraysClose:()=>OX,expectArraysEqual:()=>MX,expectNumbersClose:()=>mA,expectPromiseToFail:()=>PX,expectValuesInRange:()=>LX,play:()=>VX,testEpsilon:()=>oy});var FX=.001,pA=.1;function OX(r,t,e){return e==null&&(e=oy()),aN(r,t,(n,o)=>lN(n,o,e))}function oy(){return T.backend.floatPrecision()===32?FX:pA}function aN(r,t,e){let n=!0;if((or(r)||or(t))&&(n=!1),or(r)&&or(t)&&(n=!0),n){let i=r.constructor.name,a=t.constructor.name;if(i!==a)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${a}`)}if(Array.isArray(r)&&Array.isArray(t)){let i=Ur(r),a=Ur(t);if(!an(i,a))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${a}]`)}let o=or(r)?r:ui(r),s=or(t)?t:ui(t);if(o.length!==s.length)throw new Error(`Arrays have different lengths actual: ${o.length} vs expected: ${s.length}.
| Actual: ${o}.
| Expected: ${s}.`);for(let i=0;i<s.length;++i){let a=o[i],u=s[i];if(!e(a,u))throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${u}.
| Actual: ${o}.
| Expected: ${s}.`)}typeof expect!="undefined"&&expect().nothing()}function PX(r,t){r().then(()=>t.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function MX(r,t){let e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ho(r)||Ho(r[0])||Ho(t)||Ho(t[0])?aN(r,e,(n,o)=>n==o):aN(r,t,(n,o)=>lN(n,o,0))}function mA(r,t,e){if(e==null&&(e=oy()),!lN(r,t,e))throw new Error(`Numbers differ: actual === ${r}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function lN(r,t,e){return!isFinite(r)&&!isFinite(t)?!0:!(isNaN(r)||isNaN(t)||Math.abs(r-t)>e)}function LX(r,t,e){for(let n=0;n<r.length;n++)if(r[n]<t||r[n]>e)throw new Error(`Value out of range:${r[n]} low: ${t}, high: ${e}`)}function zX(r,t){let e=new Float32Array(r),n=new Float32Array(t);if(e.length!==n.length)throw new Error(`Expected ArrayBuffer to be of length ${n.length}, but it was ${e.length}`);for(let o=0;o<n.length;o++)if(e[o]!==n[o])throw new Error(`Expected ArrayBuffer value at ${o} to be ${n[o]} but got ${e[o]} instead`)}function fA(r){for(let t=0;t<r.length;t++){let e=r[t];Array.isArray(e)?fA(e):r[t]=wu(e)}return r}function BX(r){let t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(r),new Promise(e=>{t.addEventListener("loadeddata",n=>e(t)),t.load()})}async function VX(r){await r.play(),"requestVideoFrameCallback"in r&&await new Promise(t=>{r.requestVideoFrameCallback(t)})}var Nc=class{constructor(t,e,n,o,s){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=o,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let i=s||Math.random();this.random=ay.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){let o=this.nextVal;return this.nextVal=NaN,o}let t,e,n=!1;for(;!n;){let o,s,i;do o=2*this.random()-1,s=2*this.random()-1,i=o*o+s*s;while(i>=1||i===0);let a=Math.sqrt(-2*Math.log(i)/i);t=this.mean+this.stdDev*o*a,e=this.mean+this.stdDev*s*a,(!this.truncated||this.isValidTruncated(t))&&(n=!0)}return(!this.truncated||this.isValidTruncated(e))&&(this.nextVal=this.convertValue(e)),this.convertValue(t)}convertValue(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)}isValidTruncated(t){return t<=this.upper&&t>=this.lower}},sy=class{constructor(t,e,n,o){this.alpha=t,this.beta=1/e,this.dtype=n;let s=o||Math.random();this.randu=ay.alea(s.toString()),this.randn=new Nc(0,1,n,!1,this.randu()),t<1?this.d=t+2/3:this.d=t-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let t,e,n,o,s,i;for(;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,t=o*o,e=1-.331*t*t,n=.5*t+this.d*(1-i+Math.log(i)),s=this.randu(),s<e||Math.log(s)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)}convertValue(t){return this.dtype==="float32"?t:Math.round(t)}},iy=class{constructor(t=0,e=1,n,o){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=t,this.range=e-t,this.dtype=n,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${t} - ${e} <= 1 and dtype is not float`);this.random=ay.alea(o)}convertValue(t){return this.canReturnFloat()?t:Math.round(t)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function GX(r,t,e=1,n="float32",o){if(Me(r),e==null&&(e=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new sy(t,e,n,o),i=wt(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var hA=k({randomGamma_:GX});function WX(r,t=0,e=1,n,o){if(Me(r),n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new Nc(t,e,n,!1,o),i=wt(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var kc=k({randomNormal_:WX});function UX(r,t,e){if(t!=null&&t==="bool")throw new Error(`Unsupported data type ${t}`);return kc(r,0,1,t,e)}var gA=k({randomStandardNormal_:UX});function HX(r,t=0,e=1,n="float32",o){Me(r);let s=wt(r,n),i=new iy(t,e,null,o);for(let a=0;a<s.values.length;a++)s.values[a]=i.nextValue();return s.toTensor()}var Hn=k({randomUniform_:HX});function qX(r,t,e,n){return Hn(r,t,e,"int32",n)}var xA=k({randomUniformInt_:qX});function da(r,t,e=1,n="float32"){if(e===0)throw new Error("Cannot have a step of zero");let o={start:r,stop:t,step:e,dtype:n};return T.runKernel(uu,{},o)}function KX(r){let e={input:C(r,"input","real")};return T.runKernel(Yp,e)}var Cl=k({real_:KX});function jX(r){let e={x:C(r,"x","reciprocal")};return T.runKernel(Vs,e)}var ly=k({reciprocal_:jX});function XX(r){let e={x:C(r,"x","relu")};return T.runKernel(Gs,e)}var Mr=k({relu_:XX});function YX(r){let e={x:C(r,"x","relu6")};return T.runKernel(Hs,e)}var ym=k({relu6_:YX});function ZX(r,t){let n={x:C(r,"x","reverse")},o={dims:t};return T.runKernel(qs,n,o)}var hr=k({reverse_:ZX});function JX(r){let t=C(r,"x","reverse");return _(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),hr(t,0)}var yA=k({reverse1d_:JX});function QX(r,t){let e=C(r,"x","reverse");return _(e.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${e.rank}.`),hr(e,t)}var bA=k({reverse2d_:QX});function t5(r,t){let e=C(r,"x","reverse");return _(e.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${e.rank}.`),hr(e,t)}var wA=k({reverse3d_:t5});function e5(r,t){let e=C(r,"x","reverse");return _(e.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${e.rank}.`),hr(e,t)}var IA=k({reverse4d_:e5});function r5(r){let e={x:C(r,"x","round")};return T.runKernel(Ks,e)}var bm=k({round_:r5});function n5(r){let e={x:C(r,"x","rsqrt","float32")};return T.runKernel(js,e)}var wm=k({rsqrt_:n5});function o5(r){let e={x:C(r,"x","selu")};return T.runKernel(Xs,e)}var Im=k({selu_:o5});function s5(r,t,e,n,o,s=[1,1],i="NHWC"){let a=C(r,"x","separableConv2d"),u=C(t,"depthwiseFilter","separableConv2d"),l=C(e,"pointwiseFilter","separableConv2d"),c=a,p=!1;if(a.rank===3&&(p=!0,c=R(a,[1,a.shape[0],a.shape[1],a.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");_(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),_(u.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`),_(l.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`),_(l.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`),_(l.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`);let m=u.shape[2],f=u.shape[3];_(l.shape[2]===m*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*f}, but got ${l.shape[2]}.`);let d=ua(c,u,n,o,i,s),g=Tn(d,l,1,"valid",i);return p?R(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Cm=k({separableConv2d_:s5});async function i5(r,t){let e=C(r,"x","setdiff1d"),n=C(t,"y","setdiff1d");_(e.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${e.dtype}) and y (${n.dtype}).`),_(e.rank===1,()=>`x should be 1D tensor, but got x (${e.shape}).`),_(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let o=await e.data(),s=await n.data(),i=new Set(s),a=0;for(let c=0;c<o.length;c++)i.has(o[c])||a++;let u=new le([a],e.dtype),l=new le([a],"int32");for(let c=0,p=0;c<o.length;c++)i.has(o[c])||(u.values[p]=o[c],l.values[p]=c,p++);return[u.toTensor(),l.toTensor()]}var CA=i5;function a5(r){let e={x:C(r,"x","sign")};return T.runKernel(Js,e)}var uy=k({sign_:a5});function l5(r){let e={x:C(r,"x","sin","float32")};return T.runKernel(Ys,e)}var vm=k({sin_:l5});function u5(r){let e={x:C(r,"x","sinh")};return T.runKernel(Zs,e)}var Sm=k({sinh_:u5});function c5(r,t,e){let n=C(r,"x","slice1d");return _(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),Pt(n,[t],[e])}var Nm=k({slice1d_:c5});function p5(r,t,e){let n=C(r,"x","slice2d");return _(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),Pt(n,t,e)}var wh=k({slice2d_:p5});function m5(r,t,e){let n=C(r,"x","slice3d");return _(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),Pt(n,t,e)}var km=k({slice3d_:m5});function f5(r,t,e){let n=C(r,"x","slice4d");return _(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),Pt(n,t,e)}var Tc=k({slice4d_:f5});function d5(r,t=-1){let e=C(r,"logits","softmax","float32");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and dim was ${t}`);let n={logits:e},o={dim:t};return T.runKernel(ni,n,o)}var Fu=k({softmax_:d5});function h5(r){_(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let t={input:r};return T.runKernel(Up,t)}var Ou=k({fft_:h5});function g5(r){_(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let t={input:r};return T.runKernel(Hp,t)}var vl=k({ifft_:g5});function x5(r){let t=r.shape[r.shape.length-1],e=r.size/t,n;if(t<=2){let o=R(r,[e,t]);n=vl(o)}else{let o=[e,2*(t-1)],s=R(Cl(r),[e,t]),i=R(Tu(r),[e,t]),a=hr(Pt(s,[0,1],[e,t-2]),1),u=$(hr(Pt(i,[0,1],[e,t-2]),1),ft(-1)),l=ie([s,a],1),c=ie([i,u],1),p=R(kn(l,c),[o[0],o[1]]);n=vl(p)}if(n=Cl(n),r.rank===3&&r.shape[0]!==0){let o=n,s=r.shape[0];n=R(n,[s,n.shape[0]/s,n.shape[1]]),o.dispose()}return n}var Tm=k({irfft_:x5});function y5(r,t,e=0){let o={x:C(r,"x","split")},s={numOrSizeSplits:t,axis:e};return T.runKernel(ji,o,s)}var gr=k({split_:y5});function b5(r,t){_(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let e=r.shape[r.shape.length-1],n=r.size/e,o;if(t!=null&&t<e){let d=r.shape.map(g=>0),h=r.shape.map(g=>g);h[r.shape.length-1]=t,o=Pt(r,d,h),e=t}else if(t!=null&&t>e){let d=r.shape.map(h=>h);d[r.shape.length-1]=t-e,o=ie([r,Te(d)],r.shape.length-1),e=t}else o=r;let s=vt(o),i=R(kn(o,s),[n,e]),a=Ou(i),u=Math.floor(e/2)+1,l=Cl(a),c=Tu(a),p=gr(l,[u,e-u],l.shape.length-1),m=gr(c,[u,e-u],c.shape.length-1),f=o.shape.slice();return f[o.shape.length-1]=u,R(kn(p[0],m[0]),f)}var Pu=k({rfft_:b5});function w5(r,t){let e=C(r,"a","squaredDifference"),n=C(t,"b","squaredDifference");[e,n]=jt(e,n),Mt(e.shape,n.shape);let o={a:e,b:n},s={};return T.runKernel(oi,o,s)}var _m=k({squaredDifference_:w5});function I5(r,t){let e=C(r,"x","squeeze","string_or_numeric");return R(e,p0(e.shape,t).newShape)}var qn=k({squeeze_:I5});function C5(r,t=0){let e=xl(r,"tensors","stack","string_or_numeric");_(e.length>=1,()=>"Pass at least one tensor to tf.stack"),e.length>0&&_(t<=e[0].rank,()=>"Axis must be <= rank of the tensor");let n=e,o={axis:t};return T.runKernel(Wi,n,o)}var qe=k({stack_:C5});function v5(r,t=0){let n={x:C(r,"x","step")},o={alpha:t};return T.runKernel(wo,n,o)}var To=k({step_:v5});function S5(r,t,e,n,o=0,s=0,i=0,a=0,u=0){let c={x:C(r,"x","stridedSlice","string_or_numeric")},p={begin:t,end:e,strides:n,beginMask:o,endMask:s,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:u};return T.runKernel(ml,c,p)}var cy=k({stridedSlice_:S5});function N5(r){let e={x:C(r,"x","tan","float32")};return T.runKernel(ii,e)}var py=k({tan_:N5});function Ke(r,t){io(r);let e=Ur(r,t);if(e.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return un(r,null,e,t)}function fi(r,t,e){if(io(r),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=Ur(r,e);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return un(r,t,n,e)}function my(r,t,e){if(io(r),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=Ur(r,e);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return un(r,t,n,e)}function vA(r,t,e){if(io(r),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=Ur(r,e);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return un(r,t,n,e)}function SA(r,t,e){if(io(r),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=Ur(r,e);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return un(r,t,n,e)}function NA(r,t,e){if(io(r),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=Ur(r,e);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,un(r,t,n,e)}var Mu={};Kt(Mu,{calculateShapes:()=>kA,validateInput:()=>Em,validateUpdateShape:()=>uN});function uN(r,t,e){let n=t.rank>1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${e.shape}, indices.shape: ${t.shape}, shape: ${r}, sliceDim: ${n}, and batchDim: ${o}.`;if(e.rank<o)throw new Error(s+` update.rank < ${o}. `);if(r.length<n+(e.rank-o))throw new Error(s+` Output shape length < ${n+(e.rank-o)}`);if(e.rank!==o+r.length-n)throw new Error(s+` update.rank != ${o+r.length-n}`);for(let i=0;i<o;++i)if(e.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${e.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<e.rank-o;++i)if(e.shape[i+o]!==r[i+n])throw new Error(s+` updates.shape[${i+o}] (${e.shape[i+o]}) != shape[${i+o}] (${r[i+o]})`)}function Em(r,t,e){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(r.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${r.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(e.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${e}`);if(e.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(r.size===0)throw new Error(`Updates specified for empty output. updates shape: ${r.shape}`)}uN(e,t,r)}function kA(r,t,e){let n=t.shape.length,o=n>1?t.shape[n-1]:1,s=e.length,i=1;for(let p=o;p<s;++p)i*=e[p];let a=o<1?1:o,u=te(t.shape)/a,l=[...Di(e.slice(0,o)),1],c=te(e);return{sliceRank:o,numUpdates:u,sliceSize:i,strides:l,outputSize:c}}function k5(r,t,e){let n=C(r,"tensor","tensorScatterupdate"),o=C(t,"indices","tensorScatterupdate","int32"),s=C(e,"updates","tensorScatterupdate");if(Em(s,o,n.shape),n.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${n.dtype} and ${s.dtype}.`);let i={tensor:n,indices:o,updates:s},a={};return T.runKernel(ll,i,a)}var TA=k({tensorScatterUpdate_:k5});function T5(r,t=1,e=!0){let n=C(r,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let o=n.shape[n.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);let s={x:n},i={k:t,sorted:e},[a,u]=T.runKernel(fl,s,i);return{values:a,indices:u}}var fy=k({topk_:T5});function _5(r,t=0,e=1,n,o){if(Me(r),n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Nc(t,e,n,!0,o),i=wt(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var Am=k({truncatedNormal_:_5});function E5(r,t=0){let e=C(r,"x","unique","string_or_numeric");_(e.rank>0,()=>"The input tensor must be at least 1D");let n={x:e},o={axis:t},[s,i]=T.runKernel(xu,n,o);return{values:s,indices:i}}var dy=k({unique_:E5});function A5(r,t,e){let n=C(r,"x","unsortedSegmentSum"),o=C(t,"segmentIds","unsortedSegmentSum","int32");_($a(e),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:o},i={numSegments:e};return T.runKernel(yu,s,i)}var Dm=k({unsortedSegmentSum_:A5});function D5(r,t=0){let e=C(r,"x","unstack","string_or_numeric");_(t>=-e.shape.length&&t<e.shape.length,()=>`Axis = ${t} is not in [-${e.shape.length}, ${e.shape.length})`);let n={value:e},o={axis:t};return T.runKernel(Xi,n,o)}var xr=k({unstack_:D5});function _A(r,t){return yh(r,t,"right")}function hy(r,t=!0,e,n){return T.makeVariable(r,t,e,n)}function gy(r,t){let e=[];for(let s=0;s<t.length;s++)t[s]&&e.push(s);let n=wt(r,"int32"),o=wt([e.length,r.length],"int32");for(let s=0;s<e.length;s++){let i=n.indexToLoc(e[s]),a=s*r.length;o.values.set(i,a)}return o.toTensor()}async function $5(r){let t=C(r,"condition","whereAsync","bool"),e=await t.data(),n=gy(t.shape,e);return r!==t&&t.dispose(),n}var xy=$5;async function R5(r,t,e){let n=C(r,"tensor","boolMask"),o=C(t,"mask","boolMask","bool"),s=e==null?0:e,i=o.rank,a=n.shape;_(i>0,()=>"mask cannot be scalar"),Re(a.slice(s,s+i),o.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let h=s;h<s+i;h++)u*=a[h];let l=a.slice(0,s).concat([u],a.slice(s+i)),c=R(n,l),p=R(o,[-1]),m=await xy(p),f=qn(m,[1]),d=ma(c,f,s);return r!==n&&n.dispose(),t!==o&&o.dispose(),f.dispose(),c.dispose(),p.dispose(),m.dispose(),d}var F5=R5;function O5(r,t,e){let n=C(r,"x","transpose");if(t==null&&(t=n.shape.map((i,a)=>a).reverse()),_(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(i=>{_(i>=0&&i<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let o={x:n},s={perm:t};return n.dtype==="complex64"?B(()=>{let i=Cl(n),a=Tu(n);return i=T.runKernel(uo,{x:i},s),a=T.runKernel(uo,{x:a},s),e&&(a=Ut(a)),kn(i,a)}):T.runKernel(uo,o,s)}var Vt=k({transpose_:O5});function P5(r,t,e,n,o=!0){let s=C(r,"v","movingAverage"),i=C(t,"x","movingAverage"),a=C(e,"decay","movingAverage");$0(s,i),_(an(s.shape,i.shape),()=>"Shape mismatch in v and x");let u=ft(1),l=lt(u,a),c=$(lt(i,s),l);if(o){_(n!=null,()=>"When using zeroDebias: true, step is required.");let p=C(n,"step","movingAverage");c=ct(c,lt(u,pn(a,p)))}return Y(s,c)}var M5=k({movingAverage_:P5});function L5(r,t,e){Me(e);let n=C(r,"indices","scatterND","int32"),o=C(t,"updates","scatterND");Em(o,n,e);let s={indices:n,updates:o},i={shape:e};return T.runKernel(al,s,i)}var z5=k({scatterND_:L5});function EA(r,t,e,n){if(r.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${r.dtype}.`);if(r.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${r.shape}.`);let o=r.rank>0?r.shape[0]:1,s=r.rank>1?r.shape[1]:1;if(e.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${e.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===o))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${o}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function V5(r,t,e,n=0){Me(e);let o=C(r,"sparseIndices","sparseToDense","int32"),s=C(t,"sparseValues","sparseToDense","string_or_numeric"),i=C(n,"defaultValue","sparseToDense",s.dtype);EA(o,s,e,i);let a={sparseIndices:o,sparseValues:s,defaultValue:i},u={outputShape:e};return T.runKernel(pl,a,u)}var G5=k({sparseToDense_:V5});function W5(r,t){let e=C(t,"indices","gatherND","int32"),o={params:C(r,"x","gatherND","string_or_numeric"),indices:e};return T.runKernel(Ha,o)}var U5=k({gatherND_:W5});function AA(r,t){if(t==null)return r.shape.slice();if(an(r.shape,t))return t;if(r.shape.length===t.length){let e=[];for(let n=0;n<r.shape.length;n++)t[n]==null&&r.shape[n]!=null?e.push(r.shape[n]):e.push(t[n]);return e}return t}function H5(r,t,e,n){let o=C(r,"x","dropout");if(_(o.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),_(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return r instanceof Ot?o.clone():o;let s=AA(o,e),i=1-t,a=ct(pa(Y(Hn(s,0,1,"float32",n),i)),i);return $(o,a)}var cN=k({dropout_:H5});function pN(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function Ih(r,t,e){let n=1-r%2,o=new Float32Array(r);for(let s=0;s<r;++s){let i=2*Math.PI*s/(r+n-1);o[s]=t-e*Math.cos(i)}return Ke(o,"float32")}async function q5(r,t,e=1){let n=C(r,"predictions","inTopK"),o=C(t,"targets","inTopK");_(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),_(n.rank-1===o.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${o.rank}`),Re(n.shape.slice(0,n.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=n.shape[n.shape.length-1];_(e>0&&e<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${e}`);let i=await n.data(),a=await o.data(),[u,l]=[i.length/s,s],c=m0("bool",u);for(let p=0;p<u;p++){let m=p*l,f=i.subarray(m,m+l),d=[];for(let h=0;h<f.length;h++)d.push({value:f[h],index:h});d.sort((h,g)=>g.value-h.value),c[p]=0;for(let h=0;h<e;h++)if(d[h].index===a[p]){c[p]=1;break}}return r!==n&&n.dispose(),t!==o&&o.dispose(),sr(c,o.shape,"bool")}var K5=q5;var Lu={};Kt(Lu,{conv2d:()=>DA,depthwiseConv2d:()=>$A,matMul:()=>RA});function j5(r,t,e,n,o,s="NHWC",i){let a=r;r.rank===3&&(a=R(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let u=t;u.rank===3&&(u=R(t,[1,t.shape[0],t.shape[1],t.shape[2]])),_(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),_(u.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`),_(e.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${e}.`);let l=s==="NHWC"?a.shape[3]:a.shape[1],c=s==="NHWC"?u.shape[3]:u.shape[1];_(l===e[2],()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${e[2]}.`),_(c===e[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${e[3]}).`),Se("conv2dDerFilter",o,i);let p={x:a,dy:u},m={strides:n,pad:o,dataFormat:s,dimRoundingMode:i,filterShape:e};return T.runKernel(Bp,p,m)}var $m=k({conv2DBackpropFilter_:j5});function _c(r,t,e){if(e==null||e==="linear")return r;if(e==="relu")return $(r,To(t));throw new Error(`Cannot compute gradient for fused activation ${e}.`)}function Ec(r,t){let e=t,n=ye(r.shape,t.shape);return n.length>0&&(e=pt(e,n)),R(e,r.shape)}function Ac(r,t,e,n){if(t==="linear")return r;if(t==="relu")return Mr(r);if(t==="elu")return ca(r);if(t==="relu6")return ym(r);if(t==="prelu")return Ru(r,e);if(t==="leakyrelu")return _u(r,n);if(t==="sigmoid")return en(r);throw new Error(`Unknown fused activation ${t}.`)}var Dc=(r,t)=>!(r>0)||t==="linear";function X5({x:r,filter:t,strides:e,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:a,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(u=u||"linear",Dc(T.state.gradientDepth,u)===!1){_(o==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${o} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let E=Tn(r,t,e,n,o,s,i);return a!=null&&(E=Y(E,a)),Ac(E,u,l,c)}let p=C(r,"x","conv2d","float32"),m=C(t,"filter","conv2d","float32"),f=p,d=!1;p.rank===3&&(d=!0,f=R(p,[1,p.shape[0],p.shape[1],p.shape[2]])),_(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),_(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),Se("fused conv2d",n,i);let h=o==="NHWC"?f.shape[3]:f.shape[1];_(m.shape[2]===h,()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${m.shape[2]}.`),_(Rr(e,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${s}'`);let g=wc(f.shape,m.shape,e,s,n,i),x;a!=null&&(x=C(a,"bias","fused conv2d"),[x]=jt(x,p),o==="NHWC"?Mt(g.outShape,x.shape):(_(x.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${x.shape.length}.`),_(x.shape.length===0||x.shape[0]===g.outChannels||x.shape[0]===1,()=>`Error in fused conv2d: bias shape (${x.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let b;if(l!=null){let E=l.shape;if(_(E.length<=1||E.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${E.length}.`),E.length===1)_(E[0]===1||E[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${E}) is not compatible with the number of output channels (${g.outChannels}).`);else if(E.length===3)try{Mt(E,g.outShape)}catch(A){let D=`Error in fused conv2d: PReLU activation weights (${E}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(D)}b=C(l,"prelu weights","fused conv2d")}let w=(E,A)=>{_(o==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${o} but only NHWC is currently supported.`);let[D,F,P,V]=A,G=_c(E,P,u);_(co(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let W=pm(F.shape,G,D,e,n),q=$m(F,G,D.shape,e,n),H=[W,q];if(V!=null){let K=Ec(V,G);H.push(K)}return H},I={x:f,filter:m,bias:x,preluActivationWeights:b},N={strides:e,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i,activation:u,leakyreluAlpha:c};return a==null?fn((A,D,F)=>{let P=T.runKernel(Ji,I,N);return F([D,A,P]),d&&(P=R(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:w}})(f,m):fn((A,D,F,P)=>{let V=T.runKernel(Ji,I,N);return P([D,A,V,F]),d&&(V=R(V,[V.shape[1],V.shape[2],V.shape[3]])),{value:V,gradFunc:w}})(f,m,x)}var DA=k({fusedConv2d_:X5});function Y5(r,t,e,n,o,s=[1,1],i){let a=r;r.rank===3&&(a=R(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let u=t;u.rank===3&&(u=R(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let l={x:a,dy:u},c={strides:n,pad:o,dimRoundingMode:i,dilations:s,filterShape:e};return T.runKernel(Vp,l,c)}var yy=k({depthwiseConv2dNativeBackpropFilter_:Y5});function Z5(r,t,e,n,o,s=[1,1],i){let a=t,u=!1;t.rank===3&&(u=!0,a=R(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let l={dy:a,filter:e},c={strides:n,pad:o,dimRoundingMode:i,dilations:s,inputShape:r},p=T.runKernel(Gp,l,c);return u?R(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var by=k({depthwiseConv2dNativeBackpropInput_:Z5});function J5({x:r,filter:t,strides:e,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:a,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(Dc(T.state.gradientDepth,u)===!1){let N=ua(r,t,e,n,o,s,i);return a!=null&&(N=Y(N,a)),Ac(N,u,l,c)}let p=C(r,"x","depthwiseConv2d","float32"),m=C(t,"filter","depthwiseConv2d","float32"),f=p,d=!1;p.rank===3&&(d=!0,f=R(p,[1,p.shape[0],p.shape[1],p.shape[2]])),_(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),_(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),_(f.shape[3]===m.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`),s==null&&(s=[1,1]),_(Rr(e,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${e} and dilations '${s}'`),Se("fused depthwiseConv2d",n,i);let h=wc(f.shape,m.shape,e,s,n,i,!0),g;a!=null&&(g=C(a,"bias","fused conv2d"),[g]=jt(g,p),Mt(h.outShape,g.shape));let x;l!=null&&(x=C(l,"prelu weights","fused depthwiseConv2d"));let b=(N,E)=>{_(co(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[A,D,F,P]=E,V=_c(N,F,u),G=by(D.shape,V,A,e,n,s,i),W=yy(D,V,A.shape,e,n,s,i);if(P!=null){let q=Ec(g,V);return[G,W,q]}return[G,W]},w={x:f,filter:m,bias:g,preluActivationWeights:x},I={strides:e,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i,activation:u,leakyreluAlpha:c};return a==null?fn((E,A,D)=>{let F=T.runKernel(Qi,w,I);return D([A,E,F]),d&&(F=R(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}})(f,m):fn((E,A,D,F)=>{let P=T.runKernel(Qi,w,I);return F([A,E,P,D]),d&&(P=R(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:b}})(f,m,g)}var $A=k({fusedDepthwiseConv2d_:J5});function Q5({a:r,b:t,transposeA:e=!1,transposeB:n=!1,bias:o,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:a=.2}){if(Dc(T.state.gradientDepth,s)===!1){let V=Bt(r,t,e,n);return o!=null&&(V=Y(V,o)),Ac(V,s,i,a)}let u=C(r,"a","fused matMul"),l=C(t,"b","fused matMul");[u,l]=jt(u,l);let c=e?u.shape[u.rank-2]:u.shape[u.rank-1],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],m=e?u.shape[u.rank-1]:u.shape[u.rank-2],f=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=u.shape.slice(0,-2),h=l.shape.slice(0,-2),g=te(d),x=te(h);_(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${e} and transposeB=${n} must match.`);let w=Mt(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([m,f]),I=e?R(u,[g,c,m]):R(u,[g,m,c]),N=n?R(l,[x,f,p]):R(l,[x,p,f]),E;o!=null&&(E=C(o,"bias","fused matMul"),[E]=jt(E,u),Mt(w,E.shape));let A;i!=null&&(A=C(i,"prelu weights","fused matMul"));let D=(V,G)=>{let[W,q,H,K]=G,X=_c(R(V,H.shape),H,s),Z,et;if(!e&&!n?(Z=Bt(X,q,!1,!0),et=Bt(W,X,!0,!1)):!e&&n?(Z=Bt(X,q,!1,!1),et=Bt(X,W,!0,!1)):e&&!n?(Z=Bt(q,X,!1,!0),et=Bt(W,X,!1,!1)):(Z=Bt(q,X,!0,!0),et=Bt(X,W,!0,!0)),o!=null){let nt=Ec(K,X);return[Z,et,nt]}else return[Z,et]},F={a:I,b:N,bias:E,preluActivationWeights:A},P={transposeA:e,transposeB:n,activation:s,leakyreluAlpha:a};return o==null?fn((G,W,q)=>{let H=T.runKernel(Zi,F,P);return q([G,W,H]),{value:R(H,w),gradFunc:D}})(I,N):fn((G,W,q,H)=>{let K=T.runKernel(Zi,F,P);return H([G,W,K,q]),{value:R(K,w),gradFunc:D}})(I,N,E)}var RA=k({fusedMatMul_:Q5});function t8(r){return Ih(r,.54,.46)}var FA=k({hammingWindow_:t8});function e8(r){return Ih(r,.5,.5)}var wy=k({hannWindow_:e8});function r8(r,t,e,n=!1,o=0){let s=0,i=[];for(;s+t<=r.size;)i.push(Pt(r,s,t)),s+=e;if(n)for(;s<r.size;){let a=s+t-r.size,u=ie([Pt(r,s,t-a),No([a],o)]);i.push(u),s+=e}return i.length===0?fi([],[0,t]):R(ie(i),[i.length,t])}var Iy=k({frame_:r8});function n8(r,t,e,n,o=wy){n==null&&(n=pN(t));let s=Iy(r,t,e),i=$(s,o(t));return Pu(i,n)}var OA=k({stft_:n8});function o8(r,t,e,n,o="bilinear",s=0){let i=C(r,"image","cropAndResize"),a=C(t,"boxes","cropAndResize","float32"),u=C(e,"boxInd","cropAndResize","int32"),l=a.shape[0];_(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),_(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${a.shape}.`),_(u.rank===1&&u.shape[0]===l,()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${a.shape}.`),_(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),_(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),_(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);let c={image:i,boxes:a,boxInd:u},p={method:o,extrapolationValue:s,cropSize:n};return T.runKernel(Ba,c,p)}var PA=k({cropAndResize_:o8});function s8(r){let t=C(r,"image","flipLeftRight","float32");_(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let e={image:t};return T.runKernel(Ua,e,{})}var MA=k({flipLeftRight_:s8});function i8(r){let t=C(r,"image","grayscaleToRGB"),e=t.rank-1,n=t.shape[e];_(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),_(n===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${n}.`);let o=new Array(t.rank);return o.fill(1,0,e),o[e]=3,Or(t,o)}var LA=k({grayscaleToRGB_:i8});function a8(r,t,e=0,n=.5){let o=C(r,"image","rotateWithOffset","float32");_(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);let s={image:o},i={radians:t,fillValue:e,center:n};return T.runKernel(hl,s,i)}var zA=k({rotateWithOffset_:a8});function _o(r,t,e,n,o,s){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=r.shape[0];return e=Math.min(e,i),_(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),_(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),_(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),_(t.rank===1,()=>"scores must be a 1D tensor"),_(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),_(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:e,iouThreshold:n,scoreThreshold:o,softNmsSigma:s}}function l8(r,t,e,n=.5,o=Number.NEGATIVE_INFINITY){let s=C(r,"boxes","nonMaxSuppression","float32"),i=C(t,"scores","nonMaxSuppression","float32"),a=_o(s,i,e,n,o);e=a.maxOutputSize,n=a.iouThreshold,o=a.scoreThreshold;let u={maxOutputSize:e,iouThreshold:n,scoreThreshold:o};return T.runKernel(rl,{boxes:s,scores:i},u)}var BA=k({nonMaxSuppression_:l8});function VA(r,t,e){let n=u8(r,t,e),o=n<0?-(n+1):n;r.splice(o,0,t)}function u8(r,t,e){return p8(r,t,e||c8)}function c8(r,t){return r>t?1:r<t?-1:0}function p8(r,t,e){let n=0,o=r.length,s=0,i=!1;for(;n<o;){s=n+(o-n>>>1);let a=e(t,r[s]);a>0?n=s+1:(o=s,i=!a)}return i?n:-n-1}function Cy(r,t,e,n,o){return mN(r,t,e,n,o,0)}function vy(r,t,e,n,o,s){return mN(r,t,e,n,o,0,!1,s,!0)}function Sy(r,t,e,n,o,s){return mN(r,t,e,n,o,s,!0)}function mN(r,t,e,n,o,s,i=!1,a=!1,u=!1){let l=[];for(let g=0;g<t.length;g++)t[g]>o&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(GA);let c=s>0?-.5/s:0,p=[],m=[];for(;p.length<e&&l.length>0;){let g=l.pop(),{score:x,boxIndex:b,suppressBeginIndex:w}=g;if(x<o)break;let I=!1;for(let N=p.length-1;N>=w;--N){let E=m8(r,b,p[N]);if(E>=n){I=!0;break}if(g.score=g.score*f8(n,c,E),g.score<=o)break}g.suppressBeginIndex=p.length,I||(g.score===x?(p.push(b),m.push(g.score)):g.score>o&&VA(l,g,GA))}let f=p.length,d=e-f;a&&d>0&&(p.push(...new Array(d).fill(0)),m.push(...new Array(d).fill(0)));let h={selectedIndices:p};return i&&(h.selectedScores=m),u&&(h.validOutputs=f),h}function m8(r,t,e){let n=r.subarray(t*4,t*4+4),o=r.subarray(e*4,e*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),a=Math.max(n[0],n[2]),u=Math.max(n[1],n[3]),l=Math.min(o[0],o[2]),c=Math.min(o[1],o[3]),p=Math.max(o[0],o[2]),m=Math.max(o[1],o[3]),f=(a-s)*(u-i),d=(p-l)*(m-c);if(f<=0||d<=0)return 0;let h=Math.max(s,l),g=Math.max(i,c),x=Math.min(a,p),b=Math.min(u,m),w=Math.max(x-h,0)*Math.max(b-g,0);return w/(f+d-w)}function f8(r,t,e){let n=Math.exp(t*e*e);return e<=r?n:0}function GA(r,t){return r.score-t.score||r.score===t.score&&t.boxIndex-r.boxIndex}async function d8(r,t,e,n=.5,o=Number.NEGATIVE_INFINITY){let s=C(r,"boxes","nonMaxSuppressionAsync"),i=C(t,"scores","nonMaxSuppressionAsync"),a=_o(s,i,e,n,o);e=a.maxOutputSize,n=a.iouThreshold,o=a.scoreThreshold;let u=await Promise.all([s.data(),i.data()]),l=u[0],c=u[1],{selectedIndices:p}=Cy(l,c,e,n,o);return s!==r&&s.dispose(),i!==t&&i.dispose(),Ke(p,"int32")}var WA=d8;function h8(r,t,e,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let i=C(r,"boxes","nonMaxSuppression"),a=C(t,"scores","nonMaxSuppression"),u=_o(i,a,e,n,o,s);e=u.maxOutputSize,n=u.iouThreshold,o=u.scoreThreshold,s=u.softNmsSigma;let l={boxes:i,scores:a},c={maxOutputSize:e,iouThreshold:n,scoreThreshold:o,softNmsSigma:s},p=T.runKernel(ol,l,c);return{selectedIndices:p[0],selectedScores:p[1]}}var UA=k({nonMaxSuppressionWithScore_:h8});async function g8(r,t,e,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let i=C(r,"boxes","nonMaxSuppressionAsync"),a=C(t,"scores","nonMaxSuppressionAsync"),u=_o(i,a,e,n,o,s);e=u.maxOutputSize,n=u.iouThreshold,o=u.scoreThreshold,s=u.softNmsSigma;let l=await Promise.all([i.data(),a.data()]),c=l[0],p=l[1],{selectedIndices:m,selectedScores:f}=Sy(c,p,e,n,o,s);return i!==r&&i.dispose(),a!==t&&a.dispose(),{selectedIndices:Ke(m,"int32"),selectedScores:Ke(f)}}var HA=g8;function x8(r,t,e,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let i=C(r,"boxes","nonMaxSuppression"),a=C(t,"scores","nonMaxSuppression"),u=_o(i,a,e,n,o,null),l=u.maxOutputSize,c=u.iouThreshold,p=u.scoreThreshold,m={boxes:i,scores:a},f={maxOutputSize:l,iouThreshold:c,scoreThreshold:p,padToMaxOutputSize:s},d=T.runKernel(nl,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var qA=k({nonMaxSuppressionPadded_:x8});async function y8(r,t,e,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let i=C(r,"boxes","nonMaxSuppressionAsync"),a=C(t,"scores","nonMaxSuppressionAsync"),u=_o(i,a,e,n,o,null),l=u.maxOutputSize,c=u.iouThreshold,p=u.scoreThreshold,[m,f]=await Promise.all([i.data(),a.data()]),{selectedIndices:d,validOutputs:h}=vy(m,f,l,c,p,s);return i!==r&&i.dispose(),a!==t&&a.dispose(),{selectedIndices:Ke(d,"int32"),validOutputs:ft(h,"int32")}}var KA=y8;function b8(r,t,e=!1,n=!1){let o=C(r,"images","resizeBilinear");_(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),_(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),_(n===!1||e===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=o,i=!1;o.rank===3&&(i=!0,s=R(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=t,a={images:s},u={alignCorners:e,halfPixelCenters:n,size:t},l=T.runKernel(Us,a,u);return i?R(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var Ny=k({resizeBilinear_:b8});function w8(r,t,e=!1,n=!1){let o=C(r,"images","resizeNearestNeighbor");_(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),_(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),_(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),_(n===!1||e===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=o,i=!1;o.rank===3&&(i=!0,s=R(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=t,a={images:s},u={alignCorners:e,halfPixelCenters:n,size:t},l=T.runKernel(Ws,a,u);return i?R(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var ky=k({resizeNearestNeighbor_:w8});function I8(r,t="binary",e=!1,n=.5){let o=C(r,"image","threshold"),s=.2989,i=.587,a=.114,u=o.shape[0]*o.shape[1],l=$(Ke([n]),255),c,p,m,f;if(_(o.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${o.rank}.`),_(o.shape[2]===3||o.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`),_(o.dtype==="int32"||o.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`),_(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),o.shape[2]===3){[c,p,m]=gr(o,[1,1,1],-1);let g=$(c,s),x=$(p,i),b=$(m,a);f=Y(Y(g,x),b)}else f=r;if(t==="otsu"){let g=Tx(Q(bm(f),"int32"),sr([]),256);l=C8(g,u)}let d=e?Un(f,l):Fe(f,l);return Q($(d,255),"int32")}function C8(r,t){let e=Ke([-1]),n=Ke([0]),o=Ke([0]),s,i,a,u,l,c;for(let p=0;p<r.size-1;p++){s=Pt(r,0,p+1),i=Pt(r,p+1),l=ct(pt(s),t),c=ct(pt(i),t);let m=pt($(s,da(0,s.size)));a=ct(m,pt(s));let f=No(i.shape,s.size),d=Y(da(0,i.size),f),h=$(i,d);u=ct(pt(h),pt(i));let g=lt(a,u),x=lt(a,u),b=$(l,c);o=$($(b,g),x);let w=Fe(o,n);n=be(w,o,n),e=be(w,Ke([p]),e)}return e}var jA=k({threshold_:I8});function v8(r,t,e="nearest",n="constant",o=0,s){let i=C(r,"image","transform","float32"),a=C(t,"transforms","transform","float32");_(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),_(a.rank===2&&(a.shape[0]===i.shape[0]||a.shape[0]===1)&&a.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),_(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let u={image:i,transforms:a},l={interpolation:e,fillMode:n,fillValue:o,outputShape:s};return T.runKernel(dl,u,l)}var XA=k({transform_:v8});function S8(r,t,e){let n=C(r,"a","bandPart");_(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let o=n.shape,[s,i]=n.shape.slice(-2),a,u;typeof t=="number"?(_(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),_(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),a=C(t<0?s:t,"numLower","bandPart")):(_(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),a=be(Il(t,0),s,mo(t,s))),typeof e=="number"?(_(e%1===0,()=>`bandPart(): numUpper must be an integer, got ${e}.`),_(e<=i,()=>`bandPart(): numUpper (${e}) must not be greater than the number of columns (${i}).`),u=C(e<0?i:e,"numUpper","bandPart")):(_(e.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),u=be(Il(e,0),i,mo(e,i)));let l=R(da(0,s,1,"int32"),[-1,1]),c=da(0,i,1,"int32"),p=lt(l,c),m=Pr(Un(p,a),mn(p,Ut(u))),f=Te([s,i],n.dtype);return R(qe(xr(R(n,[-1,s,i])).map(d=>be(m,d,f))),o)}var YA=k({bandPart_:S8});function N8(r){let t;if(Array.isArray(r)){t=!1,_(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let o=r[0].shape[0];for(let s=1;s<r.length;++s)_(r[s].shape[0]===o,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${o})`)}else t=!0,r=gr(r,r.shape[0],0).map(o=>qn(o,[0]));_(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);let e=[],n=r;for(let o=0;o<r.length;++o)e.push(T.tidy(()=>{let s=n[o];if(o>0)for(let i=0;i<o;++i){let a=$(pt($(e[i],s)),e[i]);s=lt(s,a)}return ct(s,wl(s,"euclidean"))}));return t?qe(e,0):e}var ZA=k({gramSchmidt_:N8});function k8(r,t=!1){if(_(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return JA(r,t);{let e=r.shape.slice(0,r.shape.length-2).reduce((u,l)=>u*l),n=xr(R(r,[e,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],s=[];n.forEach(u=>{let[l,c]=JA(u,t);o.push(l),s.push(c)});let i=R(qe(o,0),r.shape),a=R(qe(s,0),r.shape);return[i,a]}}function JA(r,t=!1){return T.tidy(()=>{_(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);let e=r.shape[0],n=r.shape[1],o=Cc(e),s=cn(r),i=fi([[1]],[1,1]),a=cn(i),u=e>=n?n:e;for(let l=0;l<u;++l){let c=s,p=a,m=o;[a,s,o]=T.tidy(()=>{let f=Pt(s,[l,l],[e-l,1]),d=wl(f),h=Pt(s,[l,l],[1,1]),g=be(Fe(h,0),fi([[-1]]),fi([[1]])),x=lt(h,$(g,d)),b=ct(f,x);b.shape[0]===1?a=cn(i):a=ie([i,Pt(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let w=Ut(ct(Bt(g,x),d)),I=Pt(s,[l,0],[e-l,n]),N=$(w,a),E=Vt(a);if(l===0)s=lt(I,Bt(N,Bt(E,I)));else{let F=lt(I,Bt(N,Bt(E,I)));s=ie([Pt(s,[0,0],[l,n]),F],0)}let A=Vt(N),D=Pt(o,[0,l],[e,o.shape[1]-l]);if(l===0)o=lt(D,Bt(Bt(D,a),A));else{let F=lt(D,Bt(Bt(D,a),A));o=ie([Pt(o,[0,0],[e,l]),F],1)}return[a,s,o]}),Tt([c,p,m])}return!t&&e>n&&(o=Pt(o,[0,0],[e,n]),s=Pt(s,[0,0],[n,n])),[o,s]})}var QA=k({qr_:k8});var Ze;(function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Ze||(Ze={}));function T8(r,t,e=Ze.SUM_BY_NONZERO_WEIGHTS){let n=C(r,"losses","computeWeightedLoss"),o=null;t!=null&&(o=C(t,"weights","computeWeightedLoss"));let s=o==null?n:$(n,o);if(e===Ze.NONE)return s;if(e===Ze.SUM)return pt(s);if(e===Ze.MEAN){if(o==null)return ke(s);{let i=n.size/o.size,a=ct(pt(s),pt(o));return i>1?ct(a,ft(i)):a}}if(e===Ze.SUM_BY_NONZERO_WEIGHTS){if(o==null)return ct(pt(s),ft(n.size));{let i=$(o,dr(n.shape)),a=Q(pt(mi(i,ft(0))),"float32");return ct(pt(s),a)}}throw Error(`Unknown reduction: ${e}`)}var qr=k({computeWeightedLoss_:T8});function _8(r,t,e,n=Ze.SUM_BY_NONZERO_WEIGHTS){let o=C(r,"labels","absoluteDifference"),s=C(t,"predictions","absoluteDifference"),i=null;e!=null&&(i=C(e,"weights","absoluteDifference")),Re(o.shape,s.shape,"Error in absoluteDifference: ");let a=Ee(lt(o,s));return qr(a,i,n)}var t2=k({absoluteDifference_:_8});function E8(r,t,e,n,o=Ze.SUM_BY_NONZERO_WEIGHTS){let s=C(r,"labels","cosineDistance"),i=C(t,"predictions","cosineDistance"),a=null;n!=null&&(a=C(n,"weights","cosineDistance")),Re(s.shape,i.shape,"Error in cosineDistance: ");let u=ft(1),l=lt(u,pt($(s,i),e,!0));return qr(l,a,o)}var e2=k({cosineDistance_:E8});function A8(r,t,e,n=Ze.SUM_BY_NONZERO_WEIGHTS){let o=C(r,"labels","hingeLoss"),s=C(t,"predictions","hingeLoss"),i=null;e!=null&&(i=C(e,"weights","hingeLoss")),Re(o.shape,s.shape,"Error in hingeLoss: ");let a=ft(1);o=lt($(ft(2),o),a);let u=Mr(lt(a,$(o,s)));return qr(u,i,n)}var r2=k({hingeLoss_:A8});function D8(r,t,e,n=1,o=Ze.SUM_BY_NONZERO_WEIGHTS){let s=C(r,"labels","huberLoss"),i=C(t,"predictions","huberLoss"),a=null;e!=null&&(a=C(e,"weights","huberLoss")),Re(s.shape,i.shape,"Error in huberLoss: ");let u=ft(n),l=Ee(lt(i,s)),c=mo(l,u),p=lt(l,c),m=Y($(ft(.5),Wt(c)),$(u,p));return qr(m,a,o)}var n2=k({huberLoss_:D8});function $8(r,t,e,n=1e-7,o=Ze.SUM_BY_NONZERO_WEIGHTS){let s=C(r,"labels","logLoss"),i=C(t,"predictions","logLoss"),a=null;e!=null&&(a=C(e,"weights","logLoss")),Re(s.shape,i.shape,"Error in logLoss: ");let u=ft(1),l=ft(n),c=Ut($(s,kr(Y(i,l)))),p=$(lt(u,s),kr(Y(lt(u,i),l))),m=lt(c,p);return qr(m,a,o)}var o2=k({logLoss_:$8});function R8(r,t,e,n=Ze.SUM_BY_NONZERO_WEIGHTS){let o=C(r,"labels","meanSquaredError"),s=C(t,"predictions","meanSquaredError"),i=null;e!=null&&(i=C(e,"weights","meanSquaredError")),Re(o.shape,s.shape,"Error in meanSquaredError: ");let a=_m(o,s);return qr(a,i,n)}var s2=k({meanSquaredError_:R8});function F8(r,t){let e=C(r,"labels","sigmoidCrossEntropyWithLogits"),n=C(t,"logits","sigmoidCrossEntropyWithLogits");Re(e.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let o=Mr(n),s=$(n,e),i=Eu(ir(Ut(Ee(n))));return Y(lt(o,s),i)}function O8(r,t,e,n=0,o=Ze.SUM_BY_NONZERO_WEIGHTS){let s=C(r,"multiClassLabels","sigmoidCrossEntropy"),i=C(t,"logits","sigmoidCrossEntropy"),a=null;if(e!=null&&(a=C(e,"weights","sigmoidCrossEntropy")),Re(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let l=ft(n),c=ft(1),p=ft(.5);s=Y($(s,lt(c,l)),$(p,l))}let u=F8(s,i);return qr(u,a,o)}var i2=k({sigmoidCrossEntropy_:O8});function P8(r,t,e=-1){if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${e}`);return fn((o,s,i)=>{let u=gm(s,[e],!0),l=lt(Q(s,"float32"),u);i([o,l]);let c=Ut($(l,o));return{value:pt(c,[e]),gradFunc:(f,d)=>{let[h,g]=d,x=ko(f.shape,[e]);return[$(R(f,x),lt(Q(h,"float32"),ir(g))),$(R(f,x),lt(ir(g),Q(h,"float32")))]}}})(r,t)}function M8(r,t,e,n=0,o=Ze.SUM_BY_NONZERO_WEIGHTS){let s=C(r,"onehotLabels","softmaxCrossEntropy"),i=C(t,"logits","softmaxCrossEntropy"),a=null;if(e!=null&&(a=C(e,"weights","softmaxCrossEntropy")),Re(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let l=ft(n),c=ft(1),p=ft(s.shape[1]);s=Y($(s,lt(c,l)),ct(l,p))}let u=P8(s,i);return qr(u,a,o)}var a2=k({softmaxCrossEntropy_:M8});function L8(r,t,e,n){let o=C(r,"indices","sparseFillEmptyRows","int32"),s=C(t,"values","sparseFillEmptyRows"),i=C(e,"denseShape","sparseFillEmptyRows","int32"),a=C(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(o.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
| ${o.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(a.rank!==0)throw new Error(`Default value should be a scalar but received shape ${a.shape}`);let u={indices:o,values:s,denseShape:i,defaultValue:a},l=T.runKernel(cu,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}var l2=k({sparseFillEmptyRows_:L8});function z8(r,t,e){let n=C(r,"inputIndices","sparseReshape","int32"),o=C(t,"inputShape","sparseReshape","int32"),s=C(e,"newShape","sparseReshape","int32");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
| ${n.shape}`);if(o.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${o.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:o,newShape:s},a=T.runKernel(cl,i);return{outputIndices:a[0],outputShape:a[1]}}var u2=k({sparseReshape_:z8});function B8(r,t,e){let n=C(r,"data","sparseSegmentMean"),o=C(t,"indices","sparseSegmentMean","int32"),s=C(e,"segmentIds","sparseSegmentMean","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
| ${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
| ${s.shape}`);let i={data:n,indices:o,segmentIds:s};return T.runKernel(pu,i)}var c2=k({sparseSegmentMean_:B8});function V8(r,t,e){let n=C(r,"data","sparseSegmentSum"),o=C(t,"indices","sparseSegmentSum","int32"),s=C(e,"segmentIds","sparseSegmentSum","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
| ${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
| ${s.shape}`);let i={data:n,indices:o,segmentIds:s};return T.runKernel(mu,i)}var p2=k({sparseSegmentSum_:V8});function G8(r,t,e,n,o,s,i,a){let u=C(r,"data","stringNGrams","string");if(u.dtype!=="string")throw new Error("Data must be of datatype string");if(u.shape.length!==1)throw new Error(`Data must be a vector, saw: ${u.shape}`);let l=C(t,"dataSplits","stringNGrams");if(l.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let c={separator:e,nGramWidths:n,leftPad:o,rightPad:s,padWidth:i,preserveShortSequences:a},p={data:u,dataSplits:l},m=T.runKernel(du,p,c);return{nGrams:m[0],nGramsSplits:m[1]}}var m2=k({stringNGrams_:G8});function W8(r,t,e=!0){let n=C(r,"input","stringSplit","string"),o=C(t,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(o.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${o.shape}`);let s={skipEmpty:e},i={input:n,delimiter:o},a=T.runKernel(hu,i,s);return{indices:a[0],values:a[1],shape:a[2]}}var f2=k({stringSplit_:W8});function U8(r,t){let e=C(r,"input","stringToHashBucketFast","string"),n={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let o={input:e};return T.runKernel(gu,o,n)}var d2=k({stringToHashBucketFast_:U8});function H8(r,t,e,n=!0){let o=C(r,"input","staticRegexReplace","string"),s={pattern:t,rewrite:e,replaceGlobal:n};return T.runKernel(cc,{x:o},s)}var h2=k({staticRegexReplace_:H8});var q8={fft:Ou,ifft:vl,rfft:Pu,irfft:Tm},K8={hammingWindow:FA,hannWindow:wy,frame:Iy,stft:OA},hn={flipLeftRight:MA,grayscaleToRGB:LA,resizeNearestNeighbor:ky,resizeBilinear:Ny,rotateWithOffset:zA,cropAndResize:PA,nonMaxSuppression:BA,nonMaxSuppressionAsync:WA,nonMaxSuppressionWithScore:UA,nonMaxSuppressionWithScoreAsync:HA,nonMaxSuppressionPadded:qA,nonMaxSuppressionPaddedAsync:KA,threshold:jA,transform:XA},fN={bandPart:YA,gramSchmidt:ZA,qr:QA},j8={absoluteDifference:t2,computeWeightedLoss:qr,cosineDistance:e2,hingeLoss:r2,huberLoss:n2,logLoss:o2,meanSquaredError:s2,sigmoidCrossEntropy:i2,softmaxCrossEntropy:a2},X8={sparseFillEmptyRows:l2,sparseReshape:u2,sparseSegmentMean:c2,sparseSegmentSum:p2},Y8={stringNGrams:m2,stringSplit:f2,stringToHashBucketFast:d2,staticRegexReplace:h2};var J={};Kt(J,{Serializable:()=>Ch,SerializationMap:()=>ha,registerClass:()=>dN});var Ch=class{getClassName(){return this.constructor.className}static fromConfig(t,e){return new t(e)}},ha=class{constructor(){this.classNameMap={}}static getMap(){return ha.instance==null&&(ha.instance=new ha),ha.instance}static register(t){ha.getMap().classNameMap[t.className]=[t,t.fromConfig]}};function dN(r){_(r.className!=null,()=>"Class being registered does not have the static className property defined."),_(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),_(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),ha.register(r)}var Kr=class extends Ch{minimize(t,e=!1,n){let{value:o,grads:s}=this.computeGradients(t,n);if(n!=null){let i=n.map(a=>({name:a.name,tensor:s[a.name]}));this.applyGradients(i)}else this.applyGradients(s);return Tt(s),e?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(t,e){return Kx(t,e)}dispose(){this.iterations_!=null&&Tt(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:ft(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(t){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(t){return this.iterations_=(await t[0].tensor.data())[0],t.slice(1)}};Object.defineProperty(Kr,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var $c=class extends Kr{static get className(){return"Adadelta"}constructor(t,e,n=null){super(),this.learningRate=t,this.rho=e,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=T.backend.epsilon())}applyGradients(t){(Array.isArray(t)?t.map(n=>n.name):Object.keys(t)).forEach((n,o)=>{let s=T.registeredVariables[n],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accum_grad`,variable:B(()=>vt(s).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${n}/accum_var`,variable:B(()=>vt(s).variable(i))});let a=Array.isArray(t)?t[o].tensor:t[n];if(a==null)return;let u=this.accumulatedGrads[o].variable,l=this.accumulatedUpdates[o].variable;B(()=>{let c=Y($(u,this.rho),$(Wt(a),1-this.rho)),p=$(ct(Ne(Y(l,this.epsilon)),Ne(Y(u,this.epsilon))),a),m=Y($(l,this.rho),$(Wt(p),1-this.rho));u.assign(c),l.assign(m);let f=Y($(p,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Tt(this.accumulatedGrads.map(t=>t.variable)),Tt(this.accumulatedUpdates.map(t=>t.variable)))}async getWeights(){let t=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t);let e=t.length/2,n=!1;this.accumulatedGrads=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedUpdates=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.rho,e.epsilon)}};var Rc=class extends Kr{static get className(){return"Adagrad"}constructor(t,e=.1){super(),this.learningRate=t,this.initialAccumulatorValue=e,this.accumulatedGrads=[]}applyGradients(t){(Array.isArray(t)?t.map(n=>n.name):Object.keys(t)).forEach((n,o)=>{let s=T.registeredVariables[n];this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accumulator`,variable:B(()=>No(s.shape,this.initialAccumulatorValue).variable(!1))});let i=Array.isArray(t)?t[o].tensor:t[n];if(i==null)return;let a=this.accumulatedGrads[o].variable;B(()=>{let u=Y(a,Wt(i));a.assign(u);let l=Y($(ct(i,Ne(Y(u,T.backend.epsilon()))),-this.learningRate),s);s.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Tt(this.accumulatedGrads.map(t=>t.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(t){t=await this.extractIterations(t);let e=!1;this.accumulatedGrads=t.map(n=>({originalName:n.name,variable:n.tensor.variable(e)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(t,e){return new t(e.learningRate,e.initialAccumulatorValue)}};var Fc=class extends Kr{static get className(){return"Adam"}constructor(t,e,n,o=null){super(),this.learningRate=t,this.beta1=e,this.beta2=n,this.epsilon=o,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],B(()=>{this.accBeta1=ft(e).variable(),this.accBeta2=ft(n).variable()}),o==null&&(this.epsilon=T.backend.epsilon())}applyGradients(t){let e=Array.isArray(t)?t.map(n=>n.name):Object.keys(t);B(()=>{let n=lt(1,this.accBeta1),o=lt(1,this.accBeta2);e.forEach((s,i)=>{let a=T.registeredVariables[s],u=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${s}/m`,variable:B(()=>vt(a).variable(u))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${s}/v`,variable:B(()=>vt(a).variable(u))});let l=Array.isArray(t)?t[i].tensor:t[s];if(l==null)return;let c=this.accumulatedFirstMoment[i].variable,p=this.accumulatedSecondMoment[i].variable,m=Y($(c,this.beta1),$(l,1-this.beta1)),f=Y($(p,this.beta2),$(Wt(l),1-this.beta2)),d=ct(m,n),h=ct(f,o);c.assign(m),p.assign(f);let g=Y($(ct(d,Y(Ne(h),this.epsilon)),-this.learningRate),a);a.assign(g)}),this.accBeta1.assign($(this.accBeta1,this.beta1)),this.accBeta2.assign($(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Tt(this.accumulatedFirstMoment.map(t=>t.variable)),this.accumulatedSecondMoment!=null&&Tt(this.accumulatedSecondMoment.map(t=>t.variable))}async getWeights(){let t=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t),B(()=>{this.accBeta1.assign(pn(this.beta1,this.iterations_+1)),this.accBeta2.assign(pn(this.beta2,this.iterations_+1))});let e=t.length/2,n=!1;this.accumulatedFirstMoment=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedSecondMoment=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)}};var Oc=class extends Kr{static get className(){return"Adamax"}constructor(t,e,n,o=null,s=0){super(),this.learningRate=t,this.beta1=e,this.beta2=n,this.epsilon=o,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],B(()=>{this.iteration=ft(0).variable(),this.accBeta1=ft(e).variable()}),o==null&&(this.epsilon=T.backend.epsilon())}applyGradients(t){let e=Array.isArray(t)?t.map(n=>n.name):Object.keys(t);B(()=>{let n=lt(1,this.accBeta1),o=ct(-this.learningRate,Y($(this.iteration,this.decay),1));e.forEach((s,i)=>{let a=T.registeredVariables[s],u=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${s}/m`,variable:vt(a).variable(u)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${s}/v`,variable:vt(a).variable(u)});let l=Array.isArray(t)?t[i].tensor:t[s];if(l==null)return;let c=this.accumulatedFirstMoment[i].variable,p=this.accumulatedWeightedInfNorm[i].variable,m=Y($(c,this.beta1),$(l,1-this.beta1)),f=$(p,this.beta2),d=Ee(l),h=_n(f,d);c.assign(m),p.assign(h);let g=Y($(ct(o,n),ct(m,Y(h,this.epsilon))),a);a.assign(g)}),this.iteration.assign(Y(this.iteration,1)),this.accBeta1.assign($(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Tt(this.accumulatedFirstMoment.map(t=>t.variable)),this.accumulatedWeightedInfNorm!=null&&Tt(this.accumulatedWeightedInfNorm.map(t=>t.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(t){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)}};var Sl=class extends Kr{static get className(){return"SGD"}constructor(t){super(),this.learningRate=t,this.setLearningRate(t)}applyGradients(t){(Array.isArray(t)?t.map(n=>n.name):Object.keys(t)).forEach((n,o)=>{let s=Array.isArray(t)?t[o].tensor:t[n];if(s==null)return;let i=T.registeredVariables[n];B(()=>{let a=Y($(this.c,s),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(t){this.learningRate=t,this.c!=null&&this.c.dispose(),this.c=$e(ft(-t))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(t){if(t=await this.extractIterations(t),t.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(t,e){return new t(e.learningRate)}};var Pc=class extends Sl{static get className(){return"Momentum"}constructor(t,e,n=!1){super(t),this.learningRate=t,this.momentum=e,this.useNesterov=n,this.accumulations=[],this.m=ft(this.momentum)}applyGradients(t){(Array.isArray(t)?t.map(n=>n.name):Object.keys(t)).forEach((n,o)=>{let s=T.registeredVariables[n];this.accumulations[o]==null&&(this.accumulations[o]={originalName:`${n}/momentum`,variable:B(()=>vt(s).variable(!1))});let i=this.accumulations[o].variable,a=Array.isArray(t)?t[o].tensor:t[n];a!=null&&B(()=>{let u,l=Y($(this.m,i),a);this.useNesterov?u=Y($(this.c,Y(a,$(l,this.m))),s):u=Y($(this.c,l),s),i.assign(l),s.assign(u)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Tt(this.accumulations.map(t=>t.variable))}setMomentum(t){this.momentum=t}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(t){t=await this.extractIterations(t);let e=!1;this.accumulations=t.map(n=>({originalName:n.name,variable:n.tensor.variable(e)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)}};var Mc=class extends Kr{static get className(){return"RMSProp"}constructor(t,e=.9,n=0,o=null,s=!1){if(super(),this.learningRate=t,this.decay=e,this.momentum=n,this.epsilon=o,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,o==null&&(this.epsilon=T.backend.epsilon()),t==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(t){(Array.isArray(t)?t.map(n=>n.name):Object.keys(t)).forEach((n,o)=>{let s=T.registeredVariables[n],i=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${n}/rms`,variable:B(()=>vt(s).variable(i))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${n}/momentum`,variable:B(()=>vt(s).variable(i))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${n}/mg`,variable:B(()=>vt(s).variable(i))});let a=Array.isArray(t)?t[o].tensor:t[n];if(a==null)return;let u=this.accumulatedMeanSquares[o].variable,l=this.accumulatedMoments[o].variable;B(()=>{let c=Y($(u,this.decay),$(Wt(a),1-this.decay));if(this.centered){let p=this.accumulatedMeanGrads[o].variable,m=Y($(p,this.decay),$(a,1-this.decay)),f=ct($(a,this.learningRate),Ne(lt(c,Y(Wt(m),this.epsilon)))),d=Y($(l,this.momentum),f);u.assign(c),p.assign(m),l.assign(d);let h=lt(s,d);s.assign(h)}else{let p=Y($(u,this.decay),$(Wt(a),1-this.decay)),m=Y($(l,this.momentum),ct($(a,this.learningRate),Ne(Y(p,this.epsilon))));u.assign(p),l.assign(m);let f=lt(s,m);s.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Tt(this.accumulatedMeanSquares.map(t=>t.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Tt(this.accumulatedMeanGrads.map(t=>t.variable)),this.accumulatedMoments!=null&&Tt(this.accumulatedMoments.map(t=>t.variable))}async getWeights(){let t=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&t.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t);let e=this.centered?t.length/3:t.length/2,n=!1;this.accumulatedMeanSquares=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedMoments=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=t.slice(e*2,e*3).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)}};var Z8=[$c,Rc,Fc,Oc,Pc,Mc,Sl];function g2(){for(let r of Z8)dN(r)}var Lr={};Kt(Lr,{CompositeArrayBuffer:()=>vr,browserFiles:()=>y2,browserHTTPRequest:()=>I2,concatenateArrayBuffers:()=>rE,copyModel:()=>gE,decodeWeights:()=>lx,encodeWeights:()=>Q_,fromMemory:()=>C2,fromMemorySync:()=>wN,getLoadHandlers:()=>iE,getModelArtifactsForJSON:()=>nm,getModelArtifactsForJSONSync:()=>B0,getModelArtifactsInfoForJSON:()=>ea,getSaveHandlers:()=>sE,getWeightSpecs:()=>cx,http:()=>_y,isHTTPScheme:()=>Ty,listModels:()=>dE,loadWeights:()=>b2,moveModel:()=>xE,registerLoadRouter:()=>oE,registerSaveRouter:()=>nE,removeModel:()=>hE,weightsLoaderFactory:()=>yN,withSaveHandler:()=>v2,withSaveHandlerSync:()=>S2});var J8="model",Q8=".json",tY=".weights.bin";function x2(r){return new Promise(t=>setTimeout(t)).then(r)}var Nl=class{constructor(t){if(!L().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(Nl.URL_SCHEME)&&(t=t.slice(Nl.URL_SCHEME.length)),(t==null||t.length===0)&&(t=J8),this.modelJsonFileName=t+Q8,this.weightDataFileName=t+tY}async save(t){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let e=vr.join(t.weightData),n=window.URL.createObjectURL(new Blob([e],{type:"application/octet-stream"}));if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let o=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],s=ux(t,o),i=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=i,await x2(()=>a.dispatchEvent(new MouseEvent("click"))),t.weightData!=null){let u=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;u.download=this.weightDataFileName,u.href=n,await x2(()=>u.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ea(t)}}}};Nl.URL_SCHEME="downloads://";var hN=class{constructor(t){if(t==null||t.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${t}`);this.jsonFile=t[0],this.weightsFiles=t.slice(1)}async load(){return new Promise((t,e)=>{let n=new FileReader;n.onload=o=>{let s=JSON.parse(o.target.result),i=s.modelTopology;if(i==null){e(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(s.weightsManifest==null){e(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){t({modelTopology:i});return}let u=nm(s,l=>this.loadWeights(l));t(u)},n.onerror=o=>e(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(t){let e=[],n=[];for(let i of t)e.push(...i.weights),n.push(...i.paths);let o=this.checkManifestAndWeightFiles(t),s=n.map(i=>this.loadWeightsFile(i,o[i]));return Promise.all(s).then(i=>[e,i])}loadWeightsFile(t,e){return new Promise((n,o)=>{let s=new FileReader;s.onload=i=>{let a=i.target.result;n(a)},s.onerror=i=>o(`Failed to weights data from file of path '${t}'.`),s.readAsArrayBuffer(e)})}checkManifestAndWeightFiles(t){let e=[],n=this.weightsFiles.map(s=>z0(s.name)),o={};for(let s of t)s.paths.forEach(i=>{let a=z0(i);if(e.indexOf(a)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(e.push(a),n.indexOf(a)===-1)throw new Error(`Weight file with basename '${a}' is not provided.`);o[i]=this.weightsFiles[n.indexOf(a)]});if(e.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${e.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return o}},eY=r=>L().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Nl.URL_SCHEME)?rY(r.slice(Nl.URL_SCHEME.length)):null;ve.registerSaveRouter(eY);function rY(r="model"){return new Nl(r)}function y2(r){return new hN(r)}function gN(r,t,e,n){i(r),e=e==null?0:e,n=n==null?1:n,a(e,n);let o=0,s=u=>(u.then(l=>{let c=e+ ++o/r.length*(n-e);return t(c),l}),u);function i(u){_(u!=null&&Array.isArray(u)&&u.length>0,()=>"promises must be a none empty array")}function a(u,l){_(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${u}`),_(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${l}`),_(l>=u,()=>`startFraction must be no more than endFraction, but got startFraction ${u} and endFraction ${l}`)}return Promise.all(r.map(s))}async function xN(r,t){t==null&&(t={});let e=t.fetchFunc==null?L().platform.fetch:t.fetchFunc,n=r.map(p=>e(p,t.requestInit,{isBinary:!0})),o=0,s=.5,a=(t.onProgress==null?await Promise.all(n):await gN(n,t.onProgress,o,s)).map(p=>p.arrayBuffer()),u=.5,l=1;return t.onProgress==null?await Promise.all(a):await gN(a,t.onProgress,u,l)}async function b2(r,t="",e,n){return yN(i=>xN(i,{requestInit:n}))(r,t,e)}function yN(r){return async(t,e="",n)=>{let o=t.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],a=[];if(t.forEach((f,d)=>{let h=0;f.weights.forEach(g=>{let x="quantization"in g?g.quantization.dtype:g.dtype,b=mh[x]*te(g.shape),w=()=>{o[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:b})};n!=null?n.forEach((I,N)=>{I===g.name&&(w(),i[N]=!0)}):w(),a.push(g.name),h+=b})}),!i.every(f=>f)){let f=n.filter((d,h)=>!i[h]);throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}.
| Manifest JSON has weights with names: ${a.join(", ")}.`)}let u=o.reduce((f,d,h)=>(d&&f.push(h),f),[]),l=[];u.forEach(f=>{t[f].paths.forEach(d=>{let h=e+(e.endsWith("/")?"":"/")+d;l.push(h)})});let c=await r(l),p={},m=0;return u.forEach(f=>{let d=t[f].paths.length,h=new vr(c.slice(m,m+d));s[f].forEach(x=>{let b=h.slice(x.groupOffset,x.groupOffset+x.sizeBytes),w=lx(b,[x.manifestEntry]);for(let I in w)p[I]=w[I]}),m+=d}),p}}var nY="application/octet-stream",oY="application/json",vh=class{constructor(t,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,this.weightUrlConverter=e.weightUrlConverter,e.fetchFunc!=null?(_(typeof e.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=e.fetchFunc):this.fetch=L().platform.fetch,_(t!=null&&t.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(t)&&_(t.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${t.length}).`),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);e.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],o=ux(t,n);if(e.body.append("model.json",new Blob([JSON.stringify(o)],{type:oY}),"model.json"),t.weightData!=null){let i=vr.join(t.weightData);e.body.append("model.weights.bin",new Blob([i],{type:nY}),"model.weights.bin")}let s=await this.fetch(this.path,e);if(s.ok)return{modelArtifactsInfo:ea(t),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){let t=await this.fetch(this.path,this.requestInit);if(!t.ok)throw new Error(`Request to ${this.path} failed with status code ${t.status}. Please verify this URL points to the model JSON of the model to load.`);let e;try{e=await t.json()}catch(s){let i=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?i+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":i+=" Please make sure the server is serving valid JSON for this request.",new Error(i)}let n=e.modelTopology,o=e.weightsManifest;if(n==null&&o==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return nm(e,s=>this.loadWeights(s))}async loadWeights(t){let e=Array.isArray(this.path)?this.path[1]:this.path,[n,o]=sY(e),s=this.weightPathPrefix||n,i=cx(t),a=[],u=[];for(let c of t)for(let p of c.paths)this.weightUrlConverter!=null?u.push(this.weightUrlConverter(p)):a.push(s+p+o);this.weightUrlConverter&&a.push(...await Promise.all(u));let l=await xN(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,l]}};vh.URL_SCHEME_REGEX=/^https?:\/\//;function sY(r){let t=r.lastIndexOf("/"),e=r.lastIndexOf("?"),n=r.substring(0,t),o=e>t?r.substring(e):"";return[n+"/",o]}function Ty(r){return r.match(vh.URL_SCHEME_REGEX)!=null}var w2=(r,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let e=!0;if(Array.isArray(r)?e=r.every(n=>Ty(n)):e=Ty(r),e)return _y(r,t)}return null};ve.registerSaveRouter(w2);ve.registerLoadRouter(w2);function _y(r,t){return new vh(r,t)}function I2(r,t){return _y(r,t)}var Sh=class{constructor(t){this.modelArtifacts=t}load(){return this.modelArtifacts}},Ey=class{constructor(t){this.saveHandler=t}save(t){return this.saveHandler(t)}},bN=class{constructor(t){t.load&&(this.load=()=>Promise.resolve(t.load())),t.save&&(this.save=e=>Promise.resolve(t.save(e)))}};function C2(r,t,e,n){let o=arguments;return new bN(wN(...o))}function wN(r,t,e,n){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new Sh(r):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Sh({modelTopology:r})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Sh({modelTopology:r,weightSpecs:t,weightData:e,trainingConfig:n}))}function v2(r){return new Ey(r)}function S2(r){return new Ey(r)}var k2={};Kt(k2,{confusionMatrix:()=>N2});function iY(r,t,e){let n=C(r,"labels","confusionMatrix"),o=C(t,"predictions","confusionMatrix");_(e==null||e>0&&Number.isInteger(e),()=>`If provided, numClasses must be a positive integer, but got ${e}`),_(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),_(o.rank===1,()=>`Expected the rank of predictions to be 1, but got ${o.rank}`),_(n.shape[0]===o.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`),_(e>0&&Number.isInteger(e),()=>`numClasses is required to be a positive integer, but got ${e}`);let s=fa(Q(n,"int32"),e),i=fa(Q(o,"int32"),e),a=Vt(s),u=Bt(a,i);return Q(u,"int32")}var N2=k({confusionMatrix_:iY});var Ay={};Kt(Ay,{draw:()=>dY,fromPixels:()=>hY,fromPixelsAsync:()=>pY,toPixels:()=>fY});var Lc,T2=!1;function _2(r,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let e=!1,n=!1,o=!1,s=!1,i=!1,a=!1;if(r.data instanceof Uint8Array)e=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)s=!0;else if(r.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);if(ih(oh,T.backendName)!=null){let d={pixels:r},h={numChannels:t};return T.runKernel(oh,d,h)}let[l,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],p;if(i)p=r.getContext("2d").getImageData(0,0,l,c).data;else if(n||e)p=r.data;else if(s||o||a){if(Lc==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")Lc=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Lc=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Lc.canvas.width=l,Lc.canvas.height=c,Lc.drawImage(r,0,0,l,c),p=Lc.getImageData(0,0,l,c).data}let m;if(t===4)m=new Int32Array(p);else{let d=l*c;m=new Int32Array(d*t);for(let h=0;h<d;h++)for(let g=0;g<t;++g)m[h*t+g]=p[h*4+g]}return my(m,[c,l,t],"int32")}function aY(r){return r!=null&&r.data instanceof Uint8Array}function lY(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function uY(r){return r!=null&&r.width!==0&&r.height!==0}function cY(r){return lY()&&!(r instanceof ImageBitmap)&&uY(r)&&!aY(r)}async function pY(r,t=3){let e=null;if(L().getBool("WRAP_TO_IMAGEBITMAP")&&cY(r)){let n;try{n=await createImageBitmap(r,{premultiplyAlpha:"none"})}catch(o){n=null}n!=null&&n.width===r.width&&n.height===r.height?e=n:e=r}else e=r;return _2(e,t)}function E2(r){if(r.rank!==2&&r.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${r.rank}.`);let t=r.rank===2?1:r.shape[2];if(t>4||t===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if(r.dtype!=="float32"&&r.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${r.dtype}. Please use float32 or int32 tensors.`)}function mY(r){let t=(r==null?void 0:r.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}async function fY(r,t){let e=C(r,"img","toPixels");if(!(r instanceof Ot)){let l=e;e=Q(l,"int32"),l.dispose()}E2(e);let[n,o]=e.shape.slice(0,2),s=e.rank===2?1:e.shape[2],i=await e.data(),a=e.dtype==="float32"?255:1,u=new Uint8ClampedArray(o*n*4);for(let l=0;l<n*o;++l){let c=[0,0,0,255];for(let m=0;m<s;m++){let f=i[l*s+m];if(e.dtype==="float32"){if(f<0||f>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${f}.`)}else if(e.dtype==="int32"&&(f<0||f>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${f}.`);s===1?(c[0]=f*a,c[1]=f*a,c[2]=f*a):c[m]=f*a}let p=l*4;u[p+0]=Math.round(c[0]),u[p+1]=Math.round(c[1]),u[p+2]=Math.round(c[2]),u[p+3]=Math.round(c[3])}if(t!=null){T2||(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),T2=!0),t.width=o,t.height=n;let l=t.getContext("2d"),c=new ImageData(u,o,n);l.putImageData(c,0,0)}return e!==r&&e.dispose(),u}function dY(r,t,e){let n=C(r,"img","draw");if(!(r instanceof Ot)){let i=n;n=Q(i,"int32"),i.dispose()}E2(n),mY(e==null?void 0:e.imageOptions);let o={image:n},s={canvas:t,options:e};T.runKernel(Zg,o,s)}var hY=k({fromPixels_:_2});var Dy={};Kt(Dy,{prepareAndValidate:()=>A2});function A2(r,t){let e=r.shape.length,n=t.shape.length;if(e<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e}.`);if(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[n-1]>e)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[n-1]} vs. ${e}`);if(te(r.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r.shape}.`);let o=t.shape,s=o[o.length-1],i=1;for(let p=0;p<o.length-1;++p)i*=o[p];let a=r.shape,u=o.slice();u.pop();let l=1;for(let p=s;p<e;++p)l*=a[p],u.push(a[p]);let c=[...Di(r.shape).map(p=>p/l),1].slice(0,s);return[u,i,l,c]}var ze={};Kt(ze,{assertParamsValid:()=>xY,computeFlatOffset:()=>CY,computeOutShape:()=>bY,getNormalizedAxes:()=>wY,isSliceContinous:()=>IY,maskToAxes:()=>yY,parseSliceParams:()=>CN,sliceInfo:()=>vY,startForAxis:()=>L2,startIndicesWithElidedDims:()=>O2,stopForAxis:()=>z2,stopIndicesWithElidedDims:()=>P2,stridesForAxis:()=>M2,stridesWithElidedDims:()=>$2});var IN=-2,gY=-1;function xY(r,t,e){let n=r.shape.length;_(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),_(n===e.length,()=>`Error in slice${n}D: Length of size ${e} must match the rank of the array (${n}).`);for(let o=0;o<n;++o)_(t[o]+e[o]<=r.shape[o],()=>`Error in slice${n}D: begin[${o}] + size[${o}] (${t[o]+e[o]}) would overflow input.shape[${o}] (${r.shape[o]})`)}function yY(r){let t=[],e=0;for(;r>0;)r&1&&t.push(e),r/=2,e++;return t}function bY(r,t,e){let n=[];for(let o=0;o<r.length;o++)n[o]=Math.ceil((t[o]-r[o])/e[o]);return n}function $2(r,t,e,n){let o=[...r];for(let s=o.length;s<n.length;s++)o.push(1);for(let s=0;s<e;s++)s===0?o[t]=1:(o.splice(t,0,1),o.pop());return o}function R2(r,t,e){return e<=r?e:e-(t-1)}function F2(r,t){let e=[];for(let n=0;n<r;n++)e.push(t+n);return e}function wY(r,t,e,n,o,s,i,a,u){let l=r.length,c=new Array(l),p=new Array(l),m=new Array(l);if(t.length&&e>0){let f=t[0],d=e+1;c=O2(i,f,d,n,r),p=P2(a,f,d,o,r),m=$2(s,f,d,r)}else for(let f=0;f<l;f++)c[f]=L2(i,n,s,r,f,u),p[f]=z2(a,o,s,r,f,u),m[f]=M2(s,f,u);return{begin:c,end:p,strides:m}}function O2(r,t,e,n,o){let s=[...o],i=F2(e,t);for(let a=0;a<s.length;a++)if(i.indexOf(a)>-1)s[a]=0;else{let u=R2(t,e,a),l=n[u];r&1<<u&&(l=0),s[a]=l}return s}function P2(r,t,e,n,o){let s=[...o],i=F2(e,t);for(let a=0;a<s.length;a++)if(i.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{let u=R2(t,e,a),l=n[u];r&1<<u&&(l=Number.MAX_SAFE_INTEGER),s[a]=l}for(let a=0;a<s.length;a++){let u=o[a];s[a]<0&&(s[a]+=u),s[a]=Op(0,s[a],o[a])}return s}function M2(r,t,e){let n=r[t];return(e&1<<t||n==null)&&(n=1),n}function L2(r,t,e,n,o,s){let i=t[o],a=e[o]||1;(r&1<<o||s&1<<o||i==null)&&(a>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let u=n[o];return i<0&&(i+=u),i=Op(0,i,u-1),i}function z2(r,t,e,n,o,s){let i=t[o],a=e[o]||1;(r&1<<o||s&1<<o||i==null)&&(a>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let u=n[o];return i<0&&(i+=u),a>0?i=Op(0,i,u):i=Op(-1,i,u-1),i}function IY(r,t,e){let n=e.length;for(let o=0;o<e.length;o++)if(e[o]>1){n=o;break}for(let o=n+1;o<e.length;o++)if(t[o]>0||e[o]!==r[o])return!1;return!0}function CY(r,t){let e=r.length>0?r[r.length-1]:1;for(let n=0;n<r.length-1;n++)e+=r[n]*t[n];return e}function CN(r,t,e){let n,o=r.shape.length;typeof t=="number"?n=[t,...new Array(o-1).fill(0)]:t.length<o?n=t.concat(new Array(o-t.length).fill(0)):n=t.slice(),n.forEach(i=>{_(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return e==null?s=new Array(o).fill(-1):typeof e=="number"?s=[e,...new Array(o-1).fill(-1)]:e.length<o?s=e.concat(new Array(o-e.length).fill(-1)):s=e,s=s.map((i,a)=>i>=0?i:(_(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`),r.shape[a]-n[a])),[n,s]}function vY(r,t,e,n,o,s,i,a,u){let l;if(n==null?(l=new Array(t.length),l.fill(1)):l=n,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1,p={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:e.slice(),strides:l.slice(),beginMask:o,endMask:s,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:u};for(let w=0;w<p.dims;w++)c&&1<<w&a&&p.numAddAxisAfterEllipsis++,1<<w&i&&(c=!0);c||(p.ellipsisMask|=1<<p.dims,p.dims++);let m={dims:r.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};SY(p,m);let f=!0,d=!0,h=!0,g=[],x=[];for(let w=0;w<r.length;++w){if(m.strides[w]===0)throw Error(`strides[${w}] must be non-zero`);let I=!!(m.shrinkAxisMask&1<<w),N=r[w];if(N===-1){g.push(I?1:-1);continue}let E=[m.beginMask&1<<w,m.endMask&1<<w],A=[m.strides[w]>0?0:-1,m.strides[w]>0?N:N-1];if(I&&m.strides[w]<=0)throw Error("only stride 1 allowed on non-range indexing.");h=h&&m.strides[w]===1;let D=!!(m.beginMask&1<<w&&m.endMask&1<<w);if(m.beginValid&&m.endValid){if(I){let G=m.begin[w]<0?N+m.begin[w]:m.begin[w];if(m.begin[w]=G,m.end[w]=m.begin[w]+1,G<0||G>=N)throw Error(`slice index ${m.begin[w]} of dimension ${w} out of bounds.`)}else m.begin[w]=D2(m.begin[w],0,m.strides[w],N,E,A),m.end[w]=D2(m.end[w],1,m.strides[w],N,E,A);let V=m.strides[w]===1&&m.begin[w]===0&&m.end[w]===N;f=f&&V,d=d&&(w===0&&m.strides[w]===1||V)}else f=f&&m.strides[w]===1&&D,d=d&&(w===0&&m.strides[w]===1||D);let F,P=!1;if(m.beginValid&&m.endValid?(F=m.end[w]-m.begin[w],P=!0):I?(F=1,P=!0):D&&N>=0&&(m.strides[w]<0?F=-N:F=N,P=!0),P){let V;F===0||F<0!=m.strides[w]<0?V=0:V=Math.trunc(F/m.strides[w])+(F%m.strides[w]!==0?1:0),g.push(V)}else g.push(-1)}for(let w=0;w<m.finalShapeGatherIndices.length;++w){let I=m.finalShapeGatherIndices[w];I>=0?x.push(g[I]):I===IN&&x.push(1)}return{finalShapeSparse:x.filter((w,I)=>m.finalShapeGatherIndices[I]!==IN),finalShape:x,isIdentity:f,sliceDim0:d,isSimpleSlice:h,begin:m.begin,end:m.end,strides:m.strides}}function SY(r,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let e=0;t.beginValid=r.begin!=null,t.endValid=r.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let n=0;n<r.dims;n++)if(1<<n&r.ellipsisMask){let o=Math.min(t.dims-(r.dims-n)+1+r.numAddAxisAfterEllipsis,t.dims);for(;e<o;e++)t.begin[e]=0,t.end[e]=0,t.strides[e]=1,t.beginMask|=1<<e,t.endMask|=1<<e,t.finalShapeGatherIndices.push(e),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[e]=n}else if(1<<n&r.newAxisMask)t.finalShapeGatherIndices.push(IN),t.finalShapeGatherIndicesSparse.push(-1);else{if(e===t.begin.length)throw Error(`Index out of range using input dim ${e}; input has only ${t.dims} dims, ${t.begin.length}.`);r.begin!=null&&(t.begin[e]=r.begin[n]),r.end!=null&&(t.end[e]=r.end[n]),t.strides[e]=r.strides[n],r.beginMask&1<<n&&(t.beginMask|=1<<e),r.endMask&1<<n&&(t.endMask|=1<<e),r.shrinkAxisMask&1<<n?(t.finalShapeGatherIndices.push(gY),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<e):(t.finalShapeGatherIndices.push(e),t.finalShapeGatherIndicesSparse.push(n)),t.inputShapeGatherIndicesSparse[e]=n,e++}}function D2(r,t,e,n,o,s){if(o[t])return e>0?s[t]:s[t+1&1];{let i=r<0?n+r:r;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var B2="4.7.0";var Nh=class{static sgd(t){return new Sl(t)}static momentum(t,e,n=!1){return new Pc(t,e,n)}static rmsprop(t,e=.9,n=0,o=null,s=!1){return new Mc(t,e,n,o,s)}static adam(t=.001,e=.9,n=.999,o=null){return new Fc(t,e,n,o)}static adadelta(t=.001,e=.95,n=null){return new $c(t,e,n)}static adamax(t=.002,e=.9,n=.999,o=null,s=0){return new Oc(t,e,n,o,s)}static adagrad(t,e=.1){return new Rc(t,e)}};var zc=Nh;var NY=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function kh(){return new Promise(r=>NY(()=>r()))}var S={};Kt(S,{ERF_A1:()=>BY,ERF_A2:()=>VY,ERF_A3:()=>GY,ERF_A4:()=>WY,ERF_A5:()=>UY,ERF_P:()=>zY,PARALLELIZE_THRESHOLD:()=>$y,RowPartitionType:()=>ga,SELU_SCALE:()=>SN,SELU_SCALEALPHA:()=>vN,applyActivation:()=>Ac,assertAndGetBroadcastShape:()=>Mt,assertAxesAreInnerMostDims:()=>l6,assertParamsConsistent:()=>kY,assignToTypedArray:()=>YY,axesAreInnerMostDims:()=>Z0,calculateShapes:()=>kA,checkEinsumDimSizes:()=>r7,checkPadOnDimRoundingMode:()=>Se,combineLocations:()=>$E,combineRaggedTensorToTensorShapes:()=>_Y,complexWithEvenIndex:()=>KY,complexWithOddIndex:()=>jY,computeConv2DInfo:()=>wc,computeConv3DInfo:()=>CE,computeDefaultPad:()=>Y0,computeDilation2DInfo:()=>aj,computeOptimalWindowSize:()=>$Y,computeOutAndReduceShapes:()=>J0,computeOutShape:()=>TY,computePool2DInfo:()=>X0,computePool3DInfo:()=>lj,convertConv2DDataFormat:()=>vE,decodeEinsumEquation:()=>t7,eitherStridesOrDilationsAreOne:()=>Rr,expandShapeToKeepDim:()=>ko,exponent:()=>JY,exponents:()=>ZY,fromStringArrayToUint8:()=>v7,fromUint8ToStringArray:()=>C7,getAxesPermutation:()=>Q0,getBroadcastDims:()=>EE,getComplexWithIndex:()=>XY,getEinsumComputePath:()=>n7,getEinsumPermutation:()=>e7,getFusedBiasGradient:()=>Ec,getFusedDyActivation:()=>_c,getImageCenter:()=>RY,getInnerMostAxes:()=>u6,getPermuted:()=>OY,getRaggedRank:()=>AY,getReductionAxes:()=>ye,getReshaped:()=>FY,getReshapedPermuted:()=>PY,getRowPartitionTypesHelper:()=>EY,getSliceBeginCoords:()=>MY,getSliceSize:()=>LY,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>a7,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>l7,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>u7,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>m7,getSparseReshapeInputOutputMismatchErrorMessage:()=>d7,getSparseReshapeInputOutputMultipleErrorMessage:()=>f7,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>c7,getSparseReshapeNegativeOutputDimErrorMessage:()=>p7,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>y7,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>h7,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>g7,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>x7,getUndoAxesPermutation:()=>xh,isIdentityPermutation:()=>o7,log:()=>rK,mergeRealAndImagArrays:()=>HY,prepareAndValidate:()=>A2,prepareSplitSize:()=>i7,segment_util:()=>kN,shouldFuse:()=>Dc,slice_util:()=>ze,splitRealAndImagArrays:()=>qY,stridesOrDilationsArePositive:()=>sa,tupleValuesAreOne:()=>co,upcastType:()=>ur,validateDefaultValueShape:()=>DY,validateInput:()=>Em,validateUpdateShape:()=>uN,warn:()=>ta});function kY(r,t){let e=r[0].length;r.forEach((o,s)=>{_(o.length===e,()=>`Error in concat${e}D: rank of tensors[${s}] must be the same as the rank of the rest (${e})`)}),_(t>=0&&t<e,()=>`Error in concat${e}D: axis must be between 0 and ${e-1}.`);let n=r[0];r.forEach((o,s)=>{for(let i=0;i<e;i++)_(i===t||o[i]===n[i],()=>`Error in concat${e}D: Shape of tensors[${s}] (${o}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function TY(r,t){let e=r[0].slice();for(let n=1;n<r.length;n++)e[t]+=r[n][t];return e}var ga;(function(r){r[r.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",r[r.VALUE_ROWIDS=1]="VALUE_ROWIDS",r[r.ROW_LENGTHS=2]="ROW_LENGTHS",r[r.ROW_SPLITS=3]="ROW_SPLITS",r[r.ROW_LIMITS=4]="ROW_LIMITS",r[r.ROW_STARTS=5]="ROW_STARTS"})(ga||(ga={}));function _Y(r,t,e){let n=new Array;if(e==null&&t==null)return n;if(t==null)for(;n.length<r+e.length;)n.push(-1);else n=t.slice();if(e==null)return n;if(r+e.length!==n.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${r+e.length}, but shape.rank = ${n.length}`);for(let o=1;o<e.length;++o){let s=e[o],i=n[n.length-e.length+o],a=n[i];if(s>=0)if(a>=0){if(a!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${o+r}] = ${s} but shape[${o+r}] = ${a}`)}else n[i]=s}return n}function EY(r){let t={FIRST_DIM_SIZE:ga.FIRST_DIM_SIZE,VALUE_ROWIDS:ga.VALUE_ROWIDS,ROW_LENGTHS:ga.ROW_LENGTHS,ROW_SPLITS:ga.ROW_SPLITS,ROW_LIMITS:ga.ROW_LIMITS,ROW_STARTS:ga.ROW_STARTS},e=[];for(let n of r)if(n in t)e.push(t[n]);else break;return e}function AY(r){return r.length===0?0:r[0]===ga.FIRST_DIM_SIZE?r.length-1:r.length}function DY(r,t){if(r==null||t==null)return;let e=r.length,n=t.length;if(e>=n)throw new Error(`defaultValue.shape=${r} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${e} must be less than ragged tensor input flatValues.rank = ${n})`);for(let o=0;o<Math.min(e,n-1);++o){let s=r[o],i=t[o+1];if(s>=0&&i>=0&&s!==1&&s!==i)throw new Error(`defaultValue.shape=${r}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${o-r.length}] = ${s} but ragged tensor input.flatValues.shape[${o-r.length}] = ${i}`)}}var $y=30;function $Y(r){return r<=$y?r:Mp(r,Math.floor(Math.sqrt(r)))}function RY(r,t,e){let n=e*(typeof r=="number"?r:r[0]),o=t*(typeof r=="number"?r:r[1]);return[n,o]}function FY(r,t,e,n=!0){let o=[];if(n)o=o.concat(t.slice(0)),o.push(r[0]/e),o=o.concat(r.slice(1));else{o=o.concat(r[0]);let s=t.length;for(let i=0;i<s;++i)o=o.concat([r[i+1]/t[i],t[i]]);o=o.concat(r.slice(s+1))}return o}function OY(r,t,e=!0){let n=[];if(e){n.push(t);for(let o=t+1;o<r;++o)o<=2*t?(n.push(o),n.push(o-(t+1))):n.push(o)}else{let o=[],s=[];for(let i=1;i<r;++i)i>=t*2+1||i%2===1?s.push(i):o.push(i);n.push(...o),n.push(0),n.push(...s)}return n}function PY(r,t,e,n=!0){let o=[];n?o.push(r[0]/e):o.push(r[0]*e);for(let s=1;s<r.length;++s)s<=t.length?n?o.push(t[s-1]*r[s]):o.push(r[s]/t[s-1]):o.push(r[s]);return o}function MY(r,t){let e=[0];for(let n=0;n<t;++n)e.push(r[n][0]);return e}function LY(r,t,e){let n=r.slice(0,1);for(let o=0;o<e;++o)n.push(r[o+1]-t[o][0]-t[o][1]);return n}var vN=1.7580993408473768,SN=1.0507009873554805;var zY=.3275911,BY=.254829592,VY=-.284496736,GY=1.421413741,WY=-1.453152027,UY=1.061405429;function HY(r,t){if(r.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${r.length}, imag: ${t.length}.`);let e=new Float32Array(r.length*2);for(let n=0;n<e.length;n+=2)e[n]=r[n/2],e[n+1]=t[n/2];return e}function qY(r){let t=new Float32Array(r.length/2),e=new Float32Array(r.length/2);for(let n=0;n<r.length;n+=2)t[n/2]=r[n],e[n/2]=r[n+1];return{real:t,imag:e}}function KY(r){let t=Math.ceil(r.length/4),e=new Float32Array(t),n=new Float32Array(t);for(let o=0;o<r.length;o+=4)e[Math.floor(o/4)]=r[o],n[Math.floor(o/4)]=r[o+1];return{real:e,imag:n}}function jY(r){let t=Math.floor(r.length/4),e=new Float32Array(t),n=new Float32Array(t);for(let o=2;o<r.length;o+=4)e[Math.floor(o/4)]=r[o],n[Math.floor(o/4)]=r[o+1];return{real:e,imag:n}}function XY(r,t){let e=r[t*2],n=r[t*2+1];return{real:e,imag:n}}function YY(r,t,e,n){r[n*2]=t,r[n*2+1]=e}function ZY(r,t){let e=new Float32Array(r/2),n=new Float32Array(r/2);for(let o=0;o<Math.ceil(r/2);o++){let s=(t?2:-2)*Math.PI*(o/r);e[o]=Math.cos(s),n[o]=Math.sin(s)}return{real:e,imag:n}}function JY(r,t,e){let n=(e?2:-2)*Math.PI*(r/t),o=Math.cos(n),s=Math.sin(n);return{real:o,imag:s}}var NN="->",QY=/->/g,V2=",",G2="...";function t7(r,t){r=r.replace(/\s/g,"");let e=(r.length-r.replace(QY,"").length)/NN.length;if(e<1)throw new Error("Equations without an arrow are not supported.");if(e>1)throw new Error(`Equation must contain exactly one arrow ("${NN}").`);let[n,o]=r.split(NN);_(n.indexOf(G2)===-1,()=>`The ellipsis notation ("${G2}") is not supported yet.`);let s=n.split(V2),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let a=[];for(let m=0;m<o.length;++m){let f=o[m];if(!s.some(d=>d.indexOf(f)!==-1))throw new Error(`Output subscripts contain the label ${f} not present in the input subscripts.`);a.indexOf(f)===-1&&a.push(f)}for(let m=0;m<n.length;++m){let f=n[m];a.indexOf(f)===-1&&f!==V2&&a.push(f)}let u=new Array(s.length);for(let m=0;m<i;++m){if(new Set(s[m].split("")).size!==s[m].length)throw new Error(`Found duplicate axes in input component ${s[m]}. Support for duplicate axes in input is not implemented yet.`);u[m]=[];for(let f=0;f<s[m].length;++f)u[m].push(a.indexOf(s[m][f]))}let l=a.length,c=o.length,p=[];for(let m=c;m<l;++m)p.push(m);return{allDims:a,summedDims:p,idDims:u}}function e7(r,t){let e=new Array(r);e.fill(-1);for(let o=0;o<t.length;++o)e[t[o]]=o;let n=[];for(let o=0;o<r;++o)e[o]===-1&&n.push(o);return e=e.filter(o=>o!==-1),{permutationIndices:e,expandDims:n}}function r7(r,t,e){let n=new Array(r);for(let o=0;o<e.length;++o){let s=e[o].shape;for(let i=0;i<t[o].length;++i)n[t[o][i]]===void 0?n[t[o][i]]=s[i]:_(n[t[o][i]]===s[i],()=>`Expected dimension ${n[t[o][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function n7(r,t){let e=r,n=[],o=0;r.length===0&&e.push(-1),o=r.length+1;for(let i=0;i<o;++i)n.push([]);let s=[];for(let i=0;i<e.length;++i){let a=e[i],u=s7(t,a);for(let l of u)s.indexOf(l)===-1&&(n[i].push(l),s.push(l))}return{path:e,steps:n}}function o7(r){return r.every((t,e)=>t===e)}function s7(r,t){let e=[];for(let n=0;n<r.length;++n)(r[n].length===0||r[n].indexOf(t)!==-1||t===-1)&&e.push(n);return e}function i7(r,t,e=0){let n=[];if(typeof t=="number")_(r.shape[e]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(r.shape[e]/t);else{let o=t.reduce((i,a)=>(a===-1&&(i+=1),i),0);_(o<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((a,u)=>u>0?a+u:a);t[s]=r.shape[e]-i}_(r.shape[e]===t.reduce((i,a)=>i+a),()=>"The sum of sizes must match the size of the axis dimension."),n=t}return n}function a7(r){return`Received SparseTensor with denseShape[0] = 0 but
| indices.shape[0] = ${r}`}function l7(r,t){return`indices(${r}, 0) is invalid: ${t} < 0`}function u7(r,t,e){return`indices(${r}, 0) is invalid: ${t} >= ${e}`}function c7(r,t){return`only one output dimension may be -1, not both ${r} and ${t}`}function p7(r,t){return`size ${r} must be non-negative, not ${t}`}function m7(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function f7(r,t){let e=te(r),n=te(t);return`Input to reshape is a SparseTensor with ${e}
| dense values, but the requested shape requires a multiple of ${n}. inputShape=${r} outputShape= ${t}`}function d7(r,t){let e=te(r),n=te(t);return`Input to reshape is a tensor with ${e} dense values, but the requested shape has ${n}. inputShape=${r} outputShape=${t}`}function h7(){return"segment ids must be >= 0"}function g7(){return"segment ids are not increasing"}function x7(r,t){return`Segment id ${r} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function y7(r,t,e){return`Bad: indices[${r}] == ${t} out of range [0, ${e})`}var kN={};Kt(kN,{collectGatherOpShapeInfo:()=>I7,computeOutShape:()=>w7,segOpComputeOptimalWindowSize:()=>b7});function b7(r,t){let e=!1,n;for(r<=$y?(n=r,e=!0):n=Mp(r,Math.floor(Math.sqrt(r)));!e;)n>t||n===r?e=!0:n=Mp(r,n+1);return n}function w7(r,t,e){let n=[],o=r.length;for(let s=0;s<o;s++)s!==t?n.push(r[s]):n.push(e);return n}function I7(r,t,e,n){let o=t.shape.length,s=r.shape.length;if(n!==0&&(n<-o||n>o))throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${n}`);if(n<0&&(n+=o),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
| ${s}).`);if(e<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${e}).`);for(let p=0;p<n;++p)if(r.shape[p]!==t.shape[p])throw new Error(`x.shape[${p}]: ${r.shape[p]} should be equal to indices.shape[${p}]: ${t.shape[p]}.`);let i=r.shape[e],a=[],u=1,l=1,c=1;for(let p=0;p<n;++p)a.push(r.shape[p]),u*=r.shape[p];for(let p=n;p<e;p++)a.push(r.shape[p]),l*=r.shape[p];for(let p=n;p<o;p++)a.push(t.shape[p]);for(let p=e+1;p<s;p++)a.push(r.shape[p]),c*=r.shape[p];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:i,outputShape:a}}function C7(r){try{return r.map(t=>em(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function v7(r){return r.map(t=>wu(t))}var jr={};Kt(jr,{nonMaxSuppressionV3Impl:()=>Cy,nonMaxSuppressionV4Impl:()=>vy,nonMaxSuppressionV5Impl:()=>Sy,whereImpl:()=>gy});g2();var Ry={kernelName:$i,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,To(Q(e,"float32"),-1))}}};var W2={kernelName:qo,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=Wt(Q(e,"float32")),o=Ne(lt(ft(1),n));return Ut(ct(r,o))}}}};var U2={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=Ne(lt(Wt(Q(e,"float32")),1));return ct(r,n)}}}};var H2={kernelName:ao,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=r,u=ye(e.shape,o);return u.length>0&&(a=pt(a,u)),R(a,e.shape)},b:()=>{let a=r,u=ye(n.shape,o);return u.length>0&&(a=pt(a,u)),R(a,n.shape)}}}};var q2={kernelName:jo,saveAllInputs:!0,gradFunc:(r,t)=>{let e={};return t.forEach((n,o)=>{e[o]=()=>r.clone()}),e}};var K2={kernelName:Ri,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>vt(e)}}};var j2={kernelName:Fi,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>vt(e)}}};var X2={kernelName:Xo,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,Ne(lt(ft(1),Wt(Q(e,"float32")))))}}};var Y2={kernelName:Yo,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=Ne(Y(ft(1),Wt(Q(e,"float32"))));return ct(r,n)}}}};var Z2={kernelName:Qo,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=Y(Wt(e),Wt(n)),u=$(r,ct(n,a)),l=ye(e.shape,o);return l.length>0&&(u=pt(u,l)),R(u,e.shape)},b:()=>{let a=Y(Wt(e),Wt(n)),u=Ut($(r,ct(e,a))),l=ye(n.shape,o);return l.length>0&&(u=pt(u,l)),R(u,n.shape)}}}};var J2={kernelName:Zo,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,Y(Wt(Q(e,"float32")),1))}}};var Q2={kernelName:Jo,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,lt(ft(1),Wt(Q(e,"float32"))))}}};function S7(r,t,e,n,o,s){let i=C(r,"dy","avgPool3dGrad"),a=C(t,"input","avgPool3dGrad"),u=i,l=a,c=!1;a.rank===4&&(c=!0,u=R(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=R(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),_(u.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),_(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),Se("avgPool3dGrad",o,s);let p={dy:u,input:l},m={filterSize:e,strides:n,pad:o,dimRoundingMode:s},f=T.runKernel(Jl,p,m);return c?R(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var tD=k({avgPool3dGrad_:S7});var eD={kernelName:Oi,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{filterSize:o,strides:s,pad:i,dimRoundingMode:a}=e;return{x:()=>tD(r,n,o,s,i,a)}}};function N7(r,t,e,n,o){let s=C(r,"dy","avgPoolGrad"),i=C(t,"input","avgPoolGrad");_(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let a=i,u=s,l=!1;i.rank===3&&(l=!0,a=R(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=R(s,[1,s.shape[0],s.shape[1],s.shape[2]])),_(u.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${u.rank}.`),_(a.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);let c={dy:u,input:a},p={filterSize:e,strides:n,pad:o},m=T.runKernel(Zl,c,p);return l?R(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var rD=k({avgPoolGrad_:N7});var nD={kernelName:ts,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{filterSize:o,strides:s,pad:i}=e;return{x:()=>rD(r,n,o,s,i)}}};var oD={kernelName:es,inputsToSave:["a","b"],gradFunc:(r,t,e)=>{let[n,o]=t,{transposeA:s,transposeB:i}=e;return!s&&!i?{a:()=>Bt(r,o,!1,!0),b:()=>Bt(n,r,!0,!1)}:!s&&i?{a:()=>Bt(r,o,!1,!1),b:()=>Bt(r,n,!0,!1)}:s&&!i?{a:()=>Bt(o,r,!1,!0),b:()=>Bt(n,r,!1,!1)}:{a:()=>Bt(o,r,!0,!0),b:()=>Bt(r,n,!0,!0)}}};var sD={kernelName:Pi,gradFunc:(r,t,e)=>{let{blockShape:n,crops:o}=e;return{x:()=>$u(r,n,o)}}};var iD={kernelName:C_,gradFunc:(r,t,e)=>{let n=e,o=n.inputShape,s=n.shape,i=Array.from(s);for(let u=o.length-1;u>=0;u--)if(o[u]===s[u])i[u]=1;else if(o[u]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${s}].`);let a=[];for(let u=0;u<i.length;u++)i[u]>1&&a.push(u);return{x:()=>pt(r,a,!0)}}};var aD={kernelName:xo,gradFunc:r=>({x:()=>r.clone()})};var lD={kernelName:rs,gradFunc:r=>({x:()=>vt(r)})};var uD={kernelName:yo,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{clipValueMin:o,clipValueMax:s}=e;return{x:()=>be(Pr(mn(n,o),Un(n,s)),r,vt(r))}}};var cD={kernelName:tu,inputsToSave:["x"],gradFunc:Ry.gradFunc};var pD={kernelName:Mi,saveAllInputs:!0,gradFunc:(r,t,e)=>{let n=t.map(u=>u.shape),{axis:o}=e,s=fr(o,t[0].shape)[0],i=n.map(u=>u[s]);return gr(r,i,s).map(u=>()=>u)}};var mD={kernelName:ns,inputsToSave:["x","filter"],gradFunc:(r,t,e)=>{let[n,o]=t,{dilations:s,strides:i,pad:a,dataFormat:u}=e;return _(co(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>pm(n.shape,r,o,i,a,u),filter:()=>$m(n,r,o.shape,i,a,u)}}};var fD={kernelName:os,inputsToSave:["dy","filter"],gradFunc:(r,t,e)=>{let[n,o]=t,{strides:s,pad:i,dataFormat:a,dimRoundingMode:u}=e;return{dy:()=>Tn(r,o,s,i,a,1,u),filter:()=>$m(r,n,o.shape,s,i,a,u)}}};function k7(r,t,e,n,o){let s=r;r.rank===4&&(s=R(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let i=t;i.rank===4&&(i=R(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),_(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),_(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),_(e.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${e}.`),_(s.shape[4]===e[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${e[3]}.`),_(i.shape[4]===e[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${e[4]}).`);let a={x:s,dy:i},u={strides:n,pad:o,filterShape:e};return T.runKernel(Ma,a,u)}var dD=k({conv3DBackpropFilter_:k7});var hD={kernelName:ss,inputsToSave:["x","filter"],gradFunc:(r,t,e)=>{let{dilations:n,strides:o,pad:s}=e;_(co(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);let[i,a]=t;return{x:()=>Fx(i.shape,r,a,o,s),filter:()=>dD(i,r,a.shape,o,s)}}};var gD={kernelName:is,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(Ut(vm(Q(e,"float32"))),r)}}};var xD={kernelName:as,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(Sm(Q(e,"float32")),r)}}};var yD={kernelName:ls,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{axis:o,exclusive:s,reverse:i}=e;return{x:()=>{let a=Q0([o],n.rank),u=dm(r,o,s,!i);return a!=null&&(u=Vt(u,a)),u}}}};var bD={kernelName:us,inputsToSave:["x","filter"],gradFunc:(r,t,e)=>{let{dilations:n,strides:o,pad:s,dimRoundingMode:i}=e,a=n==null?[1,1]:n;_(co(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[u,l]=t;return _(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${u.rank}.`),_(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`),_(u.shape[3]===l.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),_(Rr(o,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${a}'.`),Se("depthwiseConv2d",s,i),{x:()=>by(u.shape,r,l,o,s,a,i),filter:()=>yy(u,r,l.shape,o,s,a,i)}}};var wD={kernelName:cs,inputsToSave:["x","filter"],gradFunc:(r,t,e)=>{let[n,o]=t,s={x:n,filter:o,dy:r},i={x:n,filter:o,dy:r};return{x:()=>T.runKernel(nu,s,e),filter:()=>T.runKernel(ou,i,e)}}};var ID={kernelName:ms,outputsToSave:[!0],gradFunc:(r,t)=>{let[e]=t,n={dy:r,y:e};return{x:()=>T.runKernel(Ga,n)}}};var CD={kernelName:fs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t,n=$(ir(Ut(Wt(e))),2/Math.sqrt(Math.PI));return{x:()=>$(r,n)}}};var vD={kernelName:ds,outputsToSave:[!0],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,e)}}};var SD={kernelName:Li,inputsToSave:["input"],gradFunc:(r,t)=>{let[e]=t;return{input:()=>R(r,e.shape)}}};var ND={kernelName:hs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,ir(e))}}};var kD={kernelName:gs,gradFunc:r=>({x:()=>vt(r)})};var TD={kernelName:xs,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=ct(r,Q(n,"float32")),u=ye(e.shape,o);return u.length>0?R(pt(a,u),e.shape):a},b:()=>{let a=$(r,Q(e,"float32")),u=ye(n.shape,o);u.length>0&&(a=R(pt(a,u),n.shape));let l=Wt(n);return Ut(ct(a,Q(l,"float32")))}}}};var _D={kernelName:ys,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,t,e)=>{let{varianceEpsilon:n}=e,[o,s,i,a]=t,u=a==null?ft(1):a,l=ye(s.shape,o.shape),c=[];if(s.rank===1){for(let I=0;I<o.shape.length-1;++I)c.push(o.shape[I]);c.push(1)}let p=lt(o,s),m=$(r,u),f=wm(Y(i,ft(n))),d=$($($(f,f),f),ft(-.5));return{x:()=>s.rank===1?R($($(r,Or(R(f,[1,1,1,s.shape[0]]),c)),u),o.shape):R($($(r,f),u),o.shape),mean:()=>{let I=$($(f,ft(-1)),m);return s.rank===1&&(I=pt(I,l)),R(I,s.shape)},variance:()=>{let I=$($(d,p),m);return s.rank===1&&(I=pt(I,l)),R(I,s.shape)},scale:()=>{let I=$(p,f),N=$(r,I);return s.rank===1&&(N=pt(N,l)),R(N,s.shape)},offset:()=>{let I=r;return s.rank===1&&(I=pt(I,l)),R(I,s.shape)}}}};var DD={kernelName:zi,inputsToSave:["x","indices"],gradFunc:(r,t,e)=>{let[n,o]=t,{axis:s}=e,i=fr(s,n.shape)[0];return{x:()=>{let u=n.shape,l=o.size,c=u.slice(0,i),p=c.length,m=u.slice(s,u.length).slice(1),f=m.length,d=ED(0,p),h=ED(p+1,p+1+f),g=AD([c,[l],m]),x=R(r,g),b=R(o,[l]),w=AD([[p],d,h]),I=Vt(x,w),N=Dm(I,b,n.shape[i]),E=xh(w);return N=Vt(N,E),N},indices:()=>o}}};function ED(r,t){let e=[];for(let n=r;n<t;++n)e.push(n);return e}function AD(r){let t=[];for(let e=0;e<r.length;++e)for(let n=0;n<r[e].length;++n)t.push(r[e][n]);return t}var $D={kernelName:bs,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t;return{a:()=>vt(e),b:()=>vt(n)}}};var RD={kernelName:bo,gradFunc:r=>({x:()=>Q(r,"float32")})};var FD={kernelName:ws,gradFunc:r=>({x:()=>vt(r)})};var OD={kernelName:Is,gradFunc:r=>({x:()=>vt(r)})};var PD={kernelName:Cs,gradFunc:r=>({x:()=>vt(r)})};var MD={kernelName:vs,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{alpha:o}=e,s=Fe(n,0);return{x:()=>be(s,r,$(r,o))}}};var LD={kernelName:Ns,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,Y(e,1))}}};var zD={kernelName:Ss,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,Q(e,"float32"))}}};var BD={kernelName:S_,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,t,e)=>{let[n]=t,{axis:o}=e;return{logits:()=>{let i=ir(n);return lt(r,$(pt(r,o,!0),i))}}}};function T7(r,t,e,n=5,o=1,s=1,i=.5){let a={x:r,y:t,dy:e},u={depthRadius:n,bias:o,alpha:s,beta:i};return T.runKernel(Qa,a,u)}var VD=k({localResponseNormalizationBackprop_:T7});var GD={kernelName:ks,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,t,e)=>{let[n,o]=t,{depthRadius:s,bias:i,alpha:a,beta:u}=e;return{x:()=>VD(n,o,r,s,i,a,u)}}};function Fy(r,t,e,n){return t.rank<e.rank&&(t=R(t,ko(t.shape,n))),r.rank<e.rank&&(r=R(r,ko(r.shape,n))),{x:()=>$(r,Q(Fr(e,t),r.dtype))}}var TN={kernelName:Ts,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,t,e)=>{let n=e,{reductionIndices:o}=n,s=t[0],i=t[1],a=fr(o,s.shape),u=Fy(r,i,s,a);return{x:()=>u.x()}}};var WD={kernelName:_s,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t;return{a:()=>$(r,Q(mn(e,n),"float32")),b:()=>$(r,Q(Il(e,n),"float32"))}}};function _7(r,t,e,n,o,s,i){let a=C(r,"dy","maxPool3dGrad"),u=C(t,"input","maxPool3dGrad"),l=C(e,"output","maxPool3dGrad"),c=a,p=u,m=l,f=!1;u.rank===4&&(f=!0,c=R(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),p=R(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]]),m=R(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),_(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),_(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),_(m.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`),Se("maxPool3dGrad",s,i);let d={dy:c,input:p,output:m},h={filterSize:n,strides:o,pad:s,dimRoundingMode:i},g=T.runKernel(au,d,h);return f?R(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var UD=k({maxPool3dGrad_:_7});var HD={kernelName:Bi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,t,e)=>{let[n,o]=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=e;return{x:()=>UD(r,n,o,s,i,a,u)}}};function E7(r,t,e,n,o,s,i){let a=C(r,"dy","maxPoolGrad"),u=C(t,"input","maxPoolGrad"),l=C(e,"output","maxPoolGrad");_(u.rank===a.rank,()=>`Rank of input (${u.rank}) does not match rank of dy (${a.rank})`),_(a.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${a.rank}.`),_(u.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${u.rank}.`),Se("maxPoolGrad",s,i);let c={dy:a,input:u,output:l},p={filterSize:n,strides:o,pad:s,dimRoundingMode:i};return T.runKernel(iu,c,p)}var qD=k({maxPoolGrad_:E7});var KD={kernelName:Es,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,t,e)=>{let[n,o]=t,{filterSize:s,strides:i,pad:a}=e;return{x:()=>qD(r,n,o,s,i,a)}}};var jD={kernelName:As,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{axis:o}=e,s=fr(o,n.shape),a=J0(n.shape,s)[1],u=te(a);return{x:()=>{let c=n.shape.slice();s.forEach(f=>{c[f]=1});let p=R(r,c);return ct($(p,dr(n.shape,"float32")),u)}}}};var XD={kernelName:Ds,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,t,e)=>{let n=e,{axis:o}=n,[s,i]=t,a=fr(o,s.shape),u=Fy(r,i,s,a);return{x:()=>u.x()}}};var YD={kernelName:$s,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t;return{a:()=>$(r,Q(Un(e,n),"float32")),b:()=>$(r,Q(Fe(e,n),"float32"))}}};var ZD={kernelName:Rs,inputsToSave:["x"],gradFunc:(r,t,e)=>{let n=t[0],{paddings:o}=e,s=o.map(i=>i[0]);return{x:()=>Pt(r,s,n.shape)}}};var JD={kernelName:Fs,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=ye(e.shape,o);return a.length>0?R(pt(r,a),e.shape):r},b:()=>{let a=$(r,Ut(pa(ct(e,n)))),u=ye(n.shape,o);return u.length>0?R(pt(a,u),n.shape):a}}}};var QD={kernelName:Os,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=$(r,Q(n,"float32")),u=ye(e.shape,o);return u.length>0?R(pt(a,u),e.shape):a},b:()=>{let a=$(r,Q(e,"float32")),u=ye(n.shape,o);return u.length>0?R(pt(a,u),n.shape):a}}}};var t$={kernelName:Vi,gradFunc:r=>({x:()=>Ut(r)})};var e$={kernelName:Ps,inputsToSave:["indices"],gradFunc:(r,t)=>{let e=t[0];return{indices:()=>Te(e.shape,"float32")}}};var r$={kernelName:Gi,gradFunc:r=>({x:()=>vt(r)})};var n$={kernelName:Wi,saveAllInputs:!0,gradFunc:(r,t,e)=>{let{axis:n}=e;return xr(r,n).map(s=>()=>s)}};var _N={kernelName:Ms,inputsToSave:["x"],gradFunc:(r,t,e)=>{let n=t[0],{paddings:o}=e,s=o.map(i=>i[0]);return{x:()=>Pt(r,s,n.shape)}}};var o$={kernelName:Ls,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,t)=>{let[e,n,o]=t,s=e,i=n,a=Mt(s.shape,i.shape);return{a:()=>{let c=Q(i,"float32"),p=$(r,$(c,pn(s,lt(c,ft(1))))),m=ye(s.shape,a);return m.length>0&&(p=pt(p,m)),R(p,s.shape)},b:()=>{let c=Fe(s,0),p=be(c,kr(s),vt(s)),m=$(r,$(o,p)),f=ye(i.shape,a);return f.length>0&&(m=pt(m,f)),R(m,i.shape)}}}};var s$={kernelName:zs,inputsToSave:["x","alpha"],gradFunc:(r,t)=>{let[e,n]=t,o=Fe(e,0);return{x:()=>be(o,r,$(r,n)),alpha:()=>{let s=be(o,vt(r),$(r,e)),i=ye(n.shape,r.shape);return i.length>0&&(s=pt(s,i)),R(s,n.shape)}}}};function A7(r,t,e){let n=r.shape.slice();n[e]=1;let o=R(t,n),s=Ic(r,e,!0,!1),i=Ic(r,e,!0,!0),a=$(s,i);return $(o,a)}function D7(r,t,e){let n=r.shape.length,o=n-e.length,s=S.getAxesPermutation(e,n),i=r;s!=null&&(i=Vt(r,s));let a=i.shape.slice(),l=a.splice(n-e.length,e.length).reduce((m,f)=>m*f,1);a.push(l);let c=i.reshape(a),p=A7(c,t,o);if(p=p.reshape(i.shape),s!=null){let m=S.getUndoAxesPermutation(s);p=Vt(p,m)}return p}var i$={kernelName:Bs,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{axis:o}=e,s=[];return o==null?s=n.shape.map((i,a)=>a):typeof o=="number"?s=[o]:s=o,{x:()=>D7(n,r,s)}}};var a$={kernelName:ps,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=ct(r,Q(n,"float32")),u=ye(e.shape,o);return u.length>0?R(pt(a,u),e.shape):a},b:()=>{let a=$(r,Q(e,"float32")),u=ye(n.shape,o);u.length>0&&(a=R(pt(a,u),n.shape));let l=Wt(n);return Ut(ct(a,Q(l,"float32")))}}}};var l$={kernelName:Vs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,Ut(Wt(e)))}}};var u$={kernelName:Hs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t,n=$(Un(e,6),To(e));return{x:()=>$(r,Q(n,"float32"))}}};var c$={kernelName:Gs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,Q(To(e),"float32"))}}};var p$={kernelName:Ui,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>R(r,e.shape)}}};var m$={kernelName:Us,inputsToSave:["images"],gradFunc:(r,t,e)=>{let[n]=t,o={dy:r,images:n};return{images:()=>T.runKernel(il,o,e)}}};var f$={kernelName:Ws,inputsToSave:["images"],gradFunc:(r,t,e)=>{let[n]=t,o={dy:r,images:n};return{images:()=>T.runKernel(sl,o,e)}}};var d$={kernelName:qs,gradFunc:(r,t,e)=>{let{dims:n}=e,o=fr(n,r.shape);return{x:()=>hr(r,o)}}};var h$={kernelName:Ks,gradFunc:r=>({x:()=>vt(r)})};var g$={kernelName:js,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>Ut(ct(r,$(pn(e,1.5),2)))}}};var x$={kernelName:Hi,inputsToSave:["condition"],gradFunc:(r,t)=>{let[e]=t;return{condition:()=>Q(vt(e),"float32"),t:()=>$(r,Q(e,r.dtype)),e:()=>$(r,Q(Au(e),r.dtype))}}};var y$={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=Fe(e,ft(0)),o=ft(vN),s=ft(SN),i=$(r,s),a=$($(r,o),ir(Q(e,"float32")));return be(n,i,a)}}}};var b$={kernelName:Qs,outputsToSave:[!0],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,$(e,lt(ft(1),e)))}}};var w$={kernelName:Js,gradFunc:r=>({x:()=>vt(r)})};var I$={kernelName:Ys,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(ku(Q(e,"float32")),r)}}};var C$={kernelName:Zs,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(fm(Q(e,"float32")),r)}}};var v$={kernelName:qi,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{begin:o,size:s}=e,i=n.shape,[a,u]=CN(n,o,s),l=[];for(let c=0;c<r.rank;c++)l.push([a[c],i[c]-a[c]-u[c]]);return{x:()=>dn(r,l)}}};var S$={kernelName:ni,outputsToSave:[!0],gradFunc:(r,t,e)=>{let[n]=t,{dim:o}=e,s=!0,i=$(r,n);return{logits:()=>lt(i,$(pt(i,[o],s),n))}}};var N$={kernelName:ti,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,en(e))}}};var EN={kernelName:Ki,gradFunc:(r,t,e)=>{let{blockShape:n,paddings:o}=e;return{x:()=>Nu(r,n,o)}}};var AN={kernelName:ji,gradFunc:(r,t,e)=>{let{axis:n}=e;return{x:()=>ie(r,n)}}};var k$={kernelName:ei,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,$(Ne(Q(e,"float32")),2))}}};var T$={kernelName:fu,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(r,$(Q(e,"float32"),2))}}};var _$={kernelName:oi,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=ft(2);return{a:()=>$(r,$(o,lt(e,n))),b:()=>$(r,$(o,lt(n,e)))}}};var E$={kernelName:wo,gradFunc:r=>({x:()=>vt(r)})};var A$={kernelName:si,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Mt(e.shape,n.shape);return{a:()=>{let a=r,u=ye(e.shape,o);return u.length>0&&(a=pt(a,u)),R(a,e.shape)},b:()=>{let a=r,u=ye(n.shape,o);return u.length>0&&(a=pt(a,u)),R(Ut(a),n.shape)}}}};var D$={kernelName:ri,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,o=n.shape.slice(),{axis:s}=e;fr(s,n.shape).forEach(l=>{o[l]=1});let a=R(r,o),u=$(a,dr(n.shape,"float32"));return{x:()=>u}}};var $$={kernelName:ii,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,Wt(ku(e)))}}};var R$={kernelName:ai,outputsToSave:[!0],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$(lt(ft(1),Wt(e)),r)}}};var F$={kernelName:lo,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{reps:o}=e;return{x:()=>{let i=vt(n);if(n.rank===1)for(let a=0;a<o[0];++a)i=Y(i,Pt(r,[a*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let a=0;a<o[0];++a)for(let u=0;u<o[1];++u)i=Y(i,Pt(r,[a*n.shape[0],u*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let a=0;a<o[0];++a)for(let u=0;u<o[1];++u)for(let l=0;l<o[2];++l)i=Y(i,Pt(r,[a*n.shape[0],u*n.shape[1],l*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let a=0;a<o[0];++a)for(let u=0;u<o[1];++u)for(let l=0;l<o[2];++l)for(let c=0;c<o[3];++c)i=Y(i,Pt(r,[a*n.shape[0],u*n.shape[1],l*n.shape[2],c*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);return i}}}};var O$={kernelName:uo,gradFunc:(r,t,e)=>{let n=e,{perm:o}=n,s=xh(o);return{x:()=>Vt(r,s)}}};var P$={kernelName:Xi,gradFunc:(r,t,e)=>{let n=e,{axis:o}=n;return{value:()=>qe(r,o)}}};var M$={kernelName:yu,inputsToSave:["segmentIds"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>$7(r,e)}}};function $7(r,t){let e=_n(t,vt(t)),n=ma(r,e),o=mn(t,ft(0,"int32")),s=n.rank-o.rank;for(let a=0;a<s;++a)o=ar(o,a+1);o=Pr(o,dr(n.shape,"bool"));let i=vt(n);return be(o,n,i)}var L$={kernelName:Yi,gradFunc:r=>({x:()=>vt(r)})};var R7=[Ry,W2,U2,H2,q2,K2,j2,X2,Y2,Z2,J2,Q2,eD,nD,oD,sD,iD,aD,lD,uD,cD,pD,fD,mD,hD,gD,xD,yD,bD,wD,a$,ID,CD,vD,SD,ND,TD,kD,_D,DD,$D,RD,FD,OD,PD,MD,LD,zD,BD,GD,TN,TN,WD,HD,KD,jD,XD,YD,ZD,JD,QD,t$,e$,r$,n$,_N,_N,o$,s$,i$,l$,u$,c$,p$,m$,f$,d$,h$,g$,x$,y$,b$,w$,I$,C$,v$,S$,N$,EN,EN,AN,AN,k$,_$,T$,E$,A$,D$,$$,R$,F$,O$,P$,M$,L$];for(let r of R7)k_(r);O().prototype.abs=function(){return this.throwIfDisposed(),Ee(this)};O().prototype.acos=function(){return this.throwIfDisposed(),hx(this)};O().prototype.acosh=function(){return this.throwIfDisposed(),gx(this)};O().prototype.add=function(r){return this.throwIfDisposed(),Y(this,r)};O().prototype.all=function(r,t){return this.throwIfDisposed(),lm(this,r,t)};O().prototype.any=function(r,t){return this.throwIfDisposed(),bc(this,r,t)};O().prototype.argMax=function(r){return this.throwIfDisposed(),oa(this,r)};O().prototype.argMin=function(r){return this.throwIfDisposed(),xx(this,r)};O().prototype.asScalar=function(){return this.throwIfDisposed(),_(this.size===1,()=>"The array must have only 1 element."),R(this,[])};O().prototype.asType=function(r){return this.throwIfDisposed(),Q(this,r)};O().prototype.as1D=function(){return this.throwIfDisposed(),R(this,[this.size])};O().prototype.as2D=function(r,t){return this.throwIfDisposed(),R(this,[r,t])};O().prototype.as3D=function(r,t,e){return this.throwIfDisposed(),R(this,[r,t,e])};O().prototype.as4D=function(r,t,e,n){return this.throwIfDisposed(),R(this,[r,t,e,n])};O().prototype.as5D=function(r,t,e,n,o){return this.throwIfDisposed(),R(this,[r,t,e,n,o])};O().prototype.asin=function(){return this.throwIfDisposed(),yx(this)};O().prototype.asinh=function(){return this.throwIfDisposed(),bx(this)};O().prototype.atan=function(){return this.throwIfDisposed(),wx(this)};O().prototype.atan2=function(r){return this.throwIfDisposed(),Ix(this,r)};O().prototype.atanh=function(){return this.throwIfDisposed(),Cx(this)};O().prototype.avgPool=function(r,t,e,n){return this.throwIfDisposed(),Su(this,r,t,e,n)};O().prototype.batchToSpaceND=function(r,t){return this.throwIfDisposed(),Nu(this,r,t)};O().prototype.batchNorm=function(r,t,e,n,o){return this.throwIfDisposed(),aa(this,r,t,e,n,o)};O().prototype.broadcastTo=function(r){return this.throwIfDisposed(),la(this,r)};O().prototype.cast=function(r){return this.throwIfDisposed(),Q(this,r)};O().prototype.ceil=function(){return this.throwIfDisposed(),_x(this)};O().prototype.clipByValue=function(r,t){return this.throwIfDisposed(),Sr(this,r,t)};O().prototype.concat=function(r,t){return this.throwIfDisposed(),r instanceof Ot&&(r=[r]),ie([this,...r],t)};O().prototype.conv1d=function(r,t,e,n,o,s){return this.throwIfDisposed(),cm(this,r,t,e,n,o,s)};O().prototype.conv2dTranspose=function(r,t,e,n,o){return this.throwIfDisposed(),mm(this,r,t,e,n,o)};O().prototype.conv2d=function(r,t,e,n,o,s){return this.throwIfDisposed(),Tn(this,r,t,e,n,o,s)};O().prototype.cos=function(){return this.throwIfDisposed(),ku(this)};O().prototype.cosh=function(){return this.throwIfDisposed(),fm(this)};O().prototype.cumprod=function(r,t,e){return this.throwIfDisposed(),Ic(this,r,t,e)};O().prototype.cumsum=function(r,t,e){return this.throwIfDisposed(),dm(this,r,t,e)};O().prototype.depthToSpace=function(r,t){return this.throwIfDisposed(),Px(this,r,t)};O().prototype.depthwiseConv2d=function(r,t,e,n,o,s){return this.throwIfDisposed(),ua(this,r,t,e,n,o,s)};O().prototype.dilation2d=function(r,t,e,n,o){return this.throwIfDisposed(),Mx(this,r,t,e,n,o)};O().prototype.divNoNan=function(r){return this.throwIfDisposed(),Lx(this,r)};O().prototype.div=function(r){return this.throwIfDisposed(),ct(this,r)};O().prototype.dot=function(r){return this.throwIfDisposed(),zx(this,r)};O().prototype.elu=function(){return this.throwIfDisposed(),ca(this)};O().prototype.equal=function(r){return this.throwIfDisposed(),Fr(this,r)};O().prototype.erf=function(){return this.throwIfDisposed(),Bx(this)};O().prototype.euclideanNorm=function(r,t){return this.throwIfDisposed(),Vx(this,r,t)};O().prototype.exp=function(){return this.throwIfDisposed(),ir(this)};O().prototype.expandDims=function(r){return this.throwIfDisposed(),ar(this,r)};O().prototype.expm1=function(){return this.throwIfDisposed(),Gx(this)};O().prototype.fft=function(){return this.throwIfDisposed(),Ou(this)};O().prototype.flatten=function(){return this.throwIfDisposed(),R(this,[this.size])};O().prototype.floor=function(){return this.throwIfDisposed(),pa(this)};O().prototype.floorDiv=function(r){return this.throwIfDisposed(),am(this,r)};O().prototype.gather=function(r,t,e){return this.throwIfDisposed(),ma(this,r,t,e)};O().prototype.greaterEqual=function(r){return this.throwIfDisposed(),mn(this,r)};O().prototype.greater=function(r){return this.throwIfDisposed(),Fe(this,r)};O().prototype.ifft=function(){return this.throwIfDisposed(),vl(this)};O().prototype.irfft=function(){return this.throwIfDisposed(),Tm(this)};O().prototype.isFinite=function(){return this.throwIfDisposed(),Wx(this)};O().prototype.isInf=function(){return this.throwIfDisposed(),Ux(this)};O().prototype.isNaN=function(){return this.throwIfDisposed(),Hx(this)};O().prototype.leakyRelu=function(r){return this.throwIfDisposed(),_u(this,r)};O().prototype.lessEqual=function(r){return this.throwIfDisposed(),Un(this,r)};O().prototype.less=function(r){return this.throwIfDisposed(),Il(this,r)};O().prototype.localResponseNormalization=function(r,t,e,n){return this.throwIfDisposed(),qx(this,r,t,e,n)};O().prototype.logSigmoid=function(){return this.throwIfDisposed(),Xx(this)};O().prototype.logSoftmax=function(r){return this.throwIfDisposed(),hm(this,r)};O().prototype.logSumExp=function(r,t){return this.throwIfDisposed(),gm(this,r,t)};O().prototype.log=function(){return this.throwIfDisposed(),kr(this)};O().prototype.log1p=function(){return this.throwIfDisposed(),Eu(this)};O().prototype.logicalAnd=function(r){return this.throwIfDisposed(),Pr(this,r)};O().prototype.logicalNot=function(){return this.throwIfDisposed(),Au(this)};O().prototype.logicalOr=function(r){return this.throwIfDisposed(),xm(this,r)};O().prototype.logicalXor=function(r){return this.throwIfDisposed(),Yx(this,r)};O().prototype.matMul=function(r,t,e){return this.throwIfDisposed(),Bt(this,r,t,e)};O().prototype.maxPool=function(r,t,e,n){return this.throwIfDisposed(),Du(this,r,t,e,n)};O().prototype.max=function(r,t){return this.throwIfDisposed(),Nr(this,r,t)};O().prototype.maximum=function(r){return this.throwIfDisposed(),_n(this,r)};O().prototype.mean=function(r,t){return this.throwIfDisposed(),ke(this,r,t)};O().prototype.min=function(r,t){return this.throwIfDisposed(),bl(this,r,t)};O().prototype.minimum=function(r){return this.throwIfDisposed(),mo(this,r)};O().prototype.mirrorPad=function(r,t){return this.throwIfDisposed(),Qx(this,r,t)};O().prototype.mod=function(r){return this.throwIfDisposed(),ty(this,r)};O().prototype.mul=function(r){return this.throwIfDisposed(),$(this,r)};O().prototype.neg=function(){return this.throwIfDisposed(),Ut(this)};O().prototype.norm=function(r,t,e){return this.throwIfDisposed(),wl(this,r,t,e)};O().prototype.notEqual=function(r){return this.throwIfDisposed(),mi(this,r)};O().prototype.oneHot=function(r,t=1,e=0){return this.throwIfDisposed(),fa(this,r,t,e)};O().prototype.onesLike=function(){return this.throwIfDisposed(),Ir(this)};O().prototype.pad=function(r,t){return this.throwIfDisposed(),dn(this,r,t)};O().prototype.pool=function(r,t,e,n,o,s){return this.throwIfDisposed(),ey(this,r,t,e,n,o,s)};O().prototype.pow=function(r){return this.throwIfDisposed(),pn(this,r)};O().prototype.prelu=function(r){return this.throwIfDisposed(),Ru(this,r)};O().prototype.prod=function(r,t){return this.throwIfDisposed(),ry(this,r,t)};O().prototype.reciprocal=function(){return this.throwIfDisposed(),ly(this)};O().prototype.relu=function(){return this.throwIfDisposed(),Mr(this)};O().prototype.relu6=function(){return this.throwIfDisposed(),ym(this)};O().prototype.reshapeAs=function(r){return this.throwIfDisposed(),R(this,r.shape)};O().prototype.reshape=function(r){return this.throwIfDisposed(),R(this,r)};O().prototype.resizeBilinear=function(r,t,e){return this.throwIfDisposed(),Ny(this,r,t,e)};O().prototype.resizeNearestNeighbor=function(r,t,e){return this.throwIfDisposed(),ky(this,r,t,e)};O().prototype.reverse=function(r){return this.throwIfDisposed(),hr(this,r)};O().prototype.rfft=function(){return this.throwIfDisposed(),Pu(this)};O().prototype.round=function(){return this.throwIfDisposed(),bm(this)};O().prototype.rsqrt=function(){return this.throwIfDisposed(),wm(this)};O().prototype.selu=function(){return this.throwIfDisposed(),Im(this)};O().prototype.separableConv2d=function(r,t,e,n,o,s){return this.throwIfDisposed(),Cm(this,r,t,e,n,o,s)};O().prototype.sigmoid=function(){return this.throwIfDisposed(),en(this)};O().prototype.sign=function(){return this.throwIfDisposed(),uy(this)};O().prototype.sin=function(){return this.throwIfDisposed(),vm(this)};O().prototype.sinh=function(){return this.throwIfDisposed(),Sm(this)};O().prototype.slice=function(r,t){return this.throwIfDisposed(),Pt(this,r,t)};O().prototype.softmax=function(r){return this.throwIfDisposed(),Fu(this,r)};O().prototype.softplus=function(){return this.throwIfDisposed(),pi(this)};O().prototype.spaceToBatchND=function(r,t){return this.throwIfDisposed(),$u(this,r,t)};O().prototype.split=function(r,t){return this.throwIfDisposed(),gr(this,r,t)};O().prototype.sqrt=function(){return this.throwIfDisposed(),Ne(this)};O().prototype.square=function(){return this.throwIfDisposed(),Wt(this)};O().prototype.squaredDifference=function(r){return this.throwIfDisposed(),_m(this,r)};O().prototype.squeeze=function(r){return this.throwIfDisposed(),qn(this,r)};O().prototype.stack=function(r,t){this.throwIfDisposed();let e=r instanceof Ot?[this,r]:[this,...r];return qe(e,t)};O().prototype.step=function(r){return this.throwIfDisposed(),To(this,r)};O().prototype.stridedSlice=function(r,t,e,n,o,s,i,a){return this.throwIfDisposed(),cy(this,r,t,e,n,o,s,i,a)};O().prototype.sub=function(r){return this.throwIfDisposed(),lt(this,r)};O().prototype.sum=function(r,t){return this.throwIfDisposed(),pt(this,r,t)};O().prototype.tan=function(){return this.throwIfDisposed(),py(this)};O().prototype.tanh=function(){return this.throwIfDisposed(),ia(this)};O().prototype.tile=function(r){return this.throwIfDisposed(),Or(this,r)};O().prototype.toBool=function(){return this.throwIfDisposed(),Q(this,"bool")};O().prototype.toFloat=function(){return this.throwIfDisposed(),Q(this,"float32")};O().prototype.toInt=function(){return this.throwIfDisposed(),Q(this,"int32")};O().prototype.topk=function(r,t){return this.throwIfDisposed(),fy(this,r,t)};O().prototype.transpose=function(r){return this.throwIfDisposed(),Vt(this,r)};O().prototype.unique=function(r){return this.throwIfDisposed(),dy(this,r)};O().prototype.unsortedSegmentSum=function(r,t){return this.throwIfDisposed(),Dm(this,r,t)};O().prototype.unstack=function(r){return this.throwIfDisposed(),xr(this,r)};O().prototype.where=function(r,t){return this.throwIfDisposed(),be(r,this,t)};O().prototype.zerosLike=function(){return this.throwIfDisposed(),vt(this)};var En=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,En.prototype)}},Xr=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Xr.prototype)}},z=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,z.prototype)}},kt=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,kt.prototype)}},Rm=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Rm.prototype)}};var Th=class{constructor(t){this.maxEntries=t||100,this.cache=new Map}get(t){let e;return this.cache.has(t)&&(e=this.cache.get(t),this.cache.delete(t),this.cache.set(t,e)),e}put(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxEntries){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(t,e)}getMaxEntries(){return this.maxEntries}setMaxEntries(t){if(t<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${t}.`);if(this.maxEntries>t)for(let e=0;e<this.maxEntries-t;e++){let n=this.cache.keys().next().value;this.cache.delete(n)}this.maxEntries=t}};function Ao(r,t){if(Array.isArray(r)){let e=[];for(let n=0;n<t;n++)e=e.concat(r);return e}else{let e=new Array(t);return e.fill(r),e}}function fo(r,t){if(!r)throw new Rm(t)}function $N(r,t){let e=0;for(let n of r)n===t&&e++;return e}function Tr(r){return r.length===1?r[0]:r}function we(r){return Array.isArray(r)?r:[r]}function Do(r){let e=r.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return e[0]!=="_"?e:"private"+e}function kl(r){return r.length<=1||r.indexOf("_")===-1?r:r.replace(/[_]+(\w|$)/g,(t,e)=>e.toUpperCase())}var Eo={};function Fm(r){if(r==null)return null;let t={};return t.className=r.getClassName(),t.config=r.getConfig(),t}function DN(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(t=>DN(t));else{let t=Object.keys(r);for(let e of t){let n=r[e];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?r[e]=n.value:DN(n))}}}function xa(r,t={},e={},n="object",o=!1){if(typeof r=="string"){let s=r,i;if(s in e)i=e[s];else if(s in Eo)i=Eo[s];else if(i=t[s],i==null)throw new z(`Unknown ${n}: ${r}. This may be due to one of the following reasons:
| 1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
| 2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=r;if(s.className==null||s.config==null)throw new z(`${n}: Improper config format: ${JSON.stringify(s)}.
| 'className' and 'config' must set.`);let i=s.className,a,u;if(i in e?[a,u]=e[i]:i in Eo?[a,u]=Eo.className:i in t&&([a,u]=t[i]),a==null)throw new z(`Unknown ${n}: ${i}. This may be due to one of the following reasons:
| 1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
| 2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(u!=null){let l={};for(let f of Object.keys(Eo))l[f]=Eo[f];for(let f of Object.keys(e))l[f]=e[f];let c=s.config;c.customObjects=l;let p=Object.assign({},Eo);for(let f of Object.keys(e))Eo[f]=e[f];DN(s.config);let m=u(a,s.config,e,o);return Eo=Object.assign({},p),m}else{let l=Object.assign({},Eo);for(let p of Object.keys(e))Eo[p]=e[p];let c=new a(s.config);return Eo=Object.assign({},l),c}}}function F7(r,t){return r<t?-1:r>t?1:0}function _h(r,t){return-1*F7(r,t)}function $o(r){if(r==null)return r;let t=[];for(let e of r)t.indexOf(e)===-1&&t.push(e);return t}function z$(r){if(r==null)throw new z(`Invalid value in obj: ${JSON.stringify(r)}`);for(let t in r)if(r.hasOwnProperty(t))return!1;return!0}function ya(r,t,e){if(e!=null&&r.indexOf(e)<0)throw new z(`${e} is not a valid ${t}. Valid values are ${r} or null/undefined.`)}function Oy(r,t,e=0,n=1/0){return fo(e>=0),fo(n>=e),Array.isArray(r)&&r.length>=e&&r.length<=n&&r.every(o=>typeof o===t)}function Qe(r,t){Array.isArray(r)?(y.assert(r.length>0,()=>`${t} is unexpectedly an empty array.`),r.forEach((e,n)=>Qe(e,`element ${n+1} of ${t}`))):y.assert(Number.isInteger(r)&&r>0,()=>`Expected ${t} to be a positive integer, but got ${B$(r)}.`)}function B$(r){return r===null?"null":Array.isArray(r)?"["+r.map(t=>B$(t)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function V$(r,t,e){let n=e!=null?e():y.now(),o;return(...i)=>{let a=e!=null?e():y.now();return a-n<t||(n=a,o=r(...i)),o}}function Py(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}var O7=0;function Ly(){return O7++}var My={};function zu(r=""){return r in My||(My[r]=0),My[r]+=1,r+My[r].toString()}var G$=["channelsFirst","channelsLast"],W$=["nearest","bilinear"],U$=["valid","same","causal"],H$=["max","avg"],q$=["sum","mul","concat","ave"];var Om=new Map;function Oe(r){ya(G$,"DataFormat",r)}function j$(r){ya(W$,"InterpolationFormat",r)}function gn(r){ya(U$,"PaddingMode",r)}function RN(r){ya(H$,"PoolMode",r)}var Eh=[],K$="/";function hi(r,t){Eh.push(r);try{let e=t();return Eh.pop(),e}catch(e){throw Eh.pop(),e}}function P7(){return Eh.length===0?"":Eh.join(K$)+K$}function zy(r){if(!X$(r))throw new Error("Not a valid tensor name: '"+r+"'");return P7()+r}function By(r){if(!X$(r))throw new Error("Not a valid tensor name: '"+r+"'");Om.has(r)||Om.set(r,0);let t=Om.get(r);if(Om.set(r,Om.get(r)+1),t>0){let e=`${r}_${t}`;return Om.set(e,1),e}else return r}var M7=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function X$(r){return!!r.match(M7)}function Y$(r){return r===parseInt(r.toString(),10)}function Ro(r,t,e){t==null&&(t=0),e==null&&(e=r.length);let n=1;for(let o=t;o<e;++o)n*=r[o];return n}function Bc(r){if(r.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let e=0;e<r.length;e++){let n=r[e];n<t&&(t=n)}return t}function gi(r){if(r.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let e=0;e<r.length;e++){let n=r[e];n>t&&(t=n)}return t}function xn(r,t){if(t<r)throw new z(`end (${t}) < begin (${r}) is forbidden.`);let e=[];for(let n=r;n<t;++n)e.push(n);return e}var FN;function cr(){return FN==null&&(FN=wE().epsilon()),FN}function yn(){return"channelsLast"}function rn(r,t){return Q(r,t)}function _l(r,t=-1){let e=r.shape.slice();return t<0&&(t=e.length+t+1),e.splice(t,0,1),R(r,e)}function Z$(r,t){return B(()=>{if(r.shape.length!==2)throw new z(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);let e=_l(r,1);return Gy(e,[1,t,1])})}function J$(r){let t=[Ro(r.shape)];return R(r,t)}function Q$(r){if(r.rank<=1)throw new z(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);let t=[r.shape[0],Ro(r.shape,1)];return R(r,t)}function Tl(r,t,e){return B(()=>{switch(r.rank){case 1:return Nm(r,t,e);case 2:return wh(r,[t,0],[e,r.shape[1]]);case 3:return km(r,[t,0,0],[e,r.shape[1],r.shape[2]]);case 4:return Tc(r,[t,0,0,0],[e,r.shape[1],r.shape[2],r.shape[3]]);case 5:return Pt(r,[t,0,0,0,0],[e,r.shape[1],r.shape[2],r.shape[3],r.shape[4]]);case 6:return Pt(r,[t,0,0,0,0,0],[e,r.shape[1],r.shape[2],r.shape[3],r.shape[4],r.shape[5]]);default:throw new z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}})}function ON(r,t,e){return B(()=>{switch(r.rank){case 1:return Nm(r,t,e);case 2:return wh(r,[0,t],[r.shape[0],e]);case 3:return km(r,[0,0,t],[r.shape[0],r.shape[1],e]);case 4:return Tc(r,[0,0,0,t],[r.shape[0],r.shape[1],r.shape[2],e]);default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function Ah(r,t,e,n){return B(()=>{switch(r.rank){case 1:return Nm(r,t,e);case 2:switch(n){case 1:return Tl(r,t,e);case 2:return ON(r,t,e);default:throw new z(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return Tl(r,t,e);case 2:return km(r,[0,t,0],[r.shape[0],e,r.shape[2]]);case 3:return ON(r,t,e);default:throw new z(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return Tl(r,t,e);case 2:return Tc(r,[0,t,0,0],[r.shape[0],e,r.shape[2],r.shape[3]]);case 3:return Tc(r,[0,0,t,0],[r.shape[0],r.shape[1],e,r.shape[3]]);case 4:return ON(r,t,e);default:throw new z(`The axis is not within the rank of the tensor ${n}`)}default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function Pm(r,t=-1){let e;return t<0&&(e=r[0].rank,e!==0?t=e:t=0),t===r[0].rank&&(t=-1),ie(r,t)}function MN(r,t){switch(r.rank){case 1:return Ex([r,t]);case 2:return Ax([r,t],0);case 3:return Dx([r,t],0);case 4:return $x([r,t],0);default:throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}}function Gy(r,t){if(Array.isArray(t)||(t=[t]),r.rank!==t.length)throw new z(`The length of input n (${t.length}) does not match the number of dimensions in input x (${r.rank})`);return Or(r,t)}function Mm(r,t=0,e=1,n,o){return kc(r,t,e,n,o)}function Fo(r,t,e,n){if(r.rank<2||t.rank<2)throw new kt(`dot requires both inputs to be rank >= 2 but got x shape = ${r.shape} and y shape = ${t.shape}`);if(t.rank>=3){let o=r.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(o!==s)throw new kt(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${r.shape} and y shape = ${t.shape}`)}if(r.rank===2&&t.rank===2)return Lu.matMul({a:r,b:t,transposeA:!1,transposeB:!1,bias:n?PN(r.rank,n,yn()):null,activation:e});{let o=r.shape.slice(),s=o.pop();r=R(r,[-1,s]);let i=t.shape.slice(),a=i.pop(),u=i.pop(),l=[...i,a],c=Array.from({length:t.rank},(d,h)=>h===0?t.rank-2:h<=t.rank-2?h-1:h);t=R(Vt(t,c),[u,-1]);let p=[...o,...l],m=!1,f=!1;return R(Lu.matMul({a:r,b:t,transposeA:m,transposeB:f,bias:n?PN(r.rank,n,yn()):null,activation:e}),p)}}function Wy(r,t,e){return B(()=>(Array.isArray(t)?t=Ke(t,"int32"):t=Q(t,"int32"),ma(r,t,e)))}function Vc(r){return $(r,r)}function PN(r,t,e){let n=t.shape;if(t.rank!==1&&t.rank!==r)throw new z(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${r}`);if(r===5){if(e==="channelsFirst")return n.length===1?R(t,[1,n[0],1,1,1]):R(t,[1,n[3],n[0],n[1],n[2]]);if(e==="channelsLast")return n.length===1?R(t,[1,1,1,1,n[0]]):R(t,[1].concat(n))}else if(r===4){if(e==="channelsFirst")return n.length===1?R(t,[1,n[0],1,1]):R(t,[1,n[2],n[0],n[1]]);if(e==="channelsLast")return n.length===1?R(t,[1,1,1,n[0]]):R(t,[1].concat(n))}else if(r===3){if(e==="channelsFirst")return n.length===1?R(t,[1,n[0],1]):R(t,[1,n[1],n[0]]);if(e==="channelsLast")return n.length===1?R(t,[1,1,n[0]]):R(t,[1].concat(n))}else if(r<3)return t;throw new z(`Unsupported input rank by biasAdd: ${t.rank}`)}function bn(r,t,e){return B(()=>(e==null&&(e=yn()),Oe(e),Y(r,PN(r.rank,t,e))))}function tR(r,t=1){if(t!==1)throw new kt(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return ca(r)}function eR(r){return B(()=>ct(r,Y(Ee(r),1)))}function Uy(r,t,e,n){return B(()=>cN(r,t,e,n))}function rR(r){return B(()=>{let t=Y(.5,$(.2,r));return Sr(t,0,1)})}function Bu(r,t,e=!1){return e?r():t()}var nR=["fanIn","fanOut","fanAvg"],oR=["normal","uniform","truncatedNormal"];function L7(r){ya(nR,"FanMode",r)}function z7(r){ya(oR,"Distribution",r)}var wn=class extends J.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Lm=class extends wn{apply(t,e){return Te(t,e)}};Lm.className="Zeros";J.registerClass(Lm);var Vu=class extends wn{apply(t,e){return dr(t,e)}};Vu.className="Ones";J.registerClass(Vu);var zm=class extends wn{constructor(t){if(super(),typeof t!="object")throw new z(`Expected argument of type ConstantConfig but got ${t}`);if(t.value===void 0)throw new z(`config must have value set but got ${t}`);this.value=t.value}apply(t,e){return B(()=>$(ft(this.value),dr(t,e)))}getConfig(){return{value:this.value}}};zm.className="Constant";J.registerClass(zm);var Bm=class extends wn{constructor(t){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=t.minval||this.DEFAULT_MINVAL,this.maxval=t.maxval||this.DEFAULT_MAXVAL,this.seed=t.seed}apply(t,e){return Hn(t,this.minval,this.maxval,e,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};Bm.className="RandomUniform";J.registerClass(Bm);var Vm=class extends wn{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if(e=e||"float32",e!=="float32"&&e!=="int32")throw new kt(`randomNormal does not support dType ${e}.`);return Mm(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Vm.className="RandomNormal";J.registerClass(Vm);var Gm=class extends wn{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if(e=e||"float32",e!=="float32"&&e!=="int32")throw new kt(`truncatedNormal does not support dType ${e}.`);return Am(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Gm.className="TruncatedNormal";J.registerClass(Gm);var Wm=class extends wn{constructor(t){super(),this.gain=t.gain!=null?t.gain:1}apply(t,e){return B(()=>{if(t.length!==2||t[0]!==t[1])throw new z("Identity matrix initializer can only be used for 2D square matrices.");return $(this.gain,Cc(t[0]))})}getConfig(){return{gain:this.gain}}};Wm.className="Identity";J.registerClass(Wm);function B7(r,t="channelsLast"){let e,n;if(Oe(t),r.length===2)e=r[0],n=r[1];else if([3,4,5].indexOf(r.length)!==-1){if(t==="channelsFirst"){let o=Ro(r,2);e=r[1]*o,n=r[0]*o}else if(t==="channelsLast"){let o=Ro(r,0,r.length-2);e=r[r.length-2]*o,n=r[r.length-1]*o}}else{let o=Ro(r);e=Math.sqrt(o),n=Math.sqrt(o)}return[e,n]}var Yr=class extends wn{constructor(t){if(super(),t.scale<0)throw new z(`scale must be a positive float. Got: ${t.scale}`);this.scale=t.scale==null?1:t.scale,this.mode=t.mode==null?"fanIn":t.mode,L7(this.mode),this.distribution=t.distribution==null?"normal":t.distribution,z7(this.distribution),this.seed=t.seed}apply(t,e){let n=B7(t),o=n[0],s=n[1],i=this.scale;if(this.mode==="fanIn"?i/=Math.max(1,o):this.mode==="fanOut"?i/=Math.max(1,s):i/=Math.max(1,(o+s)/2),this.distribution==="normal"){let a=Math.sqrt(i);if(e=e||"float32",e!=="float32"&&e!=="int32")throw new kt(`${this.getClassName()} does not support dType ${e}.`);return Am(t,0,a,e,this.seed)}else{let a=Math.sqrt(3*i);return Hn(t,-a,a,e,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Yr.className="VarianceScaling";J.registerClass(Yr);var Gc=class extends Yr{constructor(t){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Yr.className}};Gc.className="GlorotUniform";J.registerClass(Gc);var Wc=class extends Yr{constructor(t){super({scale:1,mode:"fanAvg",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Yr.className}};Wc.className="GlorotNormal";J.registerClass(Wc);var Uc=class extends Yr{constructor(t){super({scale:2,mode:"fanIn",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Yr.className}};Uc.className="HeNormal";J.registerClass(Uc);var Hc=class extends Yr{constructor(t){super({scale:2,mode:"fanIn",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Yr.className}};Hc.className="HeUniform";J.registerClass(Hc);var qc=class extends Yr{constructor(t){super({scale:1,mode:"fanIn",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Yr.className}};qc.className="LeCunNormal";J.registerClass(qc);var Kc=class extends Yr{constructor(t){super({scale:1,mode:"fanIn",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Yr.className}};Kc.className="LeCunUniform";J.registerClass(Kc);var Um=class extends wn{constructor(t){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=t.gain==null?this.DEFAULT_GAIN:t.gain,this.seed=t.seed}apply(t,e){return B(()=>{if(t.length<2)throw new kt("Shape must be at least 2D.");if(e!=="int32"&&e!=="float32"&&e!==void 0)throw new TypeError(`Unsupported data type ${e}.`);e=e;let n=y.sizeFromShape(t.slice(0,-1)),o=t[t.length-1],s=n*o;s>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${s}) elements: Slowness may result.`);let i=[Math.max(o,n),Math.min(o,n)],a=Mm(i,0,1,e,this.seed),u=fN.qr(a,!1),l=u[0],p=u[1].flatten().stridedSlice([0],[Math.min(o,n)*Math.min(o,n)],[Math.min(o,n)+1]);return l=$(l,p.sign()),n<o&&(l=l.transpose()),$(ft(this.gain),l.reshape(t))})}getConfig(){return{gain:this.gain,seed:this.seed}}};Um.className="Orthogonal";J.registerClass(Um);var sR={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function iR(r,t={}){return xa(r,J.SerializationMap.getMap().classNameMap,t,"initializer")}function _e(r){return Fm(r)}function he(r){if(typeof r=="string"){let t=r in sR?sR[r]:r;if(t==="GlorotNormal")return new Wc;if(t==="GlorotUniform")return new Gc;if(t==="HeNormal")return new Uc;if(t==="HeUniform")return new Hc;if(t==="LeCunNormal")return new qc;if(t==="LeCunUniform")return new Kc;{let e={};return e.className=t,e.config={},iR(e)}}else return r instanceof wn?r:iR(r)}function Hy(r){return Array.isArray(r)&&Array.isArray(r[0])}function Hm(r){return r.length===0?[]:Array.isArray(r[0])?r:[r]}function St(r){let t;if(Array.isArray(r)){if(r.length!==1)throw new z(`Expected Tensor length to be 1; got ${r.length}`);t=r[0]}else t=r;return t}function Gt(r){if(Array.isArray(r)&&Array.isArray(r[0])){if(r.length===1)return r=r,r[0];throw new z(`Expected exactly 1 Shape; got ${r.length}`)}else return r}function qm(r){let t=0;for(let e of r)e.shape.length===0?t+=1:t+=e.shape.reduce((n,o)=>n*o);return t}var lR="Variable",Dh=class{constructor(t,e="float32",n=lR,o=!0,s=null){this.dtype=e==null?"float32":e,this.shape=t.shape,this.id=Ly(),n=n==null?lR:n,this.originalName=zy(n),this.name=By(this.originalName),this.trainable_=o,this.constraint=s,this.val=hy(t,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(t){return this.assertNotDisposed(),G7(this.val,t),this.val.id!==t.id&&(this.val.assign(t),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(t){this.trainable_=t,this.val.trainable=t}};function G7(r,t){if(r.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(r.shape)+" vs. "+JSON.stringify(t.shape))}function $h(r){return r.map(t=>t.read())}function Km(r){r.forEach(t=>{t[0].write(t[1])})}var Ie=class{constructor(t){this.dtype=t.dtype,this.shape=t.shape,t.shape!=null?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}},nn=class{constructor(t,e,n,o,s,i,a){this.dtype=t,this.shape=e,this.sourceLayer=n,this.inputs=o,this.callArgs=s,this.outputTensorIndex=a,this.id=Ly(),i!=null&&(this.originalName=zy(i),this.name=By(this.originalName)),this.rank=e.length}},W7=0,El=class{constructor(t,e){this.callArgs=e,this.id=W7++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(let n of t.inboundLayers)n!=null&&n.outboundNodes.push(this);t.outboundLayer.inboundNodes.push(this)}getConfig(){let t=[];for(let e of this.inboundLayers)e!=null?t.push(e.name):t.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},U7=0,_t=class extends J.Serializable{constructor(t={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=U7++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let e=t.name;if(!e){let n=this.getClassName();e=Do(n)+"_"+zu(n)}if(this.name=e,this.trainable_=t.trainable==null?!0:t.trainable,t.inputShape!=null||t.batchInputShape!=null){let n;if(t.batchInputShape!=null)n=t.batchInputShape;else if(t.inputShape!=null){let s=null;t.batchSize!=null&&(s=t.batchSize),n=[s].concat(t.inputShape)}this.batchInputShape=n;let o=t.dtype;o==null&&(o=t.inputDType),o==null&&(o="float32"),this.dtype=o}t.weights!=null?this.initialWeights=t.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(t,e){return t.name+"_ib-"+e.toString()}getNodeAtIndex(t,e){if(this.inboundNodes.length===0)throw new Xr(`The layer has never been called and thus has no defined ${e}.`);if(this.inboundNodes.length<=t)throw new z(`Asked to get ${e} at node ${t}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[t]}getInputAt(t){return Tr(this.getNodeAtIndex(t,"input").inputTensors)}getOutputAt(t){return Tr(this.getNodeAtIndex(t,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new En(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new En(`Layer ${this.name} is not connected, no input to return.`);return Tr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new En(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new En(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Tr(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(t=>t())}get updates(){return this._updates}get built(){return this._built}set built(t){this._built=t}get trainable(){return this.trainable_}set trainable(t){this._trainableWeights.forEach(e=>e.trainable=t),this.trainable_=t}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(t=>t.trainable):[]}set trainableWeights(t){this._trainableWeights=t}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(t=>!t.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(t){this._nonTrainableWeights=t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(t){if(t=we(t),this.inputSpec==null||this.inputSpec.length===0)return;let e=we(this.inputSpec);if(t.length!==e.length)throw new z(`Layer ${this.name} expects ${e.length} inputs, but it received ${t.length} input tensors. Input received: ${t}`);for(let n=0;n<t.length;n++){let o=t[n],s=e[n];if(s==null)continue;let i=o.rank;if(s.ndim!=null&&i!==s.ndim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${i}`);if(s.maxNDim!=null&&i>s.maxNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${i}`);if(s.minNDim!=null&&i<s.minNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${i}.`);if(s.dtype!=null&&o.dtype!==s.dtype)throw new z(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${o.dtype}.`);if(s.axes){let a=o.shape;for(let u in s.axes){let l=Number(u),c=s.axes[u],p=l>=0?a[l]:a[a.length+l];if(c!=null&&[c,null].indexOf(p)===-1)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${a}.`)}}if(s.shape!=null)for(let a=0;a<s.shape.length;++a){let u=s.shape[a],l=o.shape[a];if(u!=null&&l!=null&&u!==l)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${o.shape}.`)}}}call(t,e){return t}invokeCallHook(t,e){this._callHook!=null&&this._callHook(t,e)}setCallHook(t){this._callHook=t}clearCallHook(){this._callHook=null}apply(t,e){e=e||{},this.assertNotDisposed();let n=we(t),o=!0;for(let i of n)if(!(i instanceof nn)){o=!1;break}let s=!0;for(let i of n)if(i instanceof nn){s=!1;break}if(o===s)throw new z("Arguments to apply() must be all SymbolicTensors or all Tensors");return hi(this.name,()=>{if(!this.built){this.assertInputCompatibility(t);let i=[];for(let a of we(t))i.push(a.shape);this.build(Tr(i)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(t),s){let i=this.call(t,e),a=we(i),u=[];for(let l of a)n.indexOf(l)!==-1&&(l=l.clone()),u.push(l);if(i=Tr(u),this.activityRegularizer!=null)throw new kt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}else{let i=H7(t),a=this.computeOutputShape(i),u,l=q7(t);if(this.warnOnIncompatibleInputShape(Array.isArray(t)?i[0]:i),a!=null&&a.length>0&&Array.isArray(a[0])?u=a.map((c,p)=>new nn(l,c,this,we(t),e,this.name,p)):u=new nn(l,a,this,we(t),e,this.name),this.addInboundNode(t,u,null,null,i,a,e),this._refCount++,this.activityRegularizer!=null)throw new kt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return u}})}warnOnIncompatibleInputShape(t){if(this.batchInputShape!=null)if(t.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(t)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let e=!1;this.batchInputShape.forEach((n,o)=>{n!=null&&t[o]!=null&&t[o]!==n&&(e=!0)}),e&&console.warn(`The shape of the input tensor (${JSON.stringify(t)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new En(`The layer ${this.name} has never been called and thus has no defined output shape.`);let t=[];for(let e of this.inboundNodes){let n=JSON.stringify(e.outputShapes);t.indexOf(n)===-1&&t.push(n)}if(t.length===1){let e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&e.length===1?e[0]:e}else throw new En(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Xr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return qm(this.weights)}build(t){this.built=!0}getWeights(t=!1){return $h(t?this.trainableWeights:this.weights)}setWeights(t){B(()=>{let e=this.weights;if(e.length!==t.length)throw new z(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${t.length}, but the layer was expecting ${e.length} weights. Provided weights: ${t}...`);if(e.length===0)return;let n=[],o=$h(e);for(let s=0;s<o.length;++s){let i=o[s],a=e[s],u=t[s];if(!y.arraysEqual(i.shape,u.shape))throw new z(`Layer weight shape ${i.shape} not compatible with provided weight shape ${u.shape}`);n.push([a,u])}Km(n)})}addWeight(t,e,n,o,s,i,a,u){if(this._addedWeightNames.indexOf(t)!==-1)throw new z(`Duplicate weight name ${t} for layer ${this.name}`);this._addedWeightNames.push(t),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(o=u!=null?u():he("zeros"));let l=o.apply(e,n),c=new Dh(l,n,t,i,a);return l.dispose(),s!=null&&this.addLoss(()=>s.apply(c.read())),i==null&&(i=!0),i?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(t){this.fastWeightInitDuringBuild=t}addLoss(t){t==null||Array.isArray(t)&&t.length===0||(t=we(t),this._losses!==void 0&&this._losses!==null&&this.losses.push(...t))}computeOutputShape(t){return t}computeMask(t,e){if(!this.supportsMasking){if(e!=null)if(Array.isArray(e))e.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return e}addInboundNode(t,e,n,o,s,i,a=null){let u=we(t);e=we(e),n=we(n),o=we(o),s=Hm(s),i=Hm(i);let l=[],c=[],p=[];for(let m of u)l.push(m.sourceLayer),c.push(m.nodeIndex),p.push(m.tensorIndex);new El({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:p,inputTensors:u,outputTensors:e,inputMasks:n,outputMasks:o,inputShapes:s,outputShapes:i},a);for(let m=0;m<e.length;m++)e[m].sourceLayer=this,e[m].nodeIndex=this.inboundNodes.length-1,e[m].tensorIndex=m}getConfig(){let t={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(t.batchInputShape=this.batchInputShape),this.dtype!=null&&(t.dtype=this.dtype),t}disposeWeights(){return this.weights.forEach(t=>t.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let t=0;return--this._refCount===0&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}}};function H7(r){r=we(r);let t=[];for(let e of r)t.push(e.shape);return Tr(t)}function q7(r){return"float32"}function LN(r,t,e){if((t==null||e!=null&&e>0)&&(t=r.sourceLayer,e=r.nodeIndex),t.inboundNodes.length===0)return[r];{let n=t.inboundNodes[e];if(n.inboundLayers.length===0)return n.inputTensors;{let o=[];for(let s=0;s<n.inboundLayers.length;s++){let i=n.inputTensors[s],a=n.inboundLayers[s],u=n.nodeIndices[s],l=LN(i,a,u);for(let c of l)o.indexOf(c)===-1&&o.push(c)}return o}}}var xi=class extends _t{constructor(t){if(super({dtype:t.dtype,name:t.name!=null?t.name:zu("input").toString()}),t.batchSize==null&&(t.batchSize=null),t.sparse==null&&(t.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=t.sparse,t.inputShape!=null&&t.batchInputShape!=null)throw new z("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let e=t.batchInputShape;if(e==null){if(t.inputShape==null)throw new z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");e=[t.batchSize].concat(t.inputShape)}else if(t.batchSize!=null)throw new z("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=t.dtype||"float32";this.batchInputShape=e,this.dtype=n,this.inputSpec=[{shape:e}];let o=new nn(this.dtype,this.batchInputShape,this,[],{},this.name);o.nodeIndex=0,o.tensorIndex=0,new El({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[o],outputTensors:[o],inputMasks:[null],outputMasks:[null],inputShapes:[e],outputShapes:[e]})}apply(t,e){throw new z(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}};xi.className="InputLayer";J.registerClass(xi);function qy(r){if(r.batchShape==null&&r.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(r.batchShape!=null&&r.shape!=null)throw new z("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=r.batchShape;r.shape!=null&&t==null&&(t=[null].concat(r.shape));let e=r.dtype;return e==null&&(e="float32"),new xi({batchInputShape:t,name:r.name,dtype:e,sparse:r.sparse}).inboundNodes[0].outputTensors[0]}function K7(r,t){if(r.dtype==null||r.dtype===t.dtype)return t;try{return Q(t,r.dtype)}catch(e){throw new z(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${r.name}' (${r.dtype}).`)}}var Oo=class{constructor(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof Oo)for(let e in t.id2Value)this.id2Value[e]=t.id2Value[e],e in t.id2Mask&&(this.id2Mask[e]=t.id2Mask[e]);else{if(t==null)return;for(let e of t)this.add(e.key,e.value)}}add(t,e,n){if(this.id2Value[t.id]==null)this.id2Value[t.id]=K7(t,e),this.name2Id[t.name]=t.id,n!=null&&(this.id2Mask[t.id]=n);else throw new z(`Duplicate key: name=${t.name}, id=${t.id}`);return this}addFeed(t){this.add(t.key,t.value)}hasKey(t){return this.id2Value[t.id]!=null}names(){return Object.keys(this.name2Id)}getValue(t){if(t instanceof nn){if(this.id2Value[t.id]==null)throw new z(`Nonexistent key: ${t.name}`);return this.id2Value[t.id]}else{let e=this.name2Id[t];if(e==null)throw new z(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Value[e]}}getMask(t){if(t instanceof nn){if(this.id2Value[t.id]==null)throw new z(`Nonexistent key: ${t.name}`);return this.id2Mask[t.id]}else{let e=this.name2Id[t];if(e==null)throw new z(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Mask[e]}}disposeMasks(){this.id2Mask!=null&&Tt(this.id2Mask)}},Ky=new Th,jy=new Th;function cR(r){Ky!=null&&Ky.setMaxEntries(r),jy!=null&&jy.setMaxEntries(r)}function jc(r,t,e,n){let o=e==null?!1:e.training,s=Array.isArray(r),i=s?r:[r],a=i.map(d=>d.name),u=[],l=t.names();for(let d of a)l.indexOf(d)!==-1?u.push(t.getValue(d)):u.push(null);n!=null&&(n.maxNumTensors=-1/0,n.minNumTensors=1/0);let c=a.join(",")+"|"+t.names().sort().join(","),p=Ky.get(c),m;if(p==null){let d=j7(i,t);p=d.sorted,m=d.recipientCounts,Ky.put(c,p),jy.put(c,m)}m={},o||Object.assign(m,jy.get(c));let f=new Oo(t);for(let d=0;d<p.length;++d){if(n!=null){let F=fh().numTensors;F>n.maxNumTensors&&(n.maxNumTensors=F),F<n.minNumTensors&&(n.minNumTensors=F)}let h=p[d],g=h.sourceLayer;if(g instanceof xi)continue;let x=[],b=[],w=[],I=!1;for(let F of h.inputs){let P=f.getValue(F),V=f.getMask(F);x.push(P),b.push(V),V!=null&&(I=!0),o||(m[F.name]--,m[F.name]===0&&!t.hasKey(F)&&a.indexOf(F.name)===-1&&!P.isDisposed&&F.sourceLayer.stateful!==!0&&w.push(P))}I&&(e=e||{},e.mask=b[0]);let N=we(g.apply(x,e)),E=null;g.supportsMasking&&(E=g.computeMask(x,b));let A=Y7(h),D=Array.isArray(A)?A:[A];for(let F=0;F<D.length;++F){f.hasKey(D[F])||f.add(D[F],N[F],Array.isArray(E)?E[0]:E);let P=a.indexOf(D[F].name);P!==-1&&(u[P]=N[F])}o||Tt(w)}return f.disposeMasks(),s?u:u[0]}function j7(r,t){y.assert(r!=null&&r.length>0,()=>"Expected at least one fetch, got none");let e=[],n={};if(r.length===1){let o=uR(r[0],t);e=o.sorted,n=o.recipientMap}else{let o=new Set;for(let s of r){let{sorted:i,recipientMap:a}=uR(s,t);for(let u of i)o.has(u.name)||(e.push(u),o.add(u.name));for(let u in a)n[u]==null&&(n[u]=new Set),a[u].forEach(l=>n[u].add(l))}}return{sorted:e,recipientCounts:X7(n)}}function X7(r){let t={};for(let e in r)t[e]=r[e].size;return t}function uR(r,t){let e=new Set,n=[],o={};for(let a of t.names())e.add(a);let s=[],i=[];for(s.push(r);s.length>0;){let a=s[s.length-1];if(e.has(a.name)){s.pop();continue}let u=i[i.length-1]===s.length-1;if(a.inputs.length===0||u)s.pop(),n.push(a),e.add(a.name),u&&i.pop();else{i.push(s.length-1);for(let l of a.inputs)o[l.name]==null&&(o[l.name]=new Set),o[l.name].add(a.name),!e.has(l.name)&&s.push(l)}}return{sorted:n,recipientMap:o}}function Y7(r){let t;if(r.sourceLayer.inboundNodes.length===1)t=r.sourceLayer.output;else{let e=null;for(let n=0;n<r.sourceLayer.inboundNodes.length;++n)for(let o of r.sourceLayer.inboundNodes[n].outputTensors)if(o.id===r.id){e=n;break}t=r.sourceLayer.getOutputAt(e)}return t}var Z7=L();Z7.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,cR);var fR={};Kt(fR,{maxNorm:()=>J7,minMaxNorm:()=>eZ,nonNeg:()=>tZ,unitNorm:()=>Q7});function zN(r,t){return B(()=>Ne(pt($(r,r),t,!0)))}var Xc=class extends J.Serializable{getConfig(){return{}}},jm=class extends Xc{constructor(t){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return B(()=>{let e=zN(t,this.axis),n=Sr(e,0,this.maxValue);return $(t,ct(n,Y(cr(),e)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};jm.className="MaxNorm";J.registerClass(jm);var Xm=class extends Xc{constructor(t){super(),this.defaultAxis=0,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return B(()=>ct(t,Y(cr(),zN(t,this.axis))))}getConfig(){return{axis:this.axis}}};Xm.className="UnitNorm";J.registerClass(Xm);var Ym=class extends Xc{apply(t){return Mr(t)}};Ym.className="NonNeg";J.registerClass(Ym);var Zm=class extends Xc{constructor(t){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=t.minValue!=null?t.minValue:this.defaultMinValue,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.rate=t.rate!=null?t.rate:this.defaultRate,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return B(()=>{let e=zN(t,this.axis),n=Y($(this.rate,Sr(e,this.minValue,this.maxValue)),$(1-this.rate,e));return $(t,ct(n,Y(cr(),e)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};Zm.className="MinMaxNorm";J.registerClass(Zm);var pR={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Be(r){return Fm(r)}function mR(r,t={}){return xa(r,J.SerializationMap.getMap().classNameMap,t,"constraint")}function Ve(r){if(r==null)return null;if(typeof r=="string"){let e={className:r in pR?pR[r]:r,config:{}};return mR(e)}else return r instanceof Xc?r:mR(r)}function J7(r){return new jm(r)}function Q7(r){return new Xm(r)}function tZ(){return new Ym}function eZ(r){return new Zm(r)}var dR={};Kt(dR,{constant:()=>oZ,glorotNormal:()=>pZ,glorotUniform:()=>cZ,heNormal:()=>mZ,heUniform:()=>fZ,identity:()=>lZ,leCunNormal:()=>dZ,leCunUniform:()=>hZ,ones:()=>nZ,orthogonal:()=>gZ,randomNormal:()=>iZ,randomUniform:()=>sZ,truncatedNormal:()=>aZ,varianceScaling:()=>uZ,zeros:()=>rZ});function rZ(){return new Lm}function nZ(){return new Vu}function oZ(r){return new zm(r)}function sZ(r){return new Bm(r)}function iZ(r){return new Vm(r)}function aZ(r){return new Gm(r)}function lZ(r){return new Wm(r)}function uZ(r){return new Yr(r)}function cZ(r){return new Gc(r)}function pZ(r){return new Wc(r)}function mZ(r){return new Uc(r)}function fZ(r){return new Hc(r)}function dZ(r){return new qc(r)}function hZ(r){return new Kc(r)}function gZ(r){return new Um(r)}var jR={};Kt(jR,{Layer:()=>_t,RNN:()=>Dn,RNNCell:()=>Rl,activation:()=>FJ,add:()=>WJ,alphaDropout:()=>k9,average:()=>UJ,averagePooling1d:()=>QN,averagePooling2d:()=>tk,averagePooling3d:()=>ek,avgPool1d:()=>QJ,avgPool2d:()=>e9,avgPool3d:()=>n9,avgPooling1d:()=>t9,avgPooling2d:()=>r9,avgPooling3d:()=>o9,batchNormalization:()=>YJ,bidirectional:()=>y9,categoryEncoding:()=>D9,centerCrop:()=>E9,concatenate:()=>HJ,conv1d:()=>NJ,conv2d:()=>kJ,conv2dTranspose:()=>TJ,conv3d:()=>_J,conv3dTranspose:()=>EJ,convLstm2d:()=>d9,convLstm2dCell:()=>h9,cropping2D:()=>DJ,dense:()=>OJ,depthwiseConv2d:()=>RJ,dot:()=>XJ,dropout:()=>PJ,elu:()=>bJ,embedding:()=>GJ,flatten:()=>LJ,gaussianDropout:()=>N9,gaussianNoise:()=>S9,globalAveragePooling1d:()=>s9,globalAveragePooling2d:()=>i9,globalMaxPool1d:()=>w9,globalMaxPool2d:()=>I9,globalMaxPooling1d:()=>UR,globalMaxPooling2d:()=>HR,gru:()=>l9,gruCell:()=>u9,input:()=>KN,inputLayer:()=>yJ,layerNormalization:()=>ZJ,leakyReLU:()=>IJ,lstm:()=>c9,lstmCell:()=>p9,masking:()=>T9,maxPool1d:()=>C9,maxPool2d:()=>v9,maxPooling1d:()=>qR,maxPooling2d:()=>KR,maxPooling3d:()=>a9,maximum:()=>qJ,minimum:()=>KJ,multiply:()=>jJ,permute:()=>VJ,prelu:()=>CJ,randomWidth:()=>$9,reLU:()=>wJ,repeatVector:()=>zJ,rescaling:()=>_9,reshape:()=>BJ,resizing:()=>A9,rnn:()=>g9,separableConv2d:()=>AJ,simpleRNN:()=>m9,simpleRNNCell:()=>f9,softmax:()=>vJ,spatialDropout1d:()=>MJ,stackedRNNCells:()=>x9,thresholdedReLU:()=>SJ,timeDistributed:()=>b9,upSampling2d:()=>$J,zeroPadding2d:()=>JJ});async function ba(r){if(r==null)return;let t=[],e=[],n=[];for(let o in r){let s=r[o];if(typeof s!="number"){let i=s;t.push(i.data()),e.push(o),n.push(i)}}if(t.length>0){let o=await Promise.all(t);for(let s=0;s<o.length;++s)r[e[s]]=o[s][0];Tt(n)}}function Xy(r){if(r!=null)for(let t in r){let e=r[t];typeof e!="number"&&e.dispose()}}var hR;(function(r){r[r.SILENT=0]="SILENT",r[r.VERBOSE=1]="VERBOSE"})(hR||(hR={}));var xZ=125,Al=class{constructor(){this.validationData=null}setParams(t){this.params=t}async onEpochBegin(t,e){}async onEpochEnd(t,e){}async onBatchBegin(t,e){}async onBatchEnd(t,e){}async onTrainBegin(t){}async onTrainEnd(t){}setModel(t){}},Yy=class{constructor(t,e=10){t==null&&(t=[]),this.callbacks=t,this.queueLength=e}append(t){this.callbacks.push(t)}setParams(t){for(let e of this.callbacks)e.setParams(t)}setModel(t){for(let e of this.callbacks)e.setModel(t)}async onEpochBegin(t,e){e==null&&(e={});for(let n of this.callbacks)await n.onEpochBegin(t,e)}async onEpochEnd(t,e){e==null&&(e={});for(let n of this.callbacks)await n.onEpochEnd(t,e)}async onBatchBegin(t,e){e==null&&(e={});for(let n of this.callbacks)await n.onBatchBegin(t,e)}async onBatchEnd(t,e){e==null&&(e={});for(let n of this.callbacks)await n.onBatchEnd(t,e)}async onTrainBegin(t){t==null&&(t={});for(let e of this.callbacks)await e.onTrainBegin(t)}async onTrainEnd(t){t==null&&(t={});for(let e of this.callbacks)await e.onTrainEnd(t)}},BN=class extends Al{constructor(){super()}async onEpochBegin(t){this.seen=0,this.totals={}}async onBatchEnd(t,e){e==null&&(e={});let n=e.size==null?0:e.size;this.seen+=n;for(let o in e){let s=e[o];if(typeof s=="number")this.totals.hasOwnProperty(o)||(this.totals[o]=0),this.totals[o]=this.totals[o]+s*n;else{let i;o in this.totals?i=this.totals[o]:this.totals[o]=0;let a=B(()=>Y(this.totals[o],$(s,n)));this.totals[o]=a,i!=null&&i.dispose()}}}async onEpochEnd(t,e){if(e!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?e[n]=this.totals[n]/this.seen:B(()=>{let o=$(ct(1,this.seen),this.totals[n]);e[n]=o,this.totals[n].dispose(),$e(e[n])}))}},Zy=class extends Al{async onTrainBegin(t){this.epoch=[],this.history={}}async onEpochEnd(t,e){e==null&&(e={}),this.epoch.push(t);for(let n in e)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(e[n])}async syncData(){let t=[],e=[],n=[];for(let s in this.history){let i=this.history[s];for(let a=0;a<i.length;++a)if(typeof i[a]!="number"){let u=i[a];t.push(u.data()),e.push(s),n.push(a)}}let o=await Promise.all(t);for(let s=0;s<o.length;++s)this.history[e[s]][n[s]].dispose(),this.history[e[s]][n[s]]=o[s][0]}},Jy=class extends Al{constructor(t,e){if(super(),this.currentEpoch=0,this.nowFunc=t.nowFunc,this.nextFrameFunc=t.nextFrameFunc||kh,this.yieldEvery=e||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=xZ),this.yieldEvery==="never"&&t.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");y.isNumber(this.yieldEvery)&&(this.maybeWait=V$(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=t.onTrainBegin,this.trainEnd=t.onTrainEnd,this.epochBegin=t.onEpochBegin,this.epochEnd=t.onEpochEnd,this.batchBegin=t.onBatchBegin,this.batchEnd=t.onBatchEnd,this.yield=t.onYield}async maybeWait(t,e,n){let o=[];this.yield!=null&&(await ba(n),o.push(this.yield(t,e,n))),o.push(this.nextFrameFunc()),await Promise.all(o)}async onEpochBegin(t,e){this.currentEpoch=t,this.epochBegin!=null&&(await ba(e),await this.epochBegin(t,e))}async onEpochEnd(t,e){let n=[];this.epochEnd!=null&&(await ba(e),n.push(this.epochEnd(t,e))),this.yieldEvery==="epoch"&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(t,e){this.batchBegin!=null&&(await ba(e),await this.batchBegin(t,e))}async onBatchEnd(t,e){let n=[];this.batchEnd!=null&&(await ba(e),n.push(this.batchEnd(t,e))),this.yieldEvery==="batch"?n.push(this.nextFrameFunc()):y.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,t,e)),await Promise.all(n)}async onTrainBegin(t){this.trainBegin!=null&&(await ba(t),await this.trainBegin(t))}async onTrainEnd(t){this.trainEnd!=null&&(await ba(t),await this.trainEnd(t))}};function Qy(r,t){return r==null&&(r={}),r instanceof Al?[r]:Array.isArray(r)&&r[0]instanceof Al?r:we(r).map(n=>new Jy(n,t))}var In=class{constructor(){}static registerCallbackConstructor(t,e){y.assert(t>=0&&Number.isInteger(t),()=>`Verbosity level is expected to be an integer >= 0, but got ${t}`),In.checkForDuplicate(e),In.constructors[t]==null&&(In.constructors[t]=[]),In.constructors[t].push(e)}static checkForDuplicate(t){for(let e in In.constructors)In.constructors[+e].forEach(o=>{if(o===t)throw new z("Duplicate callback constructor.")})}static clear(){In.constructors={}}static createCallbacks(t){let e=[];for(let n in In.constructors){let o=+n;t>=o&&e.push(...In.constructors[o])}return e.map(n=>new n)}};In.constructors={};function tb(r,t,e,n,o,s,i,a,u){let l=new Zy,c=[new BN,...In.createCallbacks(t)];r!=null&&c.push(...r),c.push(l);let p=new Yy(c);return p.setParams({epochs:e,initialEpoch:n,samples:o,steps:s,batchSize:i,verbose:t,doValidation:a,metrics:u}),{callbackList:p,history:l}}function Cn(r,t={},e=!1){return xa(r,J.SerializationMap.getMap().classNameMap,t,"layer",e)}function Rh(r,t){return B(()=>{r.dtype!=="float32"&&(r=Q(r,"float32"));let e=pt(Vc(r),t,!0),n=No(e.shape,cr()),o=Ne(_n(e,n));return ct(r,o)})}function wa(r,t){return B(()=>ke(Vc(lt(t,r)),-1))}function Jm(r,t){return B(()=>ke(Ee(lt(t,r)),-1))}function Gu(r,t){return B(()=>{let e=lt(r,t),n=Sr(Ee(r),cr(),Number.MAX_VALUE),o=Ee(ct(e,n));return $(100,ke(o,-1))})}function yZ(r,t){return B(()=>{let e=Sr(t,cr(),Number.MAX_VALUE),n=kr(Y(1,e)),o=Sr(r,cr(),Number.MAX_VALUE),s=kr(Y(1,o));return ke(Vc(lt(n,s)),-1)})}function bZ(r,t){return B(()=>{let e=_n(0,lt(1,$(r,t)));return ke(Vc(e),-1)})}function wZ(r,t){return B(()=>{let e=_n(0,lt(1,$(r,t)));return ke(e,-1)})}function IZ(r,t){return B(()=>{let e=pt($(r,t),-1),n=Nr($(lt(1,r),t),-1);return _n(0,Y(1,lt(n,e)))})}function CZ(r,t){return B(()=>{let e=Math.log(2),n=lt(t,r),o=lt(Y(n,pi($(-2,n))),e);return ke(o,-1)})}function Yc(r,t,e=!1){return B(()=>{if(e)t=Fu(t);else{let n=pt(t,t.shape.length-1,!0);t=ct(t,n)}return t=Sr(t,cr(),1-cr()),Ut(pt($(Q(r,"float32"),kr(t)),t.shape.length-1))})}function Qm(r,t,e=!1){return B(()=>{let n=Q(pa(J$(r)),"int32");t=Sr(t,cr(),1-cr());let o=t.shape,s=R(fa(n,o[o.length-1]),o);return Yc(s,t,e)})}function vZ(r,t){if(!y.arraysEqual(r.shape,t.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(t.shape)}`);return B(()=>{let e=Mr(t),n=Ut(Ee(t));return Y(lt(e,$(t,r)),Eu(ir(n)))})}function tf(r,t){return B(()=>{let e;return e=Sr(t,cr(),1-cr()),e=kr(ct(e,lt(1,e))),ke(vZ(r,e),-1)})}function SZ(r,t){return B(()=>{let e=Sr(r,cr(),1),n=Sr(t,cr(),1);return pt($(r,kr(ct(e,n))),-1)})}function NZ(r,t){return B(()=>{let e=kr(Y(cr(),t));return ke(lt(t,$(r,e)),-1)})}function Oh(r,t){return B(()=>{let e=Rh(r,-1),n=Rh(t,-1),o=$(e,n);return Ut(pt(o,-1))})}var Fh={meanSquaredError:wa,meanAbsoluteError:Jm,meanAbsolutePercentageError:Gu,meanSquaredLogarithmicError:yZ,squaredHinge:bZ,hinge:wZ,categoricalHinge:IZ,logcosh:CZ,categoricalCrossentropy:Yc,sparseCategoricalCrossentropy:Qm,binaryCrossentropy:tf,kullbackLeiblerDivergence:SZ,poisson:NZ,cosineProximity:Oh};function eb(r){if(typeof r=="string"){if(r in Fh)return Fh[r];let t=`Unknown loss ${r}`;throw r.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${r}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new z(t)}else return r}function Ph(r,t){return B(()=>{let e=$(.5,Ir(t)),n=rn(Fe(t,e),r.dtype);return ke(Fr(r,n),-1)})}function Mh(r,t){return B(()=>rn(Fr(oa(r,-1),oa(t,-1)),"float32"))}function xR(r,t){return B(()=>Q(pt(Pr(Fr(r,1),Fr(t,1))),"float32"))}function kZ(r,t){return B(()=>Q(pt(Pr(Fr(r,1),Fr(t,0))),"float32"))}function TZ(r,t){return B(()=>Q(pt(Pr(Fr(r,0),Fr(t,1))),"float32"))}function VN(r,t){return B(()=>{let e=xR(r,t),n=TZ(r,t),o=Y(e,n);return Q(be(Fe(o,0),ct(e,o),0),"float32")})}function yR(r,t){return B(()=>{let e=xR(r,t),n=kZ(r,t),o=Y(e,n);return Q(be(Fe(o,0),ct(e,o),0),"float32")})}function nb(r,t){return tf(r,t)}function ob(r,t){return r.rank===t.rank&&(r=qn(r,[r.rank-1])),t=oa(t,-1),t.dtype!==r.dtype&&(t=Q(t,r.dtype)),Q(Fr(r,t),"float32")}var _Z=wa,EZ=wa,AZ=Jm,DZ=Jm,$Z=Gu,RZ=Gu,Lh=Yc,FZ=Oh,GN=Qm,rb={binaryAccuracy:Ph,categoricalAccuracy:Mh,precision:VN,categoricalCrossentropy:Lh,sparseCategoricalCrossentropy:GN,mse:_Z,MSE:EZ,mae:AZ,MAE:DZ,mape:$Z,MAPE:RZ,cosine:FZ};function bR(r){if(typeof r=="string"&&r in rb)return rb[r];if(typeof r!="string"&&r!=null)return r;throw new z(`Unknown metric ${r}`)}function zh(r){if(fo(r!==null,`Unknown LossOrMetricFn ${r}`),typeof r=="string")return r;{let t;for(let e of Object.keys(Fh))if(Fh[e]===r){t=e;break}if(t!==void 0)return t;for(let e of Object.keys(rb))if(rb[e]===r){t=e;break}return t!==void 0?t:r.name}}function IR(r){let t={Adagrad:()=>zc.adagrad(.01),Adadelta:()=>zc.adadelta(1,.95,cr()),Adam:()=>zc.adam(.001,.9,.999,cr()),Adamax:()=>zc.adamax(.002,.9,.999,cr(),0),RMSProp:()=>zc.rmsprop(.001,.9,0,cr()),SGD:()=>zc.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,r in t)return t[r]();throw new z(`Unknown Optimizer ${r}`)}function UN(r,t,e=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!WN(r))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(e){let n=JSON.stringify(r);n.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function WN(r){if(r===null)return!0;if(typeof r=="object")if(Object.getPrototypeOf(r)===Object.prototype){let t=Object.keys(r);for(let e of t)if(typeof e!="string"||!WN(r[e]))return!1;return!0}else if(Array.isArray(r)){for(let t of r)if(!WN(t))return!1;return!0}else return!1;else{let t=typeof r;return t==="string"||t==="number"||t==="boolean"}}function CR(r,t,e,n=console.log){let o=MZ(r),s=["Layer (type)","Input Shape","Output shape","Param #"];o?(t=t||90,e=e||[.32,.61,.89,1]):(t=t||115,e=e||[.24,.48,.7,.8,1]),e[e.length-1]<=1&&(e=e.map(c=>Math.floor(t*c)));let i;if(!o){s.push("Receives inputs"),i=[];for(let c in r.nodesByDepth)i.push(...r.nodesByDepth[c])}n("_".repeat(t)),sb(s,e,n),n("=".repeat(t));let a=r.layers;for(let c=0;c<a.length;++c)o?LZ(a[c],e,n):zZ(a[c],e,i,n),n((c===a.length-1?"=":"_").repeat(t));r.checkTrainableWeightsConsistency();let u=PZ(r),l=qm(r.nonTrainableWeights);n(`Total params: ${u+l}`),n(`Trainable params: ${u}`),n(`Non-trainable params: ${l}`),n("_".repeat(t))}function PZ(r){let t;return r.collectedTrainableWeights!=null?t=qm(r.collectedTrainableWeights):t=qm(r.trainableWeights),t}function MZ(r){let t=!0,e=[],n=[];for(let o in r.nodesByDepth)e.push(r.nodesByDepth[o]);for(let o of e){if(o.length>1||o.length===1&&o[0].inboundLayers.length>1){t=!1;break}n.push(...o)}if(t)for(let o of r.layers){let s=!1;for(let i of o.inboundNodes)if(n.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function sb(r,t,e=console.log){let n="";for(let o=0;o<r.length;++o)o>0&&(n=n.slice(0,n.length-1)+" "),n+=r[o],n=n.slice(0,t[o]),n+=" ".repeat(t[o]-n.length);e(n)}function LZ(r,t,e){let n,o;try{o=r.inboundNodes.map(u=>JSON.stringify(u.inputShapes)).join(",")}catch(u){o="multiple"}try{n=JSON.stringify(r.outputShape)}catch(u){n="multiple"}let s=r.name,i=r.getClassName(),a=[`${s} (${i})`,o,n,r.countParams().toString()];sb(a,t,e)}function zZ(r,t,e,n){let o,s;try{s=r.inboundNodes.map(p=>JSON.stringify(p.inputShapes)).join(",")}catch(p){s="multiple"}try{o=JSON.stringify(r.outputShape)}catch(p){o="multiple"}let i=[];for(let p of r.inboundNodes)if(!(e!=null&&e.length>0&&e.indexOf(p)===-1))for(let m=0;m<p.inboundLayers.length;++m){let f=p.inboundLayers[m].name,d=p.nodeIndices[m],h=p.tensorIndices[m];i.push(`${f}[${d}][${h}]`)}let a=r.name,u=r.getClassName(),l=i.length===0?"":i[0],c=[`${a} (${u})`,s,o,r.countParams().toString(),l];sb(c,t,n);for(let p=1;p<i.length;++p)sb(["","","","",i[p]],t,n)}function vR(r,t,e){return(r==="inboundNodes"||r==="outputLayers"||r==="inputLayers")&&t===0&&typeof e=="string"}function Zc(r,t){if(r===null)return null;if(typeof r=="string")return kl(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let e=[],n=r.length;for(let o=0;o<n;++o){let s=r[o];vR(t,o,s)?e.push(s):e.push(Zc(s,t))}return e}else{let e={};for(let n of Object.keys(r)){let o=r[n];if(n==="name"&&typeof o=="string")e[n]=o;else{let s=kl(n);e[s]=Zc(o,s)}}return e}}function ib(r,t){if(r==null)return null;if(typeof r=="string")return Do(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let e=[],n=r.length;for(let o=0;o<n;++o){let s=r[o];vR(t,o,s)?e.push(s):e.push(ib(s,t))}return e}else{let e={};for(let n of Object.keys(r)){let o=r[n],s=Do(n);(n==="name"||n==="className")&&typeof o=="string"?e[s]=o:e[s]=ib(o,n)}return e}}var ef="4.7.0";var Kn=class extends _t{constructor(t){if(super({}),this.containerNodes=new Set,this.name=t.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=zu(b)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(t.inputs)?this.inputs=t.inputs.slice():this.inputs=[t.inputs],Array.isArray(t.outputs)?this.outputs=t.outputs.slice():this.outputs=[t.outputs],$o(this.inputs).length!==this.inputs.length)throw new z(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);$o(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(b=>b.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let b of this.outputs){let w=b.sourceLayer,I=b.nodeIndex,N=b.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(I),this.outputLayersTensorIndices.push(N)}for(let b of this.inputs){let w=b.sourceLayer,I=b.nodeIndex,N=b.tensorIndex;fo(I===0,"input layer has >1 nodes"),fo(N===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(I),this.inputLayersTensorIndices.push(N)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let w=this.inputLayers[b];if(!(w instanceof xi))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${t.inputs}. Input ${b} (0-based) originates from layer type ${w.getClassName()}.`);this.inputNames.push(w.name),this.feedInputShapes.push(w.batchInputShape),this.feedInputNames.push(w.name)}for(let b of this.outputLayers)this.outputNames.push(b.name);this.internalInputShapes=this.inputs.map(b=>b.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);let e={},n={},o={},s={},i={},a=[],u=(b,w,I,N,E,A)=>{(N==null||E==null||A==null)&&(N=b.sourceLayer,E=b.nodeIndex,A=b.tensorIndex);let D=N.inboundNodes[E];if(I.indexOf(D)!==-1)throw new Xr(`The tensor ${b.name} at layer "${N.name}" is part of a cycle.`);if(w.indexOf(D)!==-1)return;this.containerNodes.add(Kn.nodeKey(N,E)),N.id in i||(i[N.id]=Object.keys(i).length),I.indexOf(D)===-1&&I.push(D);let F=D.inboundLayers.length;for(let P=0;P<F;P++){let V=D.inputTensors[P],G=D.inboundLayers[P],W=D.nodeIndices[P],q=D.tensorIndices[P];u(V,w,I,G,W,q)}for(w.push(D);I.indexOf(D)>=0;)I.splice(I.indexOf(D),1);a.push(D)},l=[],c=[];for(let b of this.outputs)u(b,l,c);let p=a.slice().reverse();for(let b of p){n[b.id]=b,b.id in e||(e[b.id]=0);let w=e[b.id],I=o[b.outboundLayer.id]==null?0:o[b.outboundLayer.id];w=Math.max(w,I),o[b.outboundLayer.id]=w,s[b.outboundLayer.id]=b.outboundLayer,e[b.id]=w;for(let N=0;N<b.inboundLayers.length;N++){let E=b.inboundLayers[N],A=b.nodeIndices[N],D=E.inboundNodes[A],F=e[D.id]==null?0:e[D.id];e[D.id]=Math.max(w+1,F),n[D.id]=D}}let m={};for(let b in e){let w=e[b];w in m||(m[w]=[]),m[w].push(n[b])}let f={};for(let b in o){let w=o[b];w in f||(f[w]=[]),f[w].push(s[b])}let d=Object.keys(f).map(b=>parseInt(b,10)).sort(_h);this.layers=[];for(let b of d){let w=f[b];w.sort((I,N)=>{let E=i[I.id],A=i[N.id];return E<A?-1:E>A?1:0});for(let I of w)I instanceof Kn&&this.internalContainerRefs.push(I),this.layers.push(I)}this.layersByDepth=f,d=Object.keys(m).map(b=>parseInt(b,10)).sort(_h);let h=this.inputs.slice(),g=[];for(let b of d)for(let w of m[b]){let I=w.outboundLayer;if(I!=null){for(let N of w.inputTensors)if(h.indexOf(N)===-1)throw new Xr(`Graph disconnected: cannot obtain value for tensor ${N} at layer "${I.name}". The following previous layers were accessed without issue: ${g}`);for(let N of w.outputTensors)h.push(N);g.push(I.name)}}this.nodesByDepth=m;let x=this.layers.map(b=>b.name);for(let b of x){let w=x.filter(I=>I===b).length;if(w!==1)throw new Xr(`The name "${b}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(x))}this.outboundNodes=[],this.inboundNodes=[],new El({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(b=>null),outputMasks:this.outputs.map(b=>null),inputShapes:this.inputs.map(b=>b.shape),outputShapes:this.outputs.map(b=>b.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let t={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let e of this.layers)t.numDisposedVariables+=e.dispose().numDisposedVariables;for(let e of this.internalContainerRefs)t.numDisposedVariables+=e.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach(e=>{e._trainableWeights.forEach(n=>n.trainable=t)}),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new z("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let t=[];for(let e of this.layers)t=t.concat(e.trainableWeights);return t}get nonTrainableWeights(){let t=[];for(let e of this.layers)t.push(...e.nonTrainableWeights);if(!this.trainable){let e=[];for(let n of this.layers)e.push(...n.trainableWeights);return e.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,e=!0){let n={},o=0;for(let i of this.layers)for(let a of i.weights){if(n[a.originalName]!=null)throw new z(`Duplicate weight name: ${a.originalName}`);n[a.originalName]=a,o++}let s=[];for(let i in t){let a=i;if(n[i]==null){let u=i.split("/");a=u.slice(0,-2).concat([u[u.length-1]]).join("/")}if(n[a]!=null)s.push([n[a],t[i]]);else if(e)throw new z(`Provided weight data has no target variable: ${i}`);delete n[a]}if(e){let i=[];for(let a in n)i.push(a);if(i.length>0)throw new z(`${i.length} of ${o} weights are not set: ${i}`)}Km(s)}updatedConfig(){let t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion=`tfjs-layers ${ef}`,e.backend="TensorFlow.js",e}toJSON(t,e=!0){let n=ib(this.updatedConfig());return e?JSON.stringify(n):n}call(t,e){return B(()=>{t=we(t);let n=new Oo;for(let o=0;o<this.inputs.length;++o)n.add(this.inputs[o],t[o]);return jc(this.outputs,n,e)})}computeMask(t,e){return B(()=>{t=we(t);let n;return e==null?n=Ao(null,t.length):n=we(e),this.runInternalGraph(t,n)[1]})}computeOutputShape(t){let e=Hm(t);if(e.length!==this.inputLayers.length)throw new z(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let a=0;a<e.length;a++){let u=this.inputLayers[a],l=e[a],c=u.name+"_0_0";n[c]=l}let o=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(_h);if(o.length>1)for(let a of o){let u=this.nodesByDepth[a];for(let l of u){let c=l.outboundLayer;if(this.inputLayers.map(h=>h.id).indexOf(c.id)!==-1)continue;let p=[];for(let h=0;h<l.inboundLayers.length;h++){let g=l.inboundLayers[h],x=l.nodeIndices[h],b=l.tensorIndices[h],w=`${g.name}_${x}_${b}`,I=n[w];p.push(I)}let m=c.computeOutputShape(Tr(p)),f=Hm(m),d=c.inboundNodes.indexOf(l);for(let h=0;h<f.length;h++){let g=`${c.name}_${d}_${h}`;n[g]=f[h]}}}let s=[],i=[];for(let a=0;a<this.outputLayers.length;a++){let u=this.outputLayers[a],l=this.outputLayersNodeIndices[a],c=this.outputLayersTensorIndices[a],p=`${u.name}_${l}_${c}`;i.push(p)}for(let a=0;a<i.length;a++){let u=i[a];fo(u in n),s.push(n[u])}return Tr(s)}runInternalGraph(t,e){e==null&&(e=Ao(null,t.length));let n={};for(let u=0;u<this.inputs.length;++u){let l=this.inputs[u],c=t[u],p=e[u];n[l.id]=[c,p]}let o=Object.keys(this.nodesByDepth).map(u=>parseInt(u,10)).sort(_h);for(let u of o){let l=this.nodesByDepth[u];for(let c of l){let p=c.outboundLayer,m=c.inputTensors,f=c.outputTensors,d=new Array;for(let h of m)h.id in n&&d.push(n[h.id]);if(d.length===m.length){let h={},g,x,b,w;if(c.callArgs!=null&&(h=c.callArgs),d.length===1){let[I,N]=d[0];h.mask==null&&(h.mask=N),b=we(p.call(I,h)),w=we(p.computeMask(I,N)),g=[I],x=[N]}else g=d.map(I=>I[0]),x=d.map(I=>I[1]),h.mask==null&&(h.mask=x),b=we(p.call(g,h)),w=we(p.computeMask(g,x));if(p.activityRegularizer)throw new kt("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let I=0;I<f.length;++I){let N=f[I],E=b[I],A=w[I];n[N.id]=[E,A]}}}}let s=[],i=[],a=[];for(let u of this.outputs){fo(u.id in n,`Could not compute output ${u.name} : ${u.id}`);let[l,c]=n[u.id];a.push(l.shape),s.push(l),i.push(c)}return[s,i,a]}buildNodeConversionMap(t){let e={},n;for(let o of this.layers){n=o instanceof Kn?1:0;for(let s=0;s<o.inboundNodes.length;s++){let i=Kn.nodeKey(o,s);this.containerNodes.has(i)&&(e[i]=n,n+=1)}}return e}getLayer(t,e){if(e!=null)return this.findLayer(e);if(t==null)throw new z("Provide either a layer name or layer index");if(typeof t=="number")return this.findLayer(t);for(let n of this.layers)if(n.name===t)return n;throw new z(`No such layer: ${t}`)}findLayer(t){if(this.layers.length<=t)throw new z(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}calculateLosses(){return B(()=>{let t=[];for(let e of this.layers)for(let n=0;n<e.inboundNodes.length;++n){let o=Kn.nodeKey(e,n);this.containerNodes.has(o)&&t.push(...e.calculateLosses())}return t})}getConfig(){let t={name:this.name},e=this.buildNodeConversionMap(this.layers),n=[];for(let i of this.layers){let a=i.getClassName(),u=i.getConfig(),l=[];for(let p=0;p<i.inboundNodes.length;p++){let m=i.inboundNodes[p],f=Kn.nodeKey(i,p),d={};if(this.containerNodes.has(f)){if(m.callArgs)try{JSON.stringify(m.callArgs),d=m.callArgs}catch(h){console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${m.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),d={}}if(m.inboundLayers.length>0){let h=[];for(let g=0;g<m.inboundLayers.length;g++){let x=m.inboundLayers[g],b=m.nodeIndices[g],w=m.tensorIndices[g],I=Kn.nodeKey(x,b),N=e[I];N==null&&(N=0),h.push([x.name,N,w,d])}l.push(h)}}}let c={};c.name=i.name,c.className=a,c.config=u,c.inboundNodes=l,n.push(c)}t.layers=n;let o=[];for(let i=0;i<this.inputLayers.length;i++){let a=this.inputLayers[i],u=this.inputLayersNodeIndices[i],l=Kn.nodeKey(a,u);if(!this.containerNodes.has(l))continue;let c=e[l];c==null&&(c=0);let p=this.inputLayersTensorIndices[i];o.push([a.name,c,p])}t.inputLayers=o;let s=[];for(let i=0;i<this.outputLayers.length;i++){let a=this.outputLayers[i],u=this.outputLayersNodeIndices[i],l=Kn.nodeKey(a,u);if(!this.containerNodes.has(l))continue;let c=e[l];c==null&&(c=0);let p=this.outputLayersTensorIndices[i];s.push([a.name,c,p])}return t.outputLayers=s,t}static fromConfig(t,e,n={},o=!1){let s={},i={};function a(g,x){g.name in i?i[g.name].push(x):i[g.name]=[x]}function u(g,x){let b=[],w;for(let I of x){let N=I[0],E=I[1],A=I[2];if(w=I[3]==null?{}:I[3],!(N in s)){a(g,x);return}let D=s[N];if(D.inboundNodes.length<=E){a(g,x);return}let F=D.inboundNodes[E];b.push(F.outputTensors[A])}b.length>0&&g.apply(Tr(b),w)}function l(g){let x=g.name,b=Cn(g,e.customObjects!=null?e.customObjects:{});b.setFastWeightInitDuringBuild(o),s[x]=b,g.inboundNodes.forEach(I=>{if(!(I instanceof Array))throw new z(`Corrupted configuration, expected array for nodeData: ${I}`);a(b,I)})}let c=e.name,p=e.layers;for(let g of p)l(g);for(;!z$(i);)for(let g of p){let x=s[g.name];if(x.name in i){let b=i[x.name];delete i[x.name];for(let w of b)u(x,w)}}let m=[],f=[],d=e.inputLayers;for(let g of d){let x=g[0],b=g[1],w=g[2];fo(x in s);let N=s[x].inboundNodes[b].outputTensors;m.push(N[w])}let h=e.outputLayers;for(let g of h){let x=g[0],b=g[1],w=g[2];fo(x in s);let N=s[x].inboundNodes[b].outputTensors;f.push(N[w])}return new t({inputs:m,outputs:f,name:c})}get stateful(){if(this._stateful)throw new z("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let t of this.layers)if(t.stateful)return!0;return!1}resetStates(){B(()=>{this.layers.forEach(t=>{t.stateful&&t.resetStates()})})}};function BZ(r,t,e){let n=t.length;if(r==null||Array.isArray(r)&&r.length===0)return t.map(o=>null);if(n===1)return Array.isArray(r)&&r.length===1?r:typeof r=="object"&&t[0]in r?[r[t[0]]]:[r];if(Array.isArray(r)){if(r.length!==n)throw new Error(`Provided ${e} is an array of ${r.length} element(s), but the model has ${n} outputs. Make sure a set of weights is provided for each model output.`);return r}else if(typeof r=="object"&&Object.keys(r).length>0&&typeof r[Object.keys(r)[0]]=="object"){let o=[];return t.forEach(s=>{s in r?o.push(r[s]):o.push(null)}),o}else throw new Error(`The model has multiple (${n}) outputs, so ${e} must be either an array with ${n} elements or an object with ${t} keys. Provided ${e} not understood: ${JSON.stringify(r)}`)}function ab(r,t){return BZ(r,t,"classWeight")}async function lb(r,t,e,n){if(t!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(e!=null){let o=B(()=>{if(r.shape.length===1)return cn(r);if(r.shape.length===2){if(r.shape[1]>1)return oa(r,1);if(r.shape[1]===1)return R(r,[r.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${r.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${r.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),s=Array.from(await o.data());Tt(o);let i=[];return s.forEach(a=>{if(e[a]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);i.push(e[a])}),Ke(i,"float32")}else return null}function SR(r,t){return $(r,t)}var VZ=32;function TR(r,t){let e,n,o=t;e=o.xs,n=o.ys,y.assert(e!=null&&n!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let s=NR("input",r.inputNames,e),i=NR("output",r.outputNames,n),a=s[0].shape[0];y.assert(s.length===r.inputs.length,()=>`LayersModel has ${r.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(r.inputNames)})`),y.assert(i.length===r.outputs.length,()=>`LayersModel has ${r.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(r.outputNames)})`);for(let u=0;u<s.length;u++)y.assert(s[u].shape[0]===a,()=>`Batch size mismatch: input ${r.inputNames[u]} has ${s[u].shape[0]}; expected ${a} based on input ${r.inputNames[0]}.`);for(let u=0;u<i.length;u++)y.assert(i[u].shape[0]===a,()=>`Batch size mismatch: output ${r.outputNames[u]} has ${i[u].shape[0]}; expected ${a} based on input ${r.inputNames[0]}.`);return{xs:s,ys:i}}function NR(r,t,e){if(e instanceof Ot)return[e];if(Array.isArray(e))return y.assert(e.length===t.length,()=>`Received an array of ${e.length} Tensors, but expected ${t.length} to match the ${r} keys ${t}.`),e;{let n=[];for(let o of t){if(e[o]==null)throw new z(`The feature data generated by the dataset lacks the required ${r} key '${o}'.`);n.push(e[o])}return n}}function GZ(r){if(r.length===3)throw new kt("Validation with sample weights is not implemented yet.");return{xs:r[0],ys:r[1]}}async function _R(r,t,e){let n=e.batchesPerEpoch!=null;if(y.assert(r.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),y.assert(e!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),y.assert(e.epochs!=null&&e.epochs>0&&Number.isInteger(e.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${e.epochs}`),y.assert(!n||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${e.batchesPerEpoch}`),y.assert(e.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;try{let o=e.validationData!=null,s,i;if(o)if(kR(e.validationData))y.assert(e.validationBatches==null||e.validationBatches>0&&Number.isInteger(e.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${e.validationBatches}`);else{let g=GZ(e.validationData);s=g.xs,i=g.ys}let a=r.makeTrainFunction(),u=r.getDedupedMetricsNames(),l;o?l=u.slice().concat(u.map(g=>"val_"+g)):l=u.slice();let c=Qy(e.callbacks,e.yieldEvery),p=e.verbose==null?1:e.verbose,{callbackList:m,history:f}=tb(c,p,e.epochs,null,null,WZ(t,e),null,o,l);m.setModel(r),r.history=f,await m.onTrainBegin(),r.stopTraining_=!1;let d=e.initialEpoch==null?0:e.initialEpoch,h=await t.iterator();for(;d<e.epochs;){let g={};await m.onEpochBegin(d);let x=0,b=0;for(n||(h=await t.iterator());!n||x<e.batchesPerEpoch;){let w=await h.next();if(n&&w.done){console.warn(`You provided \`batchesPerEpoch\` as ${e.batchesPerEpoch}, but your dataset iterator ran out of data after ${x} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${e.batchesPerEpoch*e.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(w.value!=null){let{xs:I,ys:N}=TR(r,w.value),E={};E.batch=b,E.size=I[0].shape[0],await m.onBatchBegin(b,E);let A=[];if(e.classWeight!=null){let P=ab(e.classWeight,r.outputNames);for(let V=0;V<P.length;++V)A.push(await lb(N[V],null,P[V]))}let D=I.concat(N).concat(A),F=a(D);Tt(D);for(let P=0;P<u.length;++P){let V=u[P],G=F[P];E[V]=G,$e(G)}await m.onBatchEnd(b,E),Xy(E),b++,x++}if(n?x>=e.batchesPerEpoch:w.done){if(o){let I;kR(e.validationData)?I=we(await r.evaluateDataset(e.validationData,{batches:e.validationBatches})):I=we(r.evaluate(s,i,{batchSize:e.validationBatchSize==null?VZ:e.validationBatchSize,verbose:0}));for(let N=0;N<r.metricsNames.length;++N)g[`val_${r.metricsNames[N]}`]=I[N]}break}if(r.stopTraining_)break}if(await m.onEpochEnd(d,g),d++,r.stopTraining_)break}return await m.onTrainEnd(),await r.history.syncData(),r.history}finally{r.isTraining=!1}}function WZ(r,t){let e=null;return t.batchesPerEpoch!=null?e=t.batchesPerEpoch:Number.isFinite(r.size)&&(e=r.size),e}function kR(r){return typeof r.iterator=="function"}function UZ(r){return typeof r.next=="function"}async function ER(r,t,e){e=e||{};let n=e.batches!=null,o=r.testFunction,s=[];if(e.verbose>0)throw new kt("Verbose mode is not implemented yet.");y.assert(!n||e.batches>0&&Number.isInteger(e.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(e.batches)}`);let i=UZ(t)?t:await t.iterator(),a=0,u=0;for(;!n||u<e.batches;){let l=await i.next();if(s=B(()=>{if(l.value){let{xs:c,ys:p}=TR(r,l.value),m=c.concat(p),f=B(()=>o(m));if(Tt(m),u===0)for(let h=0;h<f.length;++h)s.push(ft(0));let d=m[0].shape[0];for(let h=0;h<f.length;++h){let g=f[h],x=s[h];s[h]=B(()=>Y(s[h],$(d,g))),u>0&&Tt(x)}Tt(f),a+=d,++u}return s}),l.done){n&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${e.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let l=0;l<s.length;++l){let c=s[l];s[l]=ct(s[l],a),Tt(c)}return Tr(s)}function ub(r){y.assert(r>0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function rf(r,t,e){return r==null?[null]:Array.isArray(r)?r.map(n=>Tl(n,t,e-t)):Tl(r,t,e-t)}function cb(r,t){return B(()=>r==null?null:Array.isArray(r)?r.map(e=>cb(e,t)):Wy(r,t.dtype==="int32"?t:Q(t,"int32")))}function pb(r,t){let e=[],n=0,o=null;for(;n<r;)o=n+t,o>=r&&(o=r),e.push([n,o]),n=o;return e}function HN(r){let t=[];r instanceof Ot&&(r=[r]);for(let e=0;e<r.length;++e){let n=r[e];if(n.rank===1)t.push(_l(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(n)}}return t}function Po(r,t){if(r==null)return;let e=[];if(t instanceof Ot)e.push(t.id);else if(Array.isArray(t))t.forEach(o=>e.push(o.id));else if(t!=null)for(let o in t){let s=t[o];e.push(s.id)}let n=[];if(r instanceof Ot)e.indexOf(r.id)===-1&&n.push(r);else if(Array.isArray(r))r.forEach(o=>{e.indexOf(o.id)===-1&&n.push(o)});else if(r!=null)for(let o in r){let s=r[o];e.indexOf(s.id)===-1&&n.push(s)}n.forEach(o=>{o.isDisposed||o.dispose()})}function HZ(r){return r instanceof Ot}function qN(r){return Array.isArray(r)}function AR(r){return!HZ(r)&&!qN(r)}function DR(r,t,e,n=!0,o=""){if(t==null||t.length===0){if(r!=null){let i=!1;if(qN(r)&&r.length>0)i=!0;else if(AR(r)){for(let a in r)if(r.hasOwnProperty(a)){i=!0;break}}else i=!0;if(i)throw new z(`Error when checking model ${o} expected no data, but got ${r}`)}return[]}if(r==null)return t.map(i=>null);let s;if(AR(r)){r=r,s=[];for(let i of t){if(r[i]==null)throw new z(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(r[i])}}else if(qN(r)){if(r=r,r.length!==t.length)throw new z(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${r}`);s=r}else{if(r=r,t.length>1)throw new z(`The model ${o} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${r.shape}`);s=[r]}if(s=HN(s),e!=null)for(let i=0;i<t.length;++i){if(e[i]==null)continue;let a=s[i];if(a.shape.length!==e[i].length)throw new z(`Error when checking ${o}: expected ${t[i]} to have ${e[i].length} dimension(s). but got array with shape ${a.shape}`);for(let u=0;u<e[i].length;++u){if(u===0&&!n)continue;let l=a.shape[u],c=e[i][u];if(c!=null&&c>=0&&l!==c)throw new z(`${o} expected a batch of elements where each example has shape [${e[i].slice(1,e[i].length)}] (i.e.,tensor shape [*,${e[i].slice(1,e[i].length)}]) but the ${o} received an input with ${a.shape[0]} examples, each with shape [${a.shape.slice(1,a.shape.length)}] (tensor shape [${a.shape}])`)}}return s}function qZ(r,t,e){let n=$o(r.map(s=>s.shape[0]));n.sort();let o=$o(t.map(s=>s.shape[0]));if(o.sort(),n.length>1)throw new z(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(r.map(s=>s.shape))}`);if(o.length>1)throw new z(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(n.length>0&&o.length>0&&!y.arraysEqual(n,o))throw new z(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${o[0]} target sample(s).`)}function KZ(r,t,e){let n=[wa,tf,Yc];for(let o=0;o<r.length;++o){let s=r[o],i=t[o],a=e[o];if(i!=null){if(i===Yc&&s.shape[s.shape.length-1]===1)throw new z(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(n.indexOf(i)!==-1){let u=s.shape.slice(1),l=a.slice(1);for(let c=0;c<u.length;++c){let p=u[c],m=l[c];if(m!=null&&p!==m)throw new z(`A target Tensor with shape ${s.shape} was passed for an output of shape ${a}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function $R(r,t,e,n=!0,o=""){let s;if(Array.isArray(r)){if(r.length!==t.length)throw new z(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${r.length} Tensors(s).`);s=r}else{if(t.length>1)throw new z(`The model expects ${t.length} ${o} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(r.shape)}.`);s=[r]}if(e!=null)for(let i=0;i<t.length;++i){if(e[i]==null)continue;let a=s[i];if(a.shape.length!==e[i].length)throw new z(`Error when checking ${o}: expected ${t[i]} to have ${e[i].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);for(let u=0;u<e[i].length;++u){if(u===0&&!n)continue;let l=a.shape[u],c=e[i][u];if(c!=null&&c!==l)throw new z(`Error when checking ${o}: expected ${t[i]} to have shape ${JSON.stringify(e[i])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}function jZ(r,t){if(r==null||Array.isArray(r)&&r.length===0)return t.map(n=>[]);let e;if(typeof r=="string"||typeof r=="function")e=[r];else if(Array.isArray(r)||typeof r=="object")e=r;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${r}`);if(Array.isArray(e))return t.map(n=>e);{let n=[];for(let o of t){let s=e.hasOwnProperty(o)?e[o]:[];Array.isArray(s)||(s=[s]),n.push(s)}return n}}var XZ="layers-model",jn=class extends Kn{constructor(t){super(t),this.isTraining=!1}summary(t,e,n=console.log){if(!this.built)throw new z("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");CR(this,t,e,n)}compile(t){if(t.loss==null&&(t.loss=[]),this.loss=t.loss,typeof t.optimizer=="string")this.optimizer_=IR(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof Kr))throw new z("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}let e=[];if(!Array.isArray(t.loss)&&typeof t.loss!="string"&&typeof t.loss!="function"){t.loss=t.loss;for(let i in t.loss)if(this.outputNames.indexOf(i)===-1)throw new z(`Unknown entry in loss dictionary: "${i}". Only expected the following keys: ${this.outputNames}`);for(let i of this.outputNames)t.loss[i]==null&&console.warn(`Output "${i}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${i} during training`),e.push(eb(t.loss[i]))}else if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new z(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${t.loss}.`);e=t.loss.map(a=>eb(a))}else{let i=eb(t.loss);this.outputs.forEach(a=>{e.push(i)})}this.lossFunctions=e,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let i=0;i<this.outputs.length;++i){let a=this.internalOutputShapes[i],u=this.outputNames[i];this.feedOutputNames.push(u),this.feedOutputShapes.push(a),this.feedLossFns.push(this.lossFunctions[i])}let n=[];this.metrics=t.metrics,this.metricsNames=["loss"],this.metricsTensors=[],hi("loss",()=>{for(let i=0;i<this.outputs.length;++i){if(n.indexOf(i)!==-1)continue;let a=this.lossFunctions[i];this.outputs.length>1&&(this.metricsTensors.push([a,i]),this.metricsNames.push(this.outputNames[i]+"_loss"))}});let o=jZ(t.metrics,this.outputNames),s=(i,a,u)=>{this.outputNames.length>1&&(a=this.outputNames[i]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([u,i])};hi("metric",()=>{for(let i=0;i<this.outputs.length;++i){if(n.indexOf(i)!==-1)continue;let a=o[i];(l=>{let c="",p,m,f;for(let d of l){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){let g=this.internalOutputShapes[i];g[g.length-1]===1||this.lossFunctions[i]===tf?["accuracy","acc"].indexOf(d)!==-1?m=Ph:["crossentropy","ce"].indexOf(d)!==-1&&(m=nb):this.lossFunctions[i]===Qm?["accuracy","acc"].indexOf(d)!==-1?m=ob:["crossentropy","ce"].indexOf(d)!==-1&&(m=GN):["accuracy","acc"].indexOf(d)!==-1?m=Mh:["crossentropy","ce"].indexOf(d)!==-1&&(m=Lh);let x;["accuracy","acc"].indexOf(d)!==-1?x="acc":["crossentropy","ce"].indexOf(d)!==-1&&(x="ce"),f=m,p=c+x}else f=bR(d),p=c+zh(d);let h;hi(p,()=>{h=f}),s(i,p,h)}})(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(t,e,n={}){let o=n.batchSize==null?32:n.batchSize;ub(o);let s=!0,i=this.standardizeUserDataXY(t,e,s,o);try{let a=i[0].concat(i[1]);this.makeTestFunction();let u=this.testFunction,l=this.testLoop(u,a,o,n.verbose,n.steps);return Tr(l)}finally{Po(i[0],t),Po(i[1],e)}}async evaluateDataset(t,e){return this.makeTestFunction(),ER(this,t,e)}checkNumSamples(t,e,n,o="steps"){let s;if(n!=null){if(s=null,e!=null)throw new z(`If ${o} is set, batchSize must be null or undefined.Got batchSize = ${e}`)}else if(t!=null)Array.isArray(t)?s=t[0].shape[0]:s=t.shape[0];else throw new z(`Either the input data should have a defined shape, or ${o} shoud be specified.`);return s}execute(t,e){if(Array.isArray(e)&&e.length===0)throw new z("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(e),o=n?e:[e],s=this.retrieveSymbolicTensors(o),i=new Oo;if(t instanceof Ot&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new z(`The number of inputs provided (${t.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let u=0;u<this.inputs.length;++u)i.add(this.inputs[u],t[u])}else for(let u of this.inputs){let l=t[u.name];if(l==null)throw new z(`No value is provided for the model's input ${u.name}`);i.add(u,l)}let a=jc(s,i);return n?a:a[0]}retrieveSymbolicTensors(t){let e=Ao(null,t.length),n=t.length;for(let o of this.layers){let s=Array.isArray(o.output)?o.output:[o.output],i=s.map(a=>a.name);for(let a=0;a<t.length;++a){let u=i.indexOf(t[a]);if(u!==-1&&(e[a]=s[u],n--),n===0)break}if(n===0)break}if(n>0){let o=[];throw e.forEach((s,i)=>{s==null&&o.push(t[i])}),new z(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`)}return e}predictLoop(t,e=32,n=!1){return B(()=>{let o=this.checkNumSamples(t);if(n)throw new kt("Verbose predictLoop() is not implemented yet.");let s=pb(o,e),i=this.outputs.map(a=>[]);for(let a=0;a<s.length;++a)B(()=>{let l=s[a][0],c=s[a][1],p=rf(t,l,c),m=[];if(Array.isArray(p))for(let d=0;d<p.length;++d)m.push({key:this.inputs[d],value:p[d]});else m.push({key:this.inputs[0],value:p});let f=new Oo(m);return jc(this.outputs,f)}).forEach((l,c)=>i[c].push(l));return Tr(i.map(a=>ie(a,0)))})}predict(t,e={}){let n=HN(t);$R(n,this.inputNames,this.feedInputShapes,!1);try{let o=e.batchSize==null?32:e.batchSize;return ub(o),this.predictLoop(n,o)}finally{Po(n,t)}}predictOnBatch(t){$R(t,this.inputNames,this.feedInputShapes,!0);let e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)}standardizeUserDataXY(t,e,n=!0,o){if(this.optimizer_==null)throw new Xr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let i=0;i<this.feedOutputShapes.length;++i){let a=this.feedOutputShapes[i];this.feedLossFns[i]===Qm?s.push(a.slice(0,a.length-1).concat([1])):s.push(a)}if(t=DR(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=DR(e,this.feedOutputNames,s,!1,"target"),qZ(t,e,null),KZ(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&o!=null&&o>0&&t[0].shape[0]%o!==0)throw new z(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${o}. Found: ${t[0].shape[0]} sample(s).`);return[t,e]}async standardizeUserData(t,e,n,o,s=!0,i){let[a,u]=this.standardizeUserDataXY(t,e,s,i);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(o!=null){let c=ab(o,this.outputNames);l=[];for(let p=0;p<c.length;++p)l.push(await lb(u[p],null,c[p]))}return[a,u,l]}testLoop(t,e,n,o=0,s){return B(()=>{let i=this.checkNumSamples(e,n,s,"steps"),a=[];if(o>0)throw new kt("Verbose mode is not implemented yet.");if(s!=null)throw new kt("steps mode in testLoop() is not implemented yet");{let u=pb(i,n),l=Ke(xn(0,i));for(let c=0;c<u.length;++c){let p=u[c][0],m=u[c][1],f=Tl(l,p,m-p),d=cb(e,f),h=t(d);if(c===0)for(let g=0;g<h.length;++g)a.push(ft(0));for(let g=0;g<h.length;++g){let x=h[g];a[g]=Y(a[g],$(m-p,x))}}for(let c=0;c<a.length;++c)a[c]=ct(a[c],i)}return a})}getDedupedMetricsNames(){let t=this.metricsNames,e=[];for(let n=0;n<t.length;++n){let o=t[n],s=o;if($N(t,o)>1){let i=$N(t.slice(0,n),o);s+=`_${i}`}e.push(s)}return e}makeTrainFunction(){return t=>{let e=[],n=t.slice(0,this.inputs.length),o=t.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=t.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),i=[],a=()=>{let p=[];for(let h=0;h<this.inputs.length;++h)p.push({key:this.inputs[h],value:n[h]});let m=new Oo(p),f=jc(this.outputs,m,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let g=this.lossFunctions[h],x=g(o[h],f[h]);s[h]!=null&&(x=SR(x,s[h]));let b=ke(x);e.push(b),h===0?d=x:d=Y(d,x)}for(let h=0;h<this.metricsTensors.length;++h){let g;if(this.outputs.length>1&&h<this.outputs.length)g=e[h];else{let x=this.metricsTensors[h][0],b=this.metricsTensors[h][1];g=ke(x(o[b],f[b]))}$e(g),i.push(g)}return d=ke(d),this.calculateLosses().forEach(h=>{d=Y(d,h)}),d},u=this.collectedTrainableWeights.map(p=>p.read()),l=!0;return[this.optimizer_.minimize(a,l,u)].concat(i)}}makeTestFunction(){this.testFunction=t=>B(()=>{let e=[],n,o=t.slice(0,this.inputs.length),s=t.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=[];for(let l=0;l<this.inputs.length;++l)i.push({key:this.inputs[l],value:o[l]});let a=new Oo(i),u=jc(this.outputs,a);for(let l=0;l<this.lossFunctions.length;++l){let c=this.lossFunctions[l],p=ke(c(s[l],u[l]));l===0?n=p:n=Y(n,p),e.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let c=this.metricsTensors[l][0],p=this.metricsTensors[l][1],m=ke(c(s[p],u[p]));e.push(m)}return e})}async fit(t,e,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");this.isTraining=!0;let o,s,i,a,u,l,c,p,m;try{let f=n.batchSize==null?32:n.batchSize;ub(f);let d=!1,h=await this.standardizeUserData(t,e,n.sampleWeight,n.classWeight,d,f);o=h[0],s=h[1],m=h[2];let g=!1,x;if(n.validationData!=null&&n.validationData.length>0){if(g=!0,n.validationData.length===2)u=n.validationData[0],l=n.validationData[1];else throw n.validationData.length===3?new kt("validationData including sample weights is not supported yet."):new z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);let F=!0,P=await this.standardizeUserData(u,l,null,null,F,f);c=P[0],p=P[1],x=c.concat(p)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){g=!0;let F=Math.floor(o[0].shape[0]*(1-n.validationSplit)),P=o[0].shape[0];c=rf(o,F,P),i=o,o=rf(o,0,F),p=rf(s,F,P),a=s,s=rf(s,0,F),x=c.concat(p)}else n.validationSteps!=null&&(g=!0);let b=o.concat(s).concat(m);this.checkTrainableWeightsConsistency();let w=this.makeTrainFunction(),I=this.getDedupedMetricsNames(),N,E;g?(this.makeTestFunction(),N=this.testFunction,E=I.slice().concat(I.map(F=>"val_"+F))):(N=null,x=[],E=I.slice());let A=Qy(n.callbacks,n.yieldEvery);return await this.fitLoop(w,b,I,f,n.epochs,n.verbose,A,N,x,n.shuffle,E,n.initialEpoch,null,null)}finally{this.isTraining=!1,Po(o,t),Po(s,e),Po(i,t),Po(a,e),Po(c,u),Po(p,l),m!=null&&Tt(m)}}async fitLoop(t,e,n,o,s,i,a,u,l,c,p,m,f,d){o==null&&(o=32),s==null&&(s=1),c==null&&(c=!0),m==null&&(m=0);let h=!1;if(u!=null&&l!=null&&(h=!0),d!=null&&(h=!0,f==null))throw new z("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=this.checkNumSamples(e,o,f,"steps_per_epoch"),x;g!=null&&(x=xn(0,g)),i==null&&(i=1);let{callbackList:b,history:w}=tb(a,i,s,m,g,f,o,h,p);b.setModel(this),this.history=w,await b.onTrainBegin(),this.stopTraining_=!1;for(let I=m;I<s;++I){await b.onEpochBegin(I);let N={};if(f!=null)throw new kt("stepsPerEpoch mode is not implemented yet.");{if(c==="batch")throw new kt("batch shuffling is not implemneted yet");c&&y.shuffle(x);let E=Ke(x),A=pb(g,o);for(let D=0;D<A.length;++D){let F={};if(await b.onBatchBegin(D,F),B(()=>{let P=A[D][0],V=A[D][1],G=Tl(E,P,V-P);F.batch=D,F.size=V-P;let W=cb(e,G),q=t(W);for(let H=0;H<n.length;++H){let K=n[H],X=q[H];F[K]=X,$e(X)}if(D===A.length-1&&h){let H=this.testLoop(u,l,o);for(let K=0;K<n.length;++K){let X=n[K],Z=H[K];$e(Z),N["val_"+X]=Z}}}),await b.onBatchEnd(D,F),Xy(F),this.stopTraining_)break}E.dispose()}if(await b.onEpochEnd(I,N),this.stopTraining_)break}return await b.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(t,e){return _R(this,t,e)}async trainOnBatch(t,e){let n=await this.standardizeUserData(t,e),o=n[0],s=n[1],a=this.makeTrainFunction()(o.concat(s)),u=[];for(let l of a){let c=await l.data();u.push(c[0])}return Tt(a),Po(n[0],t),Po(n[1],e),Tr(u)}getNamedWeights(t){let e=[],n=t!=null&&t.trainableOnly,o=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let i=0;i<o.length;++i)n&&!o[i].trainable||e.push({name:o[i].originalName,tensor:s[i]});return e}set stopTraining(t){this.stopTraining_=t}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)}dispose(){let t=super.dispose();if(t.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let e=fh().numTensors;this.optimizer_.dispose(),t.numDisposedVariables+=e-fh().numTensors}return t}getLossIdentifiers(){let t;if(typeof this.loss=="string")t=Do(this.loss);else if(Array.isArray(this.loss)){for(let e of this.loss)if(typeof e!="string")throw new Error("Serialization of non-string loss is not supported.");t=this.loss.map(e=>Do(e))}else{let e=Object.keys(this.loss);t={};let n=this.loss;for(let o of e)if(typeof n[o]=="string")t[o]=Do(n[o]);else throw new Error("Serialization of non-string loss is not supported.")}return t}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[Do(zh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(t=>Do(zh(t)));{let t={};for(let e in this.metrics)t[e]=Do(zh(this.metrics[e]));return t}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(t){if(t.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(t.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(t.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let e=Zc(t.optimizer_config),n=Cn(e),o;if(typeof t.loss=="string")o=kl(t.loss);else if(Array.isArray(t.loss))o=t.loss.map(i=>kl(i));else if(t.loss!=null){o={};for(let i in t.loss)o[i]=kl(t.loss[i])}let s;if(Array.isArray(t.metrics))s=t.metrics.map(i=>kl(i));else if(t.metrics!=null){s={};for(let i in t.metrics)s[i]=kl(t.metrics[i])}this.compile({loss:o,metrics:s,optimizer:n})}async save(t,e){if(typeof t=="string"){let l=Lr.getSaveHandlers(t);if(l.length===0)throw new z(`Cannot find any save handlers for URL '${t}'`);if(l.length>1)throw new z(`Found more than one (${l.length}) save handlers for URL '${t}'`);t=l[0]}if(t.save==null)throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Lr.encodeWeights(this.getNamedWeights(e)),o=!1,s=null,a={modelTopology:this.toJSON(s,o),format:XZ,generatedBy:`TensorFlow.js tfjs-layers v${ef}`,convertedBy:null};if((e==null?!1:e.includeOptimizer)&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:c,specs:p}=await Lr.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...p),n.data=Lr.concatenateArrayBuffers([n.data,c])}return this.userDefinedMetadata!=null&&(UN(this.userDefinedMetadata,this.name,!0),a.userDefinedMetadata=this.userDefinedMetadata),a.weightData=n.data,a.weightSpecs=n.specs,t.save(a)}setUserDefinedMetadata(t){UN(t,this.name),this.userDefinedMetadata=t}getUserDefinedMetadata(){return this.userDefinedMetadata}};jn.className="Model";J.registerClass(jn);var mb=class extends jn{};mb.className="Functional";J.registerClass(mb);async function RR(r,t){"modelTopology"in r||(r={modelTopology:r}),r=r;let e=r.modelTopology;e.model_config!=null&&(e=e.model_config);let n=Zc(e),o=Cn(n,t);if(r.weightsManifest!=null){let s=await Lr.loadWeights(r.weightsManifest,r.pathPrefix,o.weights.map(a=>a.originalName)),i={};for(let a of o.weights)i[a.originalName]=s[a.originalName];o.loadWeights(i),Tt(s)}return o}async function FR(r,t){if(t==null&&(t={}),typeof r=="string"){let e=Lr.getLoadHandlers(r,t);if(e.length===0)e.push(Lr.browserHTTPRequest(r,t));else if(e.length>1)throw new z(`Found more than one (${e.length}) load handlers for URL '${r}'`);r=e[0]}return YZ(r,void 0,t)}async function YZ(r,t,e){if(e==null&&(e={}),r.load==null)throw new z("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let n=await r.load(),o=n.modelTopology;o.model_config!=null&&(o=o.model_config);let s=e.strict==null?!0:e.strict,i=n.weightData!=null&&n.weightSpecs!=null&&s,a=Cn(Zc(o),t,i),u=n.trainingConfig;if(u!=null&&a.loadTrainingConfig(u),n.userDefinedMetadata!=null&&a.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new z("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:l,optimizerWeights:c}=ZZ(n.weightData,n.weightSpecs);a.loadWeights(l,s),a.optimizer!=null&&c.length>0&&await a.optimizer.setWeights(c),Tt(l),Tt(c.map(p=>p.tensor))}return a}function ZZ(r,t){let e=Lr.decodeWeights(r,t),n={},o=[];return t.forEach(s=>{s.group==="optimizer"?o.push({name:s.name,tensor:e[s.name]}):n[s.name]=e[s.name]}),{modelWeights:n,optimizerWeights:o}}var Ia=class extends jn{constructor(t){if(super({inputs:[],outputs:[]}),t=t||{},this.trainable=!0,this.built=!1,this.name=t.name!=null?t.name:zu("sequential_"),t.layers!=null)for(let e of t.layers)this.add(e)}checkShape(t){if(t.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new z(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`)}add(t){let e=t instanceof Ia||t instanceof jn,n;if(e){if(n=t,n.outputs.length!==1)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new z("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(t.inboundNodes.length===0){if(t.batchInputShape==null)throw new z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let o=qy({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(o)}if(e)this.outputs=n.outputs,this.inputs=n.inputs;else{if(t.inboundNodes.length!==1)throw new z(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);if(t.inboundNodes[0].outputTensors.length!==1)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=LN(this.outputs[0])}this.inboundNodes=[],new El({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ao(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(o=>o.shape),outputShapes:this.outputs[0].shape})}else{let o=t.apply(this.outputs[0]);if(Array.isArray(o))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[o],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(t,e){return this.model==null&&this.build(),this.model.call(t,e)}build(t){if(Gt(t),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new jn({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(t,e,n=console.log){this.built||this.build(),super.summary(t,e,n)}setWeights(t){this.model==null&&this.build(),this.model.setWeights(t)}evaluate(t,e,n={}){if(!this.built)throw new Xr("The model needs to be compiled before being used.");return this.model.evaluate(t,e,n)}async evaluateDataset(t,e){if(!this.built)throw new Xr("The model needs to be compiled before being used.");return this.model.evaluateDataset(t,e)}predict(t,e={}){return this.model==null&&this.build(),this.model.predict(t,e)}predictOnBatch(t){return this.model==null&&this.build(),this.model.predictOnBatch(t)}compile(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(t){this.model.optimizer=t}async fit(t,e,n={}){if(!this.built)throw new Xr("The model needs to be compiled before being used.");return this.model.fit(t,e,n)}async fitDataset(t,e){if(!this.built)throw new Xr("The model needs to be compiled before being used.");return this.model.fitDataset(t,e)}async trainOnBatch(t,e){return this.model.trainOnBatch(t,e)}static fromConfig(t,e,n={},o=!1){let s,i={};if(e instanceof Array){if(e[0].className==null||e[0].className==="Merge")throw new z("Legacy serialization format not supported yet.");s=e}else y.assert(e.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),s=e.layers,delete e.layers,i=e;let a=new t(i);if(!(a instanceof Ia))throw new kt(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(let u of s){let c=Cn(u,void 0,o);o&&c.setFastWeightInitDuringBuild(!0),a.add(c)}return a}set stopTraining(t){if(this.model==null)throw new z("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t}get stopTraining(){if(this.model==null)throw new z("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let t=[];for(let e of this.layers){let n={};n.className=e.getClassName(),n.config=e.getConfig(),t.push(n)}return{name:this.name,layers:t}}};Ia.className="Sequential";J.registerClass(Ia);function JZ(r){return new jn(r)}function QZ(r){return new Ia(r)}function KN(r){return qy(r)}function tJ(r,t){In.registerCallbackConstructor(r,t)}var on=class extends J.Serializable{getConfig(){return{}}},fb=class extends on{apply(t,e=1){return tR(t,e)}};fb.className="elu";J.registerClass(fb);var db=class extends on{apply(t){return Im(t)}};db.className="selu";J.registerClass(db);var hb=class extends on{apply(t){return Mr(t)}};hb.className="relu";J.registerClass(hb);var gb=class extends on{apply(t){return B(()=>mo(6,Mr(t)))}};gb.className="relu6";J.registerClass(gb);var xb=class extends on{apply(t){return t}};xb.className="linear";J.registerClass(xb);var yb=class extends on{apply(t){return en(t)}};yb.className="sigmoid";J.registerClass(yb);var bb=class extends on{apply(t){return rR(t)}};bb.className="hardSigmoid";J.registerClass(bb);var wb=class extends on{apply(t){return pi(t)}};wb.className="softplus";J.registerClass(wb);var Ib=class extends on{apply(t){return eR(t)}};Ib.className="softsign";J.registerClass(Ib);var Cb=class extends on{apply(t){return ia(t)}};Cb.className="tanh";J.registerClass(Cb);var nf=class extends on{apply(t,e=-1){return Fu(t,e)}};nf.className="softmax";J.registerClass(nf);var vb=class extends on{apply(t,e=-1){return hm(t,e)}};vb.className="logSoftmax";J.registerClass(vb);var Sb=class extends on{apply(t,e=1){return B(()=>$(en($(t,e)),t))}};Sb.className="swish";J.registerClass(Sb);var Nb=class extends on{apply(t){return B(()=>$(t,ia(pi(t))))}};Nb.className="mish";J.registerClass(Nb);function yi(r){return r.getClassName()}function jN(r,t={}){return xa(r,J.SerializationMap.getMap().classNameMap,t,"activation")}function bi(r){if(r==null){let t={};return t.className="linear",t.config={},jN(t)}if(typeof r=="string"){let t={};return t.className=r,t.config={},jN(t)}else return r instanceof on?r:jN(r)}function XN(r){if(r!=null&&typeof r!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${r}`)}var kb=class extends J.Serializable{},Wu=class extends kb{constructor(t){super(),XN(t),this.l1=t==null||t.l1==null?.01:t.l1,this.l2=t==null||t.l2==null?.01:t.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(t){return B(()=>{let e=Te([1]);return this.hasL1&&(e=Y(e,pt($(this.l1,Ee(t))))),this.hasL2&&(e=Y(e,pt($(this.l2,Vc(t))))),R(e,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(t,e){return new t({l1:e.l1,l2:e.l2})}};Wu.className="L1L2";J.registerClass(Wu);function MR(r){return XN(r),new Wu({l1:r!=null?r.l1:null,l2:0})}function LR(r){return XN(r),new Wu({l2:r!=null?r.l2:null,l1:0})}var OR={l1l2:"L1L2"};function me(r){return Fm(r)}function PR(r,t={}){return xa(r,J.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ce(r){if(r==null)return null;if(typeof r=="string"){let e={className:r in OR?OR[r]:r,config:{}};return PR(e)}else return r instanceof kb?r:PR(r)}var of=class extends _t{constructor(t){super(t==null?{}:t),this.supportsMasking=!0,t!=null&&(this.maxValue=t.maxValue)}call(t,e){t=St(t);let n=Mr(t);return this.maxValue!=null&&(n=Sr(n,0,this.maxValue)),n}computeOutputShape(t){return t}getConfig(){let t={maxValue:this.maxValue},e=super.getConfig();return Object.assign(t,e),t}};of.className="ReLU";J.registerClass(of);var sf=class extends _t{constructor(t){super(t==null?{}:t),this.DEFAULT_ALPHA=.3,t==null&&(t={}),this.alpha=t.alpha==null?this.DEFAULT_ALPHA:t.alpha}call(t,e){let n=St(t);return _u(n,this.alpha)}computeOutputShape(t){return t}getConfig(){let t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}};sf.className="LeakyReLU";J.registerClass(sf);var af=class extends _t{constructor(t){if(super(t==null?{}:t),this.DEFAULT_ALPHA_INITIALIZER="zeros",t==null&&(t={}),this.supportsMasking=!0,this.alphaInitializer=he(t.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Ce(t.alphaRegularizer),this.alphaConstraint=Ve(t.alphaConstraint),t.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(t.sharedAxes))this.sharedAxes=t.sharedAxes;else if(typeof t.sharedAxes=="number")this.sharedAxes=[t.sharedAxes];else throw new z(`Expected sharedAxes to be a number or an array of numbers, but got ${t.sharedAxes}`)}build(t){t=Gt(t);let e=t.slice(1);if(this.sharedAxes!=null)for(let o of this.sharedAxes)e[o-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let o=1;o<t.length;++o)n[o]=t[o];this.inputSpec=[new Ie({ndim:t.length,axes:n})],this.built=!0}call(t,e){return t=St(t),Ru(t,this.alpha.read())}getConfig(){let t={alphaInitializer:_e(this.alphaInitializer),alphaRegularizer:me(this.alphaRegularizer),alphaConstraint:Be(this.alphaConstraint),sharedAxes:this.sharedAxes},e=super.getConfig();return Object.assign(t,e),t}};af.className="PReLU";J.registerClass(af);var lf=class extends _t{constructor(t){if(super(t==null?{}:t),this.DEFAULT_ALPHA=1,t==null&&(t={}),t.alpha!=null&&t.alpha!==this.DEFAULT_ALPHA)throw new kt(`Non-default alpha value (${t.alpha}) is not supported by the ELU layer yet.`);this.alpha=t.alpha==null?this.DEFAULT_ALPHA:t.alpha}call(t,e){let n=St(t);return ca(n)}computeOutputShape(t){return t}getConfig(){let t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}};lf.className="ELU";J.registerClass(lf);var uf=class extends _t{constructor(t){super(t==null?{}:t),this.DEFAULT_THETA=1,t==null&&(t={}),this.theta=t.theta==null?this.DEFAULT_THETA:t.theta}call(t,e){let n=St(t);return $(n,Q(Fe(n,this.theta),"float32"))}computeOutputShape(t){return t}getConfig(){let t={theta:this.theta},e=super.getConfig();return Object.assign(t,e),t}};uf.className="ThresholdedReLU";J.registerClass(uf);var cf=class extends _t{constructor(t){super(t==null?{}:t),this.DEFAULT_AXIS=1,t==null&&(t={}),this.softmax=new nf().apply,this.axis=t.axis==null?this.DEFAULT_AXIS:t.axis}call(t,e){let n=St(t);return this.softmax(n,this.axis)}computeOutputShape(t){return t}getConfig(){let t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}};cf.className="Softmax";J.registerClass(cf);function Uu(r,t,e){if(typeof r=="number")return Ao(r,t);if(r.length!==t)throw new z(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${r.length} elements.`);for(let n=0;n<t;++n){let o=r[n];if(!Y$(o))throw new z(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(r)} including a non-integer number ${o}`)}return r}function An(r,t,e,n,o=1){if(r==null)return r;let s=t+(t-1)*(o-1),i;return e==="same"?i=r:i=r-s+1,Math.floor((i+n-1)/n)}function wi(r,t,e,n){if(r==null)return null;if(n==="valid")r=r*t+gi([e-t,0]);else if(n==="same")r=r*t;else throw new z(`Unsupport padding mode: ${n}.`);return r}function Bh(r,t){return B(()=>(Oe(t),t==="channelsFirst"?Vt(r,[0,2,3,1]):r))}function YN(r,t){return B(()=>(Oe(t),t==="channelsFirst"?Vt(r,[0,2,3,4,1]):r))}function rJ(r,t,e,n=1,o="valid",s,i=1){return B(()=>{if(s==null&&(s=yn()),Oe(s),r.shape.length!==3)throw new z(`The input of a conv1dWithBias operation should be 3, but is ${r.shape.length} instead.`);if(t.shape.length!==3)throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(e!=null&&e.shape.length!==1)throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(r=Vt(r,[0,2,1])),o==="causal")throw new kt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=cm(r,t,n,o==="same"?"same":"valid","NWC",i);return e!=null&&(a=bn(a,e)),a})}function zR(r,t,e,n=[1,1],o="valid",s,i,a=null){return B(()=>{if(s==null&&(s=yn()),Oe(s),r.rank!==3&&r.rank!==4)throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${r.rank}.`);if(t.rank!==3&&t.rank!==4)throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${r.rank}.`);let u=Bh(r,s);if(o==="causal")throw new kt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=Lu.conv2d({x:u,filter:t,strides:n,pad:o==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:e,activation:a}),s==="channelsFirst"&&(u=Vt(u,[0,3,1,2])),u})}function nJ(r,t,e,n=[1,1,1],o="valid",s,i){return B(()=>{if(s==null&&(s=yn()),Oe(s),r.rank!==4&&r.rank!==5)throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${r.rank}.`);if(t.rank!==4&&t.rank!==5)throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${r.rank}.`);let a=YN(r,s);if(o==="causal")throw new kt("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=Rx(a,t,n,o==="same"?"same":"valid","NDHWC",i),e!=null&&(a=bn(a,e)),s==="channelsFirst"&&(a=Vt(a,[0,4,1,2,3])),a})}var Jc=class extends _t{constructor(t,e){if(super(e),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Jc.verifyArgs(e),this.rank=t,Qe(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new kt(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Uu(e.kernelSize,t,"kernelSize"),this.strides=Uu(e.strides==null?1:e.strides,t,"strides"),this.padding=e.padding==null?"valid":e.padding,gn(this.padding),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Oe(this.dataFormat),this.activation=bi(e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.biasInitializer=he(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Ve(e.biasConstraint),this.biasRegularizer=Ce(e.biasRegularizer),this.activityRegularizer=Ce(e.activityRegularizer),this.dilationRate=Uu(e.dilationRate==null?1:e.dilationRate,t,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new z(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new z(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(t){if(fo("kernelSize"in t,"required key 'kernelSize' not in config"),typeof t.kernelSize!="number"&&!Oy(t.kernelSize,"number",1,3))throw new z(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){let t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:yi(this.activation),useBias:this.useBias,biasInitializer:_e(this.biasInitializer),biasRegularizer:me(this.biasRegularizer),activityRegularizer:me(this.activityRegularizer),biasConstraint:Be(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}},Hu=class extends Jc{constructor(t,e){super(t,e),this.kernel=null,Hu.verifyArgs(e),this.filters=e.filters,Qe(this.filters,"filters"),this.kernelInitializer=he(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Ve(e.kernelConstraint),this.kernelRegularizer=Ce(e.kernelRegularizer)}build(t){t=Gt(t);let e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new z(`The channel dimension of the input should be defined. Found ${t[e]}`);let n=t[e],o=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[e]:n}}],this.built=!0}call(t,e){return B(()=>{t=St(t);let n,o=this.bias==null?null:this.bias.read(),s=Py(this.activation.getClassName());if(s!=null&&this.rank===2)n=zR(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)n=rJ(t,this.kernel.read(),o,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=zR(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=nJ(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new kt("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(t){t=Gt(t);let e=[],n=this.dataFormat==="channelsLast"?t.slice(1,t.length-1):t.slice(2);for(let s=0;s<n.length;++s){let i=An(n[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);e.push(i)}let o=[t[0]];return this.dataFormat==="channelsLast"?(o=o.concat(e),o.push(this.filters)):(o.push(this.filters),o=o.concat(e)),o}getConfig(){let t={filters:this.filters,kernelInitializer:_e(this.kernelInitializer),kernelRegularizer:me(this.kernelRegularizer),kernelConstraint:Be(this.kernelConstraint)},e=super.getConfig();return Object.assign(t,e),t}static verifyArgs(t){if(!("filters"in t)||typeof t.filters!="number"||t.filters<1)throw new z(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(t.filters)}`)}},Dl=class extends Hu{constructor(t){super(2,t),Dl.verifyArgs(t)}getConfig(){let t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!Oy(t.kernelSize,"number",1,2))throw new z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`)}};Dl.className="Conv2D";J.registerClass(Dl);var $l=class extends Hu{constructor(t){super(3,t),$l.verifyArgs(t)}getConfig(){let t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!(Array.isArray(t.kernelSize)&&(t.kernelSize.length===1||t.kernelSize.length===3)))throw new z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`)}};$l.className="Conv3D";J.registerClass($l);var pf=class extends Dl{constructor(t){if(super(t),this.inputSpec=[new Ie({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(t=Gt(t),t.length!==4)throw new z("Input should have rank 4; Received input shape: "+JSON.stringify(t));let e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new z("The channel dimension of the inputs should be defined. Found `None`.");let n=t[e],o=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",o,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ie({ndim:4,axes:{[e]:n}})],this.built=!0}call(t,e){return B(()=>{let n=St(t);if(n.shape.length!==4)throw new z(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let o=n.shape,s=o[0],i,a;this.dataFormat==="channelsFirst"?(i=2,a=3):(i=1,a=2);let u=o[i],l=o[a],c=this.kernelSize[0],p=this.kernelSize[1],m=this.strides[0],f=this.strides[1],d=wi(u,m,c,this.padding),h=wi(l,f,p,this.padding),g=[s,d,h,this.filters];this.dataFormat!=="channelsLast"&&(n=Vt(n,[0,2,3,1]));let x=mm(n,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(x=Vt(x,[0,3,1,2])),this.bias!=null&&(x=bn(x,this.bias.read(),this.dataFormat)),this.activation!=null&&(x=this.activation.apply(x)),x})}computeOutputShape(t){t=Gt(t);let e=t.slice(),n,o,s;this.dataFormat==="channelsFirst"?(n=1,o=2,s=3):(n=3,o=1,s=2);let i=this.kernelSize[0],a=this.kernelSize[1],u=this.strides[0],l=this.strides[1];return e[n]=this.filters,e[o]=wi(e[o],u,i,this.padding),e[s]=wi(e[s],l,a,this.padding),e}getConfig(){let t=super.getConfig();return delete t.dilationRate,t}};pf.className="Conv2DTranspose";J.registerClass(pf);var mf=class extends $l{constructor(t){if(super(t),this.inputSpec=[new Ie({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(t=Gt(t),t.length!==5)throw new z("Input should have rank 5; Received input shape: "+JSON.stringify(t));let e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new z("The channel dimension of the inputs should be defined. Found `None`.");let n=t[e],o=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",o,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ie({ndim:5,axes:{[e]:n}})],this.built=!0}call(t,e){return B(()=>{let n=St(t);if(n.shape.length!==5)throw new z(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let o=n.shape,s=o[0],i,a,u;this.dataFormat==="channelsFirst"?(u=2,i=3,a=4):(u=1,i=2,a=3);let l=o[u],c=o[i],p=o[a],m=this.kernelSize[0],f=this.kernelSize[1],d=this.kernelSize[2],h=this.strides[0],g=this.strides[1],x=this.strides[2],b=wi(l,h,m,this.padding),w=wi(c,g,f,this.padding),I=wi(p,x,d,this.padding),N=[s,b,w,I,this.filters];this.dataFormat!=="channelsLast"&&(n=Vt(n,[0,2,3,4,1]));let E=Ox(n,this.kernel.read(),N,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(E=Vt(E,[0,4,1,2,3])),this.bias!==null&&(E=bn(E,this.bias.read(),this.dataFormat)),this.activation!==null&&(E=this.activation.apply(E)),E})}computeOutputShape(t){t=Gt(t);let e=t.slice(),n,o,s,i;this.dataFormat==="channelsFirst"?(n=1,o=2,s=3,i=4):(n=4,o=1,s=2,i=3);let a=this.kernelSize[0],u=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],p=this.strides[1],m=this.strides[2];return e[n]=this.filters,e[o]=wi(e[o],c,a,this.padding),e[s]=wi(e[s],p,u,this.padding),e[i]=wi(e[i],m,l,this.padding),e}getConfig(){let t=super.getConfig();return delete t.dilationRate,t}};mf.className="Conv3DTranspose";J.registerClass(mf);var Tb=class extends Hu{constructor(t,e){if(super(t,e),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,e.filters==null)throw new z("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(e.kernelInitializer!=null||e.kernelRegularizer!=null||e.kernelConstraint!=null)throw new z("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(e.padding!=null&&e.padding!=="same"&&e.padding!=="valid")throw new z(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(e.padding)}`);this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=he(e.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Ce(e.depthwiseRegularizer),this.depthwiseConstraint=Ve(e.depthwiseConstraint),this.pointwiseInitializer=he(e.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ce(e.pointwiseRegularizer),this.pointwiseConstraint=Ve(e.pointwiseConstraint)}build(t){if(t=Gt(t),t.length<this.rank+2)throw new z(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(t)}`);let e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null||t[e]<0)throw new z(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(t[e])}`);let n=t[e],o=this.kernelSize.concat([n,this.depthMultiplier]),s=[];for(let a=0;a<this.rank;++a)s.push(1);s.push(n*this.depthMultiplier,this.filters);let i=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",o,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,i,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,i,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,i,this.biasConstraint):this.bias=null,this.inputSpec=[new Ie({ndim:this.rank+2,axes:{[e]:n}})],this.built=!0}call(t,e){return B(()=>{t=St(t);let n;if(this.rank===1)throw new kt("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(t=Vt(t,[0,2,3,1])),n=Cm(t,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=bn(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Vt(n,[0,3,1,2])),n})}getConfig(){let t=super.getConfig();return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=_e(this.depthwiseInitializer),t.pointwiseInitializer=_e(this.pointwiseInitializer),t.depthwiseRegularizer=me(this.depthwiseRegularizer),t.pointwiseRegularizer=me(this.pointwiseRegularizer),t.depthwiseConstraint=Be(this.depthwiseConstraint),t.pointwiseConstraint=Be(this.pointwiseConstraint),t}};Tb.className="SeparableConv";var ff=class extends Tb{constructor(t){super(2,t)}};ff.className="SeparableConv2D";J.registerClass(ff);var qu=class extends Hu{constructor(t){super(1,t),qu.verifyArgs(t),this.inputSpec=[{ndim:3}]}getConfig(){let t=super.getConfig();return delete t.rank,delete t.dataFormat,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!Oy(t.kernelSize,"number",1,1))throw new z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`)}};qu.className="Conv1D";J.registerClass(qu);var df=class extends _t{constructor(t){super(t),typeof t.cropping=="number"?this.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:typeof t.cropping[0]=="number"?this.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:this.cropping=t.cropping,this.dataFormat=t.dataFormat===void 0?"channelsLast":t.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(t){return this.dataFormat==="channelsFirst"?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]}call(t,e){return B(()=>{if(t=St(t),this.dataFormat==="channelsLast"){let n=Ah(t,this.cropping[0][0],t.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ah(n,this.cropping[1][0],t.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Ah(t,this.cropping[0][0],t.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ah(n,this.cropping[1][0],t.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let t={cropping:this.cropping,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}};df.className="Cropping2D";J.registerClass(df);var hf=class extends _t{constructor(t){super(t),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=t.size==null?this.DEFAULT_SIZE:t.size,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Oe(this.dataFormat),this.interpolation=t.interpolation==null?"nearest":t.interpolation,j$(this.interpolation)}computeOutputShape(t){if(this.dataFormat==="channelsFirst"){let e=t[2]==null?null:this.size[0]*t[2],n=t[3]==null?null:this.size[1]*t[3];return[t[0],t[1],e,n]}else{let e=t[1]==null?null:this.size[0]*t[1],n=t[2]==null?null:this.size[1]*t[2];return[t[0],e,n,t[3]]}}call(t,e){return B(()=>{let n=St(t),o=n.shape;if(this.dataFormat==="channelsFirst"){n=Vt(n,[0,2,3,1]);let s=this.size[0]*o[2],i=this.size[1]*o[3],a=this.interpolation==="nearest"?hn.resizeNearestNeighbor(n,[s,i]):hn.resizeBilinear(n,[s,i]);return Vt(a,[0,3,1,2])}else{let s=this.size[0]*o[1],i=this.size[1]*o[2];return this.interpolation==="nearest"?hn.resizeNearestNeighbor(n,[s,i]):hn.resizeBilinear(n,[s,i])}})}getConfig(){let t={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},e=super.getConfig();return Object.assign(t,e),t}};hf.className="UpSampling2D";J.registerClass(hf);function oJ(r,t,e=[1,1],n="valid",o,s){return B(()=>{o==null&&(o=yn()),Oe(o);let i=Bh(r,o);if(r.rank!==4)throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${r.rank}-D`);if(t.rank!==4)throw new z(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=ua(i,t,e,n==="same"?"same":"valid","NHWC",s),o==="channelsFirst"&&(i=Vt(i,[0,3,1,2])),i})}var gf=class extends Jc{constructor(t){super(2,t),this.depthwiseKernel=null,this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=he(t.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Ve(t.depthwiseConstraint),this.depthwiseRegularizer=Ce(t.depthwiseRegularizer)}build(t){if(t=Gt(t),t.length<4)throw new z(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(t)}.`);let e=this.dataFormat==="channelsFirst"?1:3;if(t[e]==null||t[e]<0)throw new z(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${t[e]}).`);let n=t[e],o=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",o,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return B(()=>{t=St(t);let n=oJ(t,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=bn(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(t){t=Gt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],n=this.dataFormat==="channelsFirst"?t[3]:t[2],o=this.dataFormat==="channelsFirst"?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,s=An(e,this.kernelSize[0],this.padding,this.strides[0]),i=An(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[t[0],o,s,i]:[t[0],s,i,o]}getConfig(){let t=super.getConfig();return t.depthMultiplier=this.depthMultiplier,t.depthwiseInitializer=_e(this.depthwiseInitializer),t.depthwiseRegularizer=me(this.depthwiseRegularizer),t.depthwiseConstraint=Be(this.depthwiseRegularizer),t}};gf.className="DepthwiseConv2D";J.registerClass(gf);function ZN(r,t,e,n){if(Array.isArray(r)){if(t!=null||e!=null)throw new z("When inputs is an array, neither initialState or constants should be provided");n!=null&&(e=r.slice(r.length-n,r.length),r=r.slice(0,r.length-n)),r.length>1&&(t=r.slice(1,r.length)),r=r[0]}function o(s){return s==null||Array.isArray(s)?s:[s]}return t=o(t),e=o(e),{inputs:r,initialState:t,constants:e}}function JN(r,t,e,n=!1,o,s,i=!1,a=!1){return B(()=>{let u=t.shape.length;if(u<3)throw new z(`Input should be at least 3D, but is ${u}D.`);let l=[1,0].concat(xn(2,u));if(t=Vt(t,l),s!=null)throw new kt("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),o!=null&&(o=Q(Q(o,"bool"),"float32"),o.rank===u-1&&(o=ar(o,-1)),o=Vt(o,l)),n&&(t=hr(t,0),o!=null&&(o=hr(o,0)));let c=[],p,m=e,f=t.shape[0],d=xr(t),h;o!=null&&(h=xr(o));for(let x=0;x<f;++x){let b=d[x],w=B(()=>r(b,m));if(o==null)p=w[0],m=w[1];else{let I=B(()=>{let N=h[x],E=lt(Ir(N),N),A=Y($(w[0],N),$(m[0],E)),D=m.map((F,P)=>Y($(w[1][P],N),$(F,E)));return{output:A,newStates:D}});p=I.output,m=I.newStates}a&&c.push(p)}let g;return a&&(g=qe(c,1)),[p,g,m]})}var Dn=class extends _t{constructor(t){super(t);let e;if(t.cell==null)throw new z("cell property is missing for the constructor of RNN.");if(Array.isArray(t.cell)?e=new ep({cells:t.cell}):e=t.cell,e.stateSize==null)throw new z("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=e,this.returnSequences=t.returnSequences==null?!1:t.returnSequences,this.returnState=t.returnState==null?!1:t.returnState,this.goBackwards=t.goBackwards==null?!1:t.goBackwards,this._stateful=t.stateful==null?!1:t.stateful,this.unroll=t.unroll==null?!1:t.unroll,this.supportsMasking=!0,this.inputSpec=[new Ie({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return xn(0,t).map(e=>null)}else return this.states_}setStates(t){this.states_=t}computeOutputShape(t){Hy(t)&&(t=t[0]),t=t;let e=this.cell.stateSize;Array.isArray(e)||(e=[e]);let n=e[0],o;if(this.returnSequences?o=[t[0],t[1],n]:o=[t[0],n],this.returnState){let s=[];for(let i of e)s.push([t[0],i]);return[o].concat(s)}else return o}computeMask(t,e){return B(()=>{Array.isArray(e)&&(e=e[0]);let n=this.returnSequences?e:null;if(this.returnState){let o=this.states.map(s=>null);return[n].concat(o)}else return n})}get states(){if(this.states_==null){let t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[];for(let n=0;n<t;++n)e.push(null);return e}else return this.states_}set states(t){this.states_=t}build(t){if(this.numConstants!=null)throw new kt("Constants support is not implemented in RNN yet.");Hy(t)&&(t=t[0]),t=t;let n=this.stateful?t[0]:null,o=t.slice(2);this.inputSpec[0]=new Ie({shape:[n,null,...o]});let s=[t[0]].concat(t.slice(2));this.cell.build(s);let i;if(Array.isArray(this.cell.stateSize)?i=this.cell.stateSize:i=[this.cell.stateSize],this.stateSpec!=null){if(!y.arraysEqual(this.stateSpec.map(a=>a.shape[a.shape.length-1]),i))throw new z(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=i.map(a=>new Ie({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(t,e=!1){B(()=>{if(!this.stateful)throw new En("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>Te([n,o])):this.states_=[Te([n,this.cell.stateSize])];else if(t==null)Tt(this.states_),this.keptStates!=null&&(Tt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>Te([n,o])):this.states_[0]=Te([n,this.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);e===!0?this.keptStates.push(this.states_.slice()):Tt(this.states_);for(let o=0;o<this.states_.length;++o){let s=t[o],i=Array.isArray(this.cell.stateSize)?this.cell.stateSize[o]:this.cell.stateSize,a=[n,i];if(!y.arraysEqual(s.shape,a))throw new z(`State ${o} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${s.shape}`);this.states_[o]=s}}this.states_=this.states_.map(o=>$e(o.clone()))})}apply(t,e){let n=e==null?null:e.initialState,o=e==null?null:e.constants;e==null&&(e={});let s=ZN(t,n,o,this.numConstants);t=s.inputs,n=s.initialState,o=s.constants;let i=[],a=[];if(n!=null){e.initialState=n,i=i.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Ie({shape:l.shape}));a=a.concat(this.stateSpec)}if(o!=null&&(e.constants=o,i=i.concat(o),this.numConstants=o.length),i[0]instanceof nn){let l=[t].concat(i),c=this.inputSpec.concat(a),p=this.inputSpec;this.inputSpec=c;let m=super.apply(l,e);return this.inputSpec=p,m}else return super.apply(t,e)}call(t,e){return B(()=>{let n=e==null?null:e.mask,o=e==null?null:e.training,s=e==null?null:e.initialState;t=St(t),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(t));let i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==i)throw new z(`RNN Layer has ${i} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let a={training:o},l=JN((d,h)=>{let g=this.cell.call([d].concat(h),a);return[g[0],g.slice(1)]},t,s,this.goBackwards,n,null,this.unroll,this.returnSequences),c=l[0],p=l[1],m=l[2];this.stateful&&this.resetStates(m,o);let f=this.returnSequences?p:c;return this.returnState?[f].concat(m):f})}getInitialState(t){return B(()=>{let e=Te(t.shape);return e=pt(e,[1,2]),e=_l(e),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Gy(e,[1,n]):e):this.cell.stateSize>1?[Gy(e,[1,this.cell.stateSize])]:[e]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(t)}getConfig(){let t=super.getConfig(),e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(e.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===Dn.className&&(e.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),t),e)}static fromConfig(t,e,n={}){let o=e.cell,s=Cn(o,n);return new t(Object.assign(e,{cell:s}))}};Dn.className="RNN";J.registerClass(Dn);var Rl=class extends _t{},Qc=class extends Rl{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,Qe(this.units,"units"),this.activation=bi(t.activation==null?this.DEFAULT_ACTIVATION:t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=he(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=he(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=he(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ce(t.kernelRegularizer),this.recurrentRegularizer=Ce(t.recurrentRegularizer),this.biasRegularizer=Ce(t.biasRegularizer),this.kernelConstraint=Ve(t.kernelConstraint),this.recurrentConstraint=Ve(t.recurrentConstraint),this.biasConstraint=Ve(t.biasConstraint),this.dropout=Bc([1,gi([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=Bc([1,gi([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Gt(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return B(()=>{if(t=t,t.length!==2)throw new z(`SimpleRNNCell expects 2 input Tensors, got ${t.length}.`);let n=t[1];t=t[0];let o=e.training==null?!1:e.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ol({ones:()=>Ir(t),rate:this.dropout,training:o,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ol({ones:()=>Ir(n),rate:this.recurrentDropout,training:o,dropoutFunc:this.dropoutFunc}));let s,i=this.dropoutMask,a=this.recurrentDropoutMask;i!=null?s=Fo($(t,i),this.kernel.read()):s=Fo(t,this.kernel.read()),this.bias!=null&&(s=bn(s,this.bias.read())),a!=null&&(n=$(n,a));let u=Y(s,Fo(n,this.recurrentKernel.read()));return this.activation!=null&&(u=this.activation.apply(u)),[u,u]})}getConfig(){let t=super.getConfig(),e={units:this.units,activation:yi(this.activation),useBias:this.useBias,kernelInitializer:_e(this.kernelInitializer),recurrentInitializer:_e(this.recurrentInitializer),biasInitializer:_e(this.biasInitializer),kernelRegularizer:me(this.kernelRegularizer),recurrentRegularizer:me(this.recurrentRegularizer),biasRegularizer:me(this.biasRegularizer),activityRegularizer:me(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},t),e)}};Qc.className="SimpleRNNCell";J.registerClass(Qc);var xf=class extends Dn{constructor(t){t.cell=new Qc(t),super(t)}call(t,e){return B(()=>{this.cell.dropoutMask!=null&&(Tt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Tt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=e==null?null:e.mask,o=e==null?null:e.training,s=e==null?null:e.initialState;return super.call(t,{mask:n,training:o,initialState:s})})}static fromConfig(t,e){return new t(e)}};xf.className="SimpleRNN";J.registerClass(xf);var tp=class extends Rl{constructor(t){if(super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.resetAfter)throw new z("GRUCell does not support reset_after parameter set to true.");this.units=t.units,Qe(this.units,"units"),this.activation=bi(t.activation===void 0?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=bi(t.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=he(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=he(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=he(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ce(t.kernelRegularizer),this.recurrentRegularizer=Ce(t.recurrentRegularizer),this.biasRegularizer=Ce(t.biasRegularizer),this.kernelConstraint=Ve(t.kernelConstraint),this.recurrentConstraint=Ve(t.recurrentConstraint),this.biasConstraint=Ve(t.biasConstraint),this.dropout=Bc([1,gi([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=Bc([1,gi([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Gt(t);let e=t[t.length-1];this.kernel=this.addWeight("kernel",[e,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return B(()=>{if(t=t,t.length!==2)throw new z(`GRUCell expects 2 input Tensors (inputs, h, c), got ${t.length}.`);let n=e.training==null?!1:e.training,o=t[1];t=t[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ol({ones:()=>Ir(t),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ol({ones:()=>Ir(o),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,a,u,l;0<this.dropout&&this.dropout<1&&(t=$(t,s[0]));let c=Fo(t,this.kernel.read());this.useBias&&(c=bn(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(o=$(o,i[0]));let p=this.recurrentKernel.read(),[m,f]=gr(p,[2*this.units,this.units],p.rank-1),d=Fo(o,m),[h,g,x]=gr(c,3,c.rank-1),[b,w]=gr(d,2,d.rank-1);a=this.recurrentActivation.apply(Y(h,b)),u=this.recurrentActivation.apply(Y(g,w));let I=Fo($(u,o),f);l=this.activation.apply(Y(x,I));let N=Y($(a,o),$(Y(1,Ut(a)),l));return[N,N]})}getConfig(){let t=super.getConfig(),e={units:this.units,activation:yi(this.activation),recurrentActivation:yi(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_e(this.kernelInitializer),recurrentInitializer:_e(this.recurrentInitializer),biasInitializer:_e(this.biasInitializer),kernelRegularizer:me(this.kernelRegularizer),recurrentRegularizer:me(this.recurrentRegularizer),biasRegularizer:me(this.biasRegularizer),activityRegularizer:me(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},t),e)}};tp.className="GRUCell";J.registerClass(tp);var yf=class extends Dn{constructor(t){t.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new tp(t),super(t)}call(t,e){return B(()=>{this.cell.dropoutMask!=null&&(Tt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Tt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=e==null?null:e.mask,o=e==null?null:e.training,s=e==null?null:e.initialState;return super.call(t,{mask:n,training:o,initialState:s})})}static fromConfig(t,e){return e.implmentation===0&&(e.implementation=1),new t(e)}};yf.className="GRU";J.registerClass(yf);var Fl=class extends Rl{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,Qe(this.units,"units"),this.activation=bi(t.activation===void 0?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=bi(t.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=he(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=he(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=he(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=t.unitForgetBias,this.kernelRegularizer=Ce(t.kernelRegularizer),this.recurrentRegularizer=Ce(t.recurrentRegularizer),this.biasRegularizer=Ce(t.biasRegularizer),this.kernelConstraint=Ve(t.kernelConstraint),this.recurrentConstraint=Ve(t.recurrentConstraint),this.biasConstraint=Ve(t.biasConstraint),this.dropout=Bc([1,gi([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=Bc([1,gi([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){var e;t=Gt(t);let n=t[t.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let o;if(this.useBias){if(this.unitForgetBias){let s=this.biasInitializer,i=this.units;o=new(e=class extends wn{apply(u,l){let c=s.apply([i]),p=new Vu().apply([i]),m=s.apply([i*2]);return MN(MN(c,p),m)}},e.className="CustomInit",e)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,o,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(t,e){return B(()=>{let n=e.training==null?!1:e.training;if(t=t,t.length!==3)throw new z(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);let o=t[1],s=t[2];t=t[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ol({ones:()=>Ir(t),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ol({ones:()=>Ir(o),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,a=this.recurrentDropoutMask,u,l,c,p;0<this.dropout&&this.dropout<1&&(t=$(t,i[0]));let m=Fo(t,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(o=$(o,a[0])),m=Y(m,Fo(o,this.recurrentKernel.read())),this.useBias&&(m=bn(m,this.bias.read()));let[f,d,h,g]=gr(m,4,m.rank-1);u=this.recurrentActivation.apply(f),l=this.recurrentActivation.apply(d),c=Y($(l,s),$(u,this.activation.apply(h))),p=this.recurrentActivation.apply(g);let x=$(p,this.activation.apply(c));return[x,x,c]})}getConfig(){let t=super.getConfig(),e={units:this.units,activation:yi(this.activation),recurrentActivation:yi(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_e(this.kernelInitializer),recurrentInitializer:_e(this.recurrentInitializer),biasInitializer:_e(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:me(this.kernelRegularizer),recurrentRegularizer:me(this.recurrentRegularizer),biasRegularizer:me(this.biasRegularizer),activityRegularizer:me(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},t),e)}};Fl.className="LSTMCell";J.registerClass(Fl);var bf=class extends Dn{constructor(t){t.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new Fl(t),super(t)}call(t,e){return B(()=>{this.cell.dropoutMask!=null&&(Tt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Tt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=e==null?null:e.mask,o=e==null?null:e.training,s=e==null?null:e.initialState;return super.call(t,{mask:n,training:o,initialState:s})})}static fromConfig(t,e){return e.implmentation===0&&(e.implementation=1),new t(e)}};bf.className="LSTM";J.registerClass(bf);var ep=class extends Rl{constructor(t){super(t),this.cells=t.cells}get stateSize(){let t=[];for(let e of this.cells.slice().reverse())Array.isArray(e.stateSize)?t.push(...e.stateSize):t.push(e.stateSize);return t}call(t,e){return B(()=>{t=t;let n=t.slice(1),o=[];for(let a of this.cells.slice().reverse())Array.isArray(a.stateSize)?o.push(n.splice(0,a.stateSize.length)):o.push(n.splice(0,1));o.reverse();let s=[],i;for(let a=0;a<this.cells.length;++a){let u=this.cells[a];n=o[a],a===0?i=[t[0]].concat(n):i=[i[0]].concat(n),i=u.call(i,e),s.push(i.slice(1))}n=[];for(let a of s.slice().reverse())n.push(...a);return[i[0]].concat(n)})}build(t){Hy(t)&&(t=t[0]),t=t;let e;this.cells.forEach((n,o)=>{hi(`RNNCell_${o}`,()=>{n.build(t),Array.isArray(n.stateSize)?e=n.stateSize[0]:e=n.stateSize,t=[t[0],e]})}),this.built=!0}getConfig(){let t=super.getConfig(),e=s=>({className:s.getClassName(),config:s.getConfig()}),o={cells:this.cells.map(e)};return Object.assign(Object.assign({},t),o)}static fromConfig(t,e,n={}){let o=[];for(let s of e.cells)o.push(Cn(s,n));return new t({cells:o})}get trainableWeights(){if(!this.trainable)return[];let t=[];for(let e of this.cells)t.push(...e.trainableWeights);return t}get nonTrainableWeights(){let t=[];for(let e of this.cells)t.push(...e.nonTrainableWeights);if(!this.trainable){let e=[];for(let n of this.cells)e.push(...n.trainableWeights);return e.concat(t)}return t}getWeights(){let t=[];for(let e of this.cells)t.push(...e.weights);return $h(t)}setWeights(t){let e=[];for(let n of this.cells){let o=n.weights.length,s=t.splice(o);for(let i=0;i<n.weights.length;++i)e.push([n.weights[i],s[i]])}Km(e)}};ep.className="StackedRNNCells";J.registerClass(ep);function Ol(r){let{ones:t,rate:e,training:n=!1,count:o=1,dropoutFunc:s}=r,i=()=>s!=null?s(t(),e):Uy(t(),e),a=()=>Bu(i,t,n);return!o||o<=1?$e(a().clone()):Array(o).fill(void 0).map(a).map(l=>$e(l.clone()))}var sJ=function(r,t){var e={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&t.indexOf(n)<0&&(e[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(r);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(r,n[o])&&(e[n[o]]=r[n[o]]);return e};var _b=class extends Dn{constructor(t){if(t.unroll)throw new kt("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(t.cell))throw new kt("It is not possible at the moment to stack convolutional cells.");super(t),this.inputSpec=[new Ie({ndim:5})]}call(t,e){return B(()=>{if(this.cell.dropoutMask!=null&&(Tt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Tt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),e&&e.constants)throw new z("ConvRNN2D cell does not support constants");let n=e==null?null:e.mask,o=e==null?null:e.training,s=e==null?null:e.initialState;return super.call(t,{mask:n,training:o,initialState:s})})}computeOutputShape(t){let e=this.computeSingleOutputShape(t);return this.returnSequences||(e=[e[0],...e.slice(2)]),this.returnState&&(e=[e,...Array(2).fill([t[0],...e.slice(-3)])]),e}getInitialState(t){return B(()=>{let{stateSize:e}=this.cell,n=t.shape,o=this.computeSingleOutputShape(n),s=[o[0],...o.slice(2)],i=Te(s);return Array.isArray(e)?Array(e.length).fill(i):[i]})}resetStates(t,e=!1){B(()=>{if(!this.stateful)throw new En("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,o=this.computeSingleOutputShape(n),s=[o[0],...o.slice(2)];if(n[0]==null)throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Te(s)):this.states_=[Te(s)];else if(t==null)Tt(this.states_),this.keptStates!=null&&(Tt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Te(s)):this.states_[0]=Te(s);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);e?this.keptStates.push(this.states_.slice()):Tt(this.states_);for(let a=0;a<this.states_.length;++a){let u=t[a],l=s;if(!y.arraysEqual(u.shape,l))throw new z(`State ${a} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${u.shape}`);this.states_[a]=u}}this.states_=this.states_.map(a=>$e(a.clone()))})}computeSingleOutputShape(t){let{dataFormat:e,filters:n,kernelSize:o,padding:s,strides:i,dilationRate:a}=this.cell,u=e==="channelsFirst",l=t[u?3:2],c=t[u?4:3],p=An(l,o[0],s,i[0],a[0]),m=An(c,o[1],s,i[1],a[1]);return[...t.slice(0,2),...u?[n,p,m]:[p,m,n]]}};_b.className="ConvRNN2D";var rp=class extends Fl{constructor(t){let{filters:e,kernelSize:n,strides:o,padding:s,dataFormat:i,dilationRate:a}=t;super(Object.assign(Object.assign({},t),{units:e})),this.filters=e,Qe(this.filters,"filters"),this.kernelSize=Uu(n,2,"kernelSize"),this.kernelSize.forEach(u=>Qe(u,"kernelSize")),this.strides=Uu(o||1,2,"strides"),this.strides.forEach(u=>Qe(u,"strides")),this.padding=s||"valid",gn(this.padding),this.dataFormat=i||"channelsLast",Oe(this.dataFormat),this.dilationRate=Uu(a||1,2,"dilationRate"),this.dilationRate.forEach(u=>Qe(u,"dilationRate"))}build(t){var e;t=Gt(t);let n=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[n]==null)throw new z(`The channel dimension of the input should be defined. Found ${t[n]}`);let o=t[n],s=4,i=this.kernelSize.concat([o,this.filters*s]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let a=this.kernelSize.concat([this.filters,this.filters*s]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let u;if(this.unitForgetBias){let l=this.biasInitializer,c=this.filters;u=new(e=class extends wn{apply(m,f){let d=l.apply([c]),h=dr([c]),g=l.apply([c*2]);return Pm([d,h,g])}},e.className="CustomInit",e)}else u=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*s],null,u,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(t,e){return B(()=>{if(t.length!==3)throw new z(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);let n=e.training||!1,o=t[0],s=t[1],i=t[2],a=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ol({ones:()=>Ir(o),rate:this.dropout,training:n,count:a,dropoutFunc:this.dropoutFunc}));let u=this.dropoutMask,l=(nt,st,at)=>!st||!st[at]?nt:$(st[at],nt),c=l(o,u,0),p=l(o,u,1),m=l(o,u,2),f=l(o,u,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ol({ones:()=>Ir(s),rate:this.recurrentDropout,training:n,count:a,dropoutFunc:this.dropoutFunc}));let d=this.recurrentDropoutMask,h=l(s,d,0),g=l(s,d,1),x=l(s,d,2),b=l(s,d,3),w=3,[I,N,E,A]=gr(this.kernel.read(),a,w),[D,F,P,V]=this.useBias?gr(this.bias.read(),a):[null,null,null,null];c=this.inputConv(c,I,D,this.padding),p=this.inputConv(p,N,F,this.padding),m=this.inputConv(m,E,P,this.padding),f=this.inputConv(f,A,V,this.padding);let[G,W,q,H]=gr(this.recurrentKernel.read(),a,w);h=this.recurrentConv(h,G),g=this.recurrentConv(g,W),x=this.recurrentConv(x,q),b=this.recurrentConv(b,H);let K=this.recurrentActivation.apply(Y(c,h)),X=this.recurrentActivation.apply(Y(p,g)),Z=Y($(X,i),$(K,this.activation.apply(Y(m,x)))),et=$(this.recurrentActivation.apply(Y(f,b)),this.activation.apply(Z));return[et,et,Z]})}getConfig(){let t=super.getConfig(),{units:e}=t,n=sJ(t,["units"]),o={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),o)}inputConv(t,e,n,o){let s=Tn(t,e,this.strides,o||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?bn(s,n,this.dataFormat):s}recurrentConv(t,e){return Tn(t,e,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};rp.className="ConvLSTM2DCell";J.registerClass(rp);var wf=class extends _b{constructor(t){let e=new rp(t);super(Object.assign(Object.assign({},t),{cell:e}))}static fromConfig(t,e){return new t(e)}};wf.className="ConvLSTM2D";J.registerClass(wf);var np=class extends _t{constructor(t){super(t),this.rate=Math.max(Math.min(t.rate,1),0),this.noiseShape=t.noiseShape,this.seed=t.seed,this.supportsMasking=!0}getNoiseShape(t){if(this.noiseShape==null)return this.noiseShape;let e=t.shape,n=[];for(let o=0;o<this.noiseShape.length;++o)n.push(this.noiseShape[o]==null?e[o]:this.noiseShape[o]);return n}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t);if(0<this.rate&&this.rate<1){let o=e.training==null?!1:e.training,s=this.getNoiseShape(n);return Bu(()=>Uy(n,this.rate,s,this.seed),()=>n,o)}return t})}getConfig(){let t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},e=super.getConfig();return Object.assign(t,e),t}dispose(){return super.dispose()}};np.className="Dropout";J.registerClass(np);var If=class extends np{constructor(t){super(t),this.inputSpec=[{ndim:3}]}getNoiseShape(t){let e=t.shape;return[e[0],1,e[2]]}};If.className="SpatialDropout1D";J.registerClass(If);var Cf=class extends _t{constructor(t){if(super(t),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.batchInputShape==null&&t.inputShape==null&&t.inputDim!=null){let e=null;t.batchSize!=null&&(e=t.batchSize),this.batchInputShape=[e,t.inputDim]}this.units=t.units,Qe(this.units,"units"),this.activation=bi(t.activation),t.useBias!=null&&(this.useBias=t.useBias),this.kernelInitializer=he(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=he(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Ve(t.kernelConstraint),this.biasConstraint=Ve(t.biasConstraint),this.kernelRegularizer=Ce(t.kernelRegularizer),this.biasRegularizer=Ce(t.biasRegularizer),this.activityRegularizer=Ce(t.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(t){t=Gt(t);let e=t[t.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[e,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:e}}],this.built=!0}computeOutputShape(t){t=Gt(t);let e=t.slice();return e[e.length-1]=this.units,e}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t),o=Py(this.activation.getClassName()),s;return o!=null?s=Fo(n,this.kernel.read(),o,this.bias?this.bias.read():null):(s=Fo(n,this.kernel.read()),this.bias!=null&&(s=bn(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let t={units:this.units,activation:yi(this.activation),useBias:this.useBias,kernelInitializer:_e(this.kernelInitializer),biasInitializer:_e(this.biasInitializer),kernelRegularizer:me(this.kernelRegularizer),biasRegularizer:me(this.biasRegularizer),activityRegularizer:me(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),biasConstraint:Be(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}};Cf.className="Dense";J.registerClass(Cf);var vf=class extends _t{constructor(t){t=t||{},super(t),this.inputSpec=[{minNDim:3}],this.dataFormat=t.dataFormat}computeOutputShape(t){t=Gt(t);for(let e of t.slice(1))if(e==null)throw new z(`The shape of the input to "Flatten" is not fully defined (got ${t.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[t[0],Ro(t,1)]}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t);if(this.dataFormat==="channelsFirst"&&n.rank>1){let o=[0];for(let s=2;s<n.rank;++s)o.push(s);o.push(1),n=Vt(n,o)}return Q$(n)})}getConfig(){let t={};this.dataFormat!=null&&(t.dataFormat=this.dataFormat);let e=super.getConfig();return Object.assign(t,e),t}};vf.className="Flatten";J.registerClass(vf);var Sf=class extends _t{constructor(t){super(t),this.supportsMasking=!0,this.activation=bi(t.activation)}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t);return this.activation.apply(n)})}getConfig(){let t={activation:yi(this.activation)},e=super.getConfig();return Object.assign(t,e),t}};Sf.className="Activation";J.registerClass(Sf);var Nf=class extends _t{constructor(t){super(t),this.n=t.n,this.inputSpec=[{ndim:2}]}computeOutputShape(t){return[t[0],this.n,t[1]]}call(t,e){return B(()=>(t=St(t),Z$(t,this.n)))}getConfig(){let t={n:this.n},e=super.getConfig();return Object.assign(t,e),t}};Nf.className="RepeatVector";J.registerClass(Nf);var kf=class extends _t{constructor(t){super(t),this.targetShape=t.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(t){return t<0||t==null}fixUnknownDimension(t,e){let n="Total size of new array must be unchanged.",o=e.slice(),s=1,i=null;for(let u=0;u<o.length;++u){let l=o[u];if(this.isUnknown(l))if(i===null)i=u;else throw new z("Can only specifiy one unknown dimension.");else s*=l}let a=Ro(t);if(i!==null){if(s===0||a%s!==0)throw new z(n);o[i]=a/s}else if(a!==s)throw new z(n);return o}computeOutputShape(t){let e=!1;for(let n=0;n<t.length;++n)if(this.isUnknown(t[n])){e=!0;break}return e?t.slice(0,1).concat(this.targetShape):t.slice(0,1).concat(this.fixUnknownDimension(t.slice(1),this.targetShape))}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t),o=n.shape,s=o.slice(0,1).concat(this.fixUnknownDimension(o.slice(1),this.targetShape));return R(n,s)})}getConfig(){let t={targetShape:this.targetShape},e=super.getConfig();return Object.assign(t,e),t}};kf.className="Reshape";J.registerClass(kf);var Tf=class extends _t{constructor(t){if(super(t),t.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(t.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${t.dims} instead.`);let e=xn(1,t.dims.length+1);if(!y.arraysEqual(t.dims.slice().sort(),e))throw new Error("Invalid permutation `dims`: "+JSON.stringify(t.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=t.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Ie({ndim:this.dims.length+1})]}computeOutputShape(t){t=Gt(t);let e=t.slice();return this.dims.forEach((n,o)=>{e[o+1]=t[n]}),e}call(t,e){return Vt(St(t),this.dimsIncludingBatch)}getConfig(){let t={dims:this.dims},e=super.getConfig();return Object.assign(t,e),t}};Tf.className="Permute";J.registerClass(Tf);var _f=class extends _t{constructor(t){super(t==null?{}:t),this.supportsMasking=!0,t!=null?this.maskValue=t.maskValue==null?0:t.maskValue:this.maskValue=0}computeOutputShape(t){return t}getConfig(){let t=super.getConfig(),e={maskValue:this.maskValue};return Object.assign(e,t),e}computeMask(t,e){let n=St(t),o=-1;return bc(mi(n,this.maskValue),o)}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t),o=-1,s=!0,i=bc(mi(n,this.maskValue),o,s);return $(n,Q(i,n.dtype))})}};_f.className="Masking";J.registerClass(_f);var Ef=class extends _t{constructor(t){if(super(t),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",t.batchInputShape==null&&t.inputShape==null){let e=null;t.batchSize!=null&&(e=t.batchSize),t.inputLength==null?this.batchInputShape=[e,null]:this.batchInputShape=[e].concat(we(t.inputLength))}this.inputDim=t.inputDim,Qe(this.inputDim,"inputDim"),this.outputDim=t.outputDim,Qe(this.outputDim,"outputDim"),this.embeddingsInitializer=he(t.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ce(t.embeddingsRegularizer),this.activityRegularizer=Ce(t.activityRegularizer),this.embeddingsConstraint=Ve(t.embeddingsConstraint),this.maskZero=t.maskZero,this.supportsMasking=t.maskZero,this.inputLength=t.inputLength}build(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(t){}computeMask(t,e){return B(()=>this.maskZero?(t=St(t),mi(t,vt(t))):null)}computeOutputShape(t){if(t=Gt(t),this.inputLength==null)return[...t,this.outputDim];let e=we(this.inputLength);if(e.length!==t.length-1)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);{let n=0;for(let o=0;o<e.length;++o){let s=e[o],i=t[o+1];if(s!=null&&i!=null&&s!==i)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);s==null&&(e[n]=i),n++}}return[t[0],...e,this.outputDim]}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t);n.dtype!=="int32"&&(n=rn(n,"int32"));let o=Wy(this.embeddings.read(),R(n,[n.size]));return R(o,Gt(this.computeOutputShape(n.shape)))})}getConfig(){let t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:_e(this.embeddingsInitializer),embeddingsRegularizer:me(this.embeddingsRegularizer),activityRegularizer:me(this.activityRegularizer),embeddingsConstraint:Be(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},e=super.getConfig();return Object.assign(t,e),t}};Ef.className="Embedding";J.registerClass(Ef);var Pl=class extends _t{constructor(t){super(t||{}),this.supportsMasking=!0}mergeFunction(t){throw new kt}computeElementwiseOpOutputShape(t,e){if(t==null||e==null)return null;if(t.length<e.length)return this.computeElementwiseOpOutputShape(e,t);if(e.length===0)return t;let n=t.slice(0,t.length-e.length);for(let o=0;o<e.length;++o){let s=t[t.length-e.length+o],i=e[o];if(s==null||i==null||s<0||i<0)n.push(null);else if(s===1)n.push(i);else if(i===1)n.push(s);else{if(s!==i)throw new z("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));n.push(s)}}return n}build(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[Gt(t)]),t=t,t.length<2)throw new z(`A merge layer should be called on an Array of at least 2 inputs. Got ${t.length} input(s).`);let e=[];for(let s of t)s!=null&&s[0]!==null&&e.push(s[0]);if(e=$o(e),e.length>1)throw new z(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(t)}.`);let n=t[0]==null?null:t[0].slice(1);for(let s=1;s<t.length;++s){let i=t[s]==null?null:t[s].slice(1);n=this.computeElementwiseOpOutputShape(n,i)}let o=t.map(s=>s.length);t.indexOf(null)===-1&&$o(o).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(t,e){return B(()=>{if(t=t,this.reshapeRequired){let n=[],o=t.map(s=>s.rank);if(o.indexOf(null)===-1){let s=gi(o);for(let i of t){let a=i.rank;for(let u=0;u<s-a;++u)i=_l(i,1);n.push(i)}return this.mergeFunction(n)}else{let s=!1;for(let u of t){let l=u.rank;if(l==null){let c=u.shape,p=c[0],m=c.slice(1).concat([p]),f=R(u,[p].concat(Ro(c.slice(1))));f=Vt(f,[1,0]),f=R(f,m),n.push(f),s=!0}else if(l>1){let c=xn(1,l).concat([0]);n.push(Vt(u,c)),s=!0}else n.push(u)}let i=this.mergeFunction(n),a=i.rank;if(s){if(a==null){let u=i.shape,l=u.length,c=u[l-1],p=[c].concat(u.slice(0,u.length-1));i=R(Vt(R(i,[-1,c]),[1,0]),p)}else if(a>1){let u=[a-1].concat(xn(0,a-1));i=Vt(i,u)}}return i}}else return this.mergeFunction(t)})}computeOutputShape(t){t=t;let e;t[0]==null?e=null:e=t[0].slice(1);for(let o=1;o<t.length;++o){let s=t[o]==null?null:t[o].slice(1);e=this.computeElementwiseOpOutputShape(e,s)}let n=[];for(let o of t)o!=null&&o[0]!==null&&n.push(o[0]);return n=$o(n),n.length===1?e=n.concat(e):e=[null].concat(e),e}computeMask(t,e){return B(()=>{if(e==null)return null;if(!Array.isArray(e))throw new z("`mask` should be an Array");if(!Array.isArray(t))throw new z("`inputs` should be an Array");if(e.length!==t.length)throw new z(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${t.length} vs ${e.length})`);if(e.every(o=>o==null))return null;e=e.map(o=>o==null?o:ar(o,0));let n=e[0];for(let o=1;o<e.length-1;++o)n=Pr(n,e[o]);return n})}},Af=class extends Pl{constructor(t){super(t)}mergeFunction(t){return B(()=>{let e=t[0].clone();for(let n=1;n<t.length;++n)e=Y(e,t[n]);return e})}};Af.className="Add";J.registerClass(Af);var Df=class extends Pl{constructor(t){super(t)}mergeFunction(t){return B(()=>{let e=t[0].clone();for(let n=1;n<t.length;++n)e=$(e,t[n]);return e})}};Df.className="Multiply";J.registerClass(Df);var $f=class extends Pl{constructor(t){super(t)}mergeFunction(t){return B(()=>{let e=t[0].clone();for(let n=1;n<t.length;++n)e=Y(e,t[n]);return $(1/t.length,e)})}};$f.className="Average";J.registerClass($f);var Rf=class extends Pl{constructor(t){super(t)}mergeFunction(t){return B(()=>{let e=t[0];for(let n=1;n<t.length;++n)e=_n(e,t[n]);return e})}};Rf.className="Maximum";J.registerClass(Rf);var Ff=class extends Pl{constructor(t){super(t)}mergeFunction(t){return B(()=>{let e=t[0];for(let n=1;n<t.length;++n)e=mo(e,t[n]);return e})}};Ff.className="Minimum";J.registerClass(Ff);var Of=class extends Pl{constructor(t){super(t),this.DEFAULT_AXIS=-1,t==null&&(t={}),this.axis=t.axis==null?this.DEFAULT_AXIS:t.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(t){if(!(Array.isArray(t)&&Array.isArray(t[0]))||t.length===1)throw new z("A `Concatenate` layer should be called on a list of at least 2 inputs");t=t;let e=!0;for(let o of t)if(o!=null){e=!1;break}if(e)return;let n=[];for(let o=0;o<t.length;++o){let s=t[o].slice();s.splice(this.axis,1);let i=!1;for(let a of n)if(y.arraysEqual(a,s)){i=!0;break}i||n.push(s)}if(n.length>1)throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}mergeFunction(t){return B(()=>Pm(t,this.axis))}computeOutputShape(t){if(!(Array.isArray(t)&&Array.isArray(t[0])))throw new z("A `Concatenate` layer should be called on a list of inputs.");let e=t,n=e[0].slice(),o=this.axis<0?n.length+this.axis:this.axis;for(let s of e.slice(1)){if(n[o]==null||s[o]==null){n[o]=null;break}n[o]+=s[o]}return n}computeMask(t,e){if(e==null)return null;if(!Array.isArray(e))throw new z("`mask` should be an array for Concatenate");if(!Array.isArray(t))throw new z("`inputs` should be an array for Concatenate");if(e.length!==t.length)throw new z(`Mismatch in the length of mask (${e.length}) and the legnth of inputs (${t.length})`);return B(()=>{let n=!0;if(e.forEach(i=>{if(i!=null){n=!1;return}}),n)return null;let o=[];for(let i=0;i<t.length;++i)e[i]==null?o.push(Q(Ir(t[i]),"bool")):e[i].rank<t[i].rank?o.push(ar(e[i],-1)):o.push(e[i]);let s=ie(o,this.axis);return lm(s,-1,!1)})}getConfig(){let t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}};Of.className="Concatenate";J.registerClass(Of);function Vh(r,t){for(;r<0;)r+=t;return r}function iJ(r,t,e){if(r.shape.length>3||t.shape.length>3)throw new kt("batchDot is not implemented for tensors of 4D or higher rank yet");if(y.assert(r.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${r.shape.length}`),y.assert(r.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof e=="number"&&(e=[e,e]),r.dtype==="complex64"||t.dtype==="complex64")throw new kt("batchDot is not implemented for complex64-type Tensors yet.");let n=r.shape.length,o=t.shape.length;e==null&&(e=[n-1,o-2]);let s=e;return B(()=>{let i;if(n>o){i=n-o;let u=[];for(let l=0;l<i;++l)u.push(1);t=R(t,t.shape.concat(u))}else if(o>n){i=o-n;let u=[];for(let l=0;l<i;++l)u.push(1);r=R(r,r.shape.concat(u))}else i=0;let a;if(r.shape.length===2&&t.shape.length===2)s[0]===s[1]?a=pt($(r,t),s[0]):a=pt($(Vt(r,[1,0]),t),s[1]);else{let u=s[0]!==r.shape.length-1,l=s[1]===t.shape.length-1;a=Bt(r,t,u,l)}if(i>0){let u;n>o?u=n+o-3:u=n-1;let l=[];for(let c=u;c<u+i;++c)l.push(c);a=qn(a,l)}return a.shape.length===1&&(a=ar(a,1)),a})}var Pf=class extends Pl{constructor(t){super(t),this.axes=t.axes,this.normalize=t.normalize==null?!1:t.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(t){y.assert(Array.isArray(t)&&t.length===2&&Array.isArray(t[0])&&Array.isArray(t[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let e=t[0],n=t[1];if(e.length>3||n.length>3)throw new kt("Dot layer does not support tensors of 4D or higher rank yet.");let o=this.interpretAxes(e,n);if(e[o[0]]!==n[o[1]])throw new z(`Dimension incompatibility: ${e[o[0]]} !== ${n[o[1]]}`)}mergeFunction(t){if(t.length!==2)throw new z(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${t.length} input(s).`);let e=t[0],n=t[1],o;return Array.isArray(this.axes)?o=this.axes.map((s,i)=>Vh(s,t[i].shape.length)):o=[Vh(this.axes,e.shape.length),Vh(this.axes,n.shape.length)],this.normalize&&(e=Rh(e,o[0]),n=Rh(n,o[1])),iJ(e,n,o)}interpretAxes(t,e){let n;return Array.isArray(this.axes)?n=this.axes:n=[Vh(this.axes,t.length),Vh(this.axes,e.length)],n}computeOutputShape(t){y.assert(Array.isArray(t)&&t.length===2&&Array.isArray(t[0])&&Array.isArray(t[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let e=t[0].slice(),n=t[1].slice();if(e.length>3||n.length>3)throw new kt("Dot layer does not support tensors of 4D or higher rank yet.");let o=this.interpretAxes(e,n);e.splice(o[0],1),n.splice(o[1],1),n.splice(0,1);let s=e.concat(n);return s.length===1&&s.push(1),s}computeMask(t,e){return null}getConfig(){let t={axes:this.axes,normalize:this.normalize},e=super.getConfig();return Object.assign(t,e),t}};Pf.className="Dot";J.registerClass(Pf);var Mf=class extends _t{constructor(t){super(t),this.supportsMasking=!0,this.stddev=t.stddev}computeOutputShape(t){return t}getConfig(){let t=super.getConfig(),e={stddev:this.stddev};return Object.assign(e,t),e}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t);return Bu(()=>Y(Mm(n.shape,0,this.stddev),n),()=>n,e.training||!1)})}};Mf.className="GaussianNoise";J.registerClass(Mf);var Lf=class extends _t{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate}computeOutputShape(t){return t}getConfig(){let t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return B(()=>{this.invokeCallHook(t,e);let n=St(t);return this.rate>0&&this.rate<1?Bu(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return $(n,Mm(n.shape,1,s))},()=>n,e.training||!1):n})}};Lf.className="GaussianDropout";J.registerClass(Lf);var zf=class extends _t{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate,this.noiseShape=t.noiseShape}_getNoiseShape(t){return this.noiseShape||St(t).shape}computeOutputShape(t){return t}getConfig(){let t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return B(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(t);return Bu(()=>{let s=St(t),i=1.6732632423543772,a=1.0507009873554805,u=-i*a,l=mn(Hn(n),this.rate);l=rn(l,"float32");let c=((1-this.rate)*(1+this.rate*u**2))**-.5,p=-c*u*this.rate,m=Y($(s,l),$(Y(l,-1),u));return Y($(m,c),p)},()=>St(t),e.training||!1)}return t})}};zf.className="AlphaDropout";J.registerClass(zf);function Gh(r,t,e,n,o,s=.001){let i;if(r.rank===2)i=Sx(r,t,e,n,o,s);else if(r.rank===3)i=Nx(r,t,e,n,o,s);else if(r.rank===4)i=kx(r,t,e,n,o,s);else throw new kt(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return i}function aJ(r,t,e,n,o=.001){return B(()=>{let s=vc(r,n),i=s.mean,a=s.variance;return[Gh(r,i,a,e,t,o),i,a]})}function lJ(r,t,e,n,o=.001){return B(()=>{let s=vc(r,n),i=s.mean,a=s.variance,u=[];for(let d of xn(0,r.rank))n.indexOf(d)!==-1?u.push(1):u.push(r.shape[d]);let l=R(i,u),c=R(a,u),p=t==null?null:R(t,u),m=e==null?null:R(e,u);return[Gh(r,l,c,m,p,o),i,a]})}function uJ(r,t,e,n,o=.001){return y.arraysEqual(n.slice().sort(),xn(0,r.rank-1))?aJ(r,t,e,n,o):lJ(r,t,e,n,o)}var Bf=class extends _t{constructor(t){t==null&&(t={}),super(t),this.supportsMasking=!0,this.axis=t.axis==null?-1:t.axis,this.momentum=t.momentum==null?.99:t.momentum,this.epsilon=t.epsilon==null?.001:t.epsilon,this.center=t.center==null?!0:t.center,this.scale=t.scale==null?!0:t.scale,this.betaInitializer=he(t.betaInitializer||"zeros"),this.gammaInitializer=he(t.gammaInitializer||"ones"),this.movingMeanInitializer=he(t.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=he(t.movingVarianceInitializer||"ones"),this.betaConstraint=Ve(t.betaConstraint),this.gammaConstraint=Ve(t.gammaConstraint),this.betaRegularizer=Ce(t.betaRegularizer),this.gammaRegularizer=Ce(t.gammaRegularizer)}build(t){t=Gt(t);let e=this.axis>=0?this.axis:this.axis+t.length,n=t[e];if(n==null)throw new z(`Axis ${e} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(t)}.`);this.inputSpec=[new Ie({ndim:t.length,axes:{[e]:n}})];let o=[n];this.scale&&(this.gamma=this.addWeight("gamma",o,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",o,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",o,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",o,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(t,e){return B(()=>{let n=e.training==null?!1:e.training,o=St(t),s=o.shape,i=s.length,a=xn(0,i),u=this.axis>=0?this.axis:this.axis+i;a.splice(u,1);let l=Ao(1,i);l[u]=s[u];let c=a.slice();c.sort();let p=!y.arraysEqual(c,xn(0,i).slice(0,i-1)),m=()=>{if(p){let b=R(this.movingMean.read(),l),w=R(this.movingVariance.read(),l),I=this.center?R(this.beta.read(),l):null,N=this.scale?R(this.gamma.read(),l):null;return Gh(o,b,w,I,N,this.epsilon)}else return Gh(o,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return m();let[f,d,h]=uJ(o,this.gamma.read(),this.beta.read(),a,this.epsilon),g=(b,w,I)=>{B(()=>{let N=1-I,E=b.read(),A=$(lt(E,w),N);b.write(lt(E,A))})};return(()=>{g(this.movingMean,d,this.momentum),g(this.movingVariance,h,this.momentum)})(),f})}getConfig(){let t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_e(this.betaInitializer),gammaInitializer:_e(this.gammaInitializer),movingMeanInitializer:_e(this.movingMeanInitializer),movingVarianceInitializer:_e(this.movingVarianceInitializer),betaRegularizer:me(this.betaRegularizer),gammaRegularizer:me(this.gammaRegularizer),betaConstraint:Be(this.betaConstraint),gammaConstraint:Be(this.gammaConstraint)},e=super.getConfig();return Object.assign(t,e),t}};Bf.className="BatchNormalization";J.registerClass(Bf);var Vf=class extends _t{constructor(t){if(t==null&&(t={}),super(t),this.axis=t.axis==null?-1:t.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=t.epsilon==null?.001:t.epsilon,this.center=t.center==null?!0:t.center,this.scale=t.scale==null?!0:t.scale,this.betaInitializer=he(t.betaInitializer||"zeros"),this.gammaInitializer=he(t.gammaInitializer||"ones"),this.betaRegularizer=Ce(t.betaRegularizer),this.gammaRegularizer=Ce(t.gammaRegularizer),this.supportsMasking=!0}build(t){t=Gt(t);let e=t.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let s=0;s<this.axis.length;++s)this.axis[s]<0&&(this.axis[s]+=e);for(let s of this.axis)if(s<0||s>=e)throw new Error(`Invalid axis: ${s}`);if(this.axis.length!==$o(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(s=>t[s]),o=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,o):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,o):this.beta=null,this.built=!0}call(t,e){let n=St(t),o=n.shape,s=o.length;return B(()=>{let{mean:a,variance:u}=vc(n,this.axis,!0),l=Ao(1,s);for(let h of this.axis)l[h]=o[h];let c=h=>h!=null&&h.shape.length!==s?R(h,l):h,p=this.scale?c(this.gamma.read()):null,m=this.center?c(this.beta.read()):null,f=[],d=[];for(let h=0;h<s;++h)this.axis.indexOf(h)!==-1?(f.push(o[h]),d.push(1)):(f.push(1),d.push(o[h]));return a=Or(a,f),u=Or(u,f),p!=null&&(p=Or(p,d)),m!=null&&(m=Or(m,d)),Gh(n,a,u,m,p,this.epsilon)})}getConfig(){let t={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_e(this.betaInitializer),gammaInitializer:_e(this.gammaInitializer),betaRegularizer:me(this.betaRegularizer),gammaRegularizer:me(this.gammaRegularizer)},e=super.getConfig();return Object.assign(t,e),t}};Vf.className="LayerNormalization";J.registerClass(Vf);function cJ(r,t,e){return B(()=>{if(r.rank!==4)throw new z(`temporalPadding expects input tensor to be 4-D, but received a ${r.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(e==null&&(e=yn()),e!=="channelsLast"&&e!=="channelsFirst")throw new z(`Unknown data format: ${e}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return e==="channelsFirst"?n=[[0,0],[0,0],t[0],t[1]]:n=[[0,0],t[0],t[1],[0,0]],dn(r,n)})}var Gf=class extends _t{constructor(t){if(t==null&&(t={}),super(t),this.dataFormat=t.dataFormat==null?yn():t.dataFormat,t.padding==null)this.padding=[[1,1],[1,1]];else if(typeof t.padding=="number")this.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,t.padding.length!==2)throw new z(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${t.padding.length} array.`);let e,n;if(typeof t.padding[0]=="number")e=[t.padding[0],t.padding[0]],n=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,t.padding[0].length!==2)throw new z(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${t.padding[0].length} array.`);if(e=t.padding[0],t.padding[1].length!==2)throw new z(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${t.padding[1].length} array.`);n=t.padding[1]}this.padding=[e,n]}this.inputSpec=[new Ie({ndim:4})]}computeOutputShape(t){t=Gt(t);let e,n;return this.dataFormat==="channelsFirst"?(t[2]!=null&&t[2]>=0?e=t[2]+this.padding[0][0]+this.padding[0][1]:e=null,t[3]!=null&&t[3]>=0?n=t[3]+this.padding[1][0]+this.padding[1][1]:n=null,[t[0],t[1],e,n]):(t[1]!=null&&t[1]>=0?e=t[1]+this.padding[0][0]+this.padding[0][1]:e=null,t[2]!=null&&t[2]>=0?n=t[2]+this.padding[1][0]+this.padding[1][1]:n=null,[t[0],e,n,t[3]])}call(t,e){return B(()=>cJ(St(t),this.padding,this.dataFormat))}getConfig(){let t={padding:this.padding,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}};Gf.className="ZeroPadding2D";J.registerClass(Gf);function Fb(r,t,e,n,o,s){return B(()=>{Oe(o),RN(s),gn(n),e==null&&(e=[1,1]),n==null&&(n="valid"),o==null&&(o=yn()),s==null&&(s="max"),r=Bh(r,o);let i,a=n==="same"?"same":"valid";return s==="max"?i=Du(r,t,e,a):i=Su(r,t,e,a),o==="channelsFirst"&&(i=Vt(i,[0,3,1,2])),i})}function BR(r,t,e,n,o,s){return B(()=>{Oe(o),RN(s),gn(n),e==null&&(e=[1,1,1]),n==null&&(n="valid"),o==null&&(o=yn()),s==null&&(s="max"),r=YN(r,o);let i,a=n==="same"?"same":"valid";return s==="max"?i=Jx(r,t,e,a):i=vx(r,t,e,a),o==="channelsFirst"&&(i=Vt(i,[0,4,1,2,3])),i})}var Eb=class extends _t{constructor(t){if(t.poolSize==null&&(t.poolSize=2),super(t),typeof t.poolSize=="number")this.poolSize=[t.poolSize];else if(Array.isArray(t.poolSize)&&t.poolSize.length===1&&typeof t.poolSize[0]=="number")this.poolSize=t.poolSize;else throw new z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.poolSize)}`);if(Qe(this.poolSize,"poolSize"),t.strides==null)this.strides=this.poolSize;else if(typeof t.strides=="number")this.strides=[t.strides];else if(Array.isArray(t.strides)&&t.strides.length===1&&typeof t.strides[0]=="number")this.strides=t.strides;else throw new z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.strides)}`);Qe(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,gn(this.padding),this.inputSpec=[new Ie({ndim:3})]}computeOutputShape(t){t=Gt(t);let e=An(t[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]}call(t,e){return B(()=>{this.invokeCallHook(t,e),t=_l(St(t),2);let n=this.poolingFunction(St(t),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return qn(n,[2])})}getConfig(){let t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},e=super.getConfig();return Object.assign(t,e),t}},Wf=class extends Eb{constructor(t){super(t)}poolingFunction(t,e,n,o,s){return Oe(s),gn(o),Fb(t,e,n,o,s,"max")}};Wf.className="MaxPooling1D";J.registerClass(Wf);var Uf=class extends Eb{constructor(t){super(t)}poolingFunction(t,e,n,o,s){return Oe(s),gn(o),Fb(t,e,n,o,s,"avg")}};Uf.className="AveragePooling1D";J.registerClass(Uf);var Ab=class extends _t{constructor(t){if(t.poolSize==null&&(t.poolSize=[2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],t.strides==null)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(t.strides.length!==2)throw new z(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides];Qe(this.poolSize,"poolSize"),Qe(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Oe(this.dataFormat),gn(this.padding),this.inputSpec=[new Ie({ndim:4})]}computeOutputShape(t){t=Gt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],n=this.dataFormat==="channelsFirst"?t[3]:t[2];return e=An(e,this.poolSize[0],this.padding,this.strides[0]),n=An(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[t[0],t[1],e,n]:[t[0],e,n,t[3]]}call(t,e){return B(()=>(this.invokeCallHook(t,e),this.poolingFunction(St(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}},Hf=class extends Ab{constructor(t){super(t)}poolingFunction(t,e,n,o,s){return Oe(s),gn(o),Fb(t,e,n,o,s,"max")}};Hf.className="MaxPooling2D";J.registerClass(Hf);var qf=class extends Ab{constructor(t){super(t)}poolingFunction(t,e,n,o,s){return Oe(s),gn(o),Fb(t,e,n,o,s,"avg")}};qf.className="AveragePooling2D";J.registerClass(qf);var Db=class extends _t{constructor(t){if(t.poolSize==null&&(t.poolSize=[2,2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],t.strides==null)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(t.strides.length!==3)throw new z(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides,t.strides];Qe(this.poolSize,"poolSize"),Qe(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Oe(this.dataFormat),gn(this.padding),this.inputSpec=[new Ie({ndim:5})]}computeOutputShape(t){t=Gt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],n=this.dataFormat==="channelsFirst"?t[3]:t[2],o=this.dataFormat==="channelsFirst"?t[4]:t[3];return e=An(e,this.poolSize[0],this.padding,this.strides[0]),n=An(n,this.poolSize[1],this.padding,this.strides[1]),o=An(o,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[t[0],t[1],e,n,o]:[t[0],e,n,o,t[4]]}call(t,e){return B(()=>(this.invokeCallHook(t,e),this.poolingFunction(St(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}},Kf=class extends Db{constructor(t){super(t)}poolingFunction(t,e,n,o,s){return Oe(s),gn(o),BR(t,e,n,o,s,"max")}};Kf.className="MaxPooling3D";J.registerClass(Kf);var jf=class extends Db{constructor(t){super(t)}poolingFunction(t,e,n,o,s){return Oe(s),gn(o),BR(t,e,n,o,s,"avg")}};jf.className="AveragePooling3D";J.registerClass(jf);var $b=class extends _t{constructor(t){super(t),this.inputSpec=[new Ie({ndim:3})]}computeOutputShape(t){return[t[0],t[2]]}call(t,e){throw new kt}},Xf=class extends $b{constructor(t){super(t||{})}call(t,e){return B(()=>{let n=St(t);return ke(n,1)})}};Xf.className="GlobalAveragePooling1D";J.registerClass(Xf);var Yf=class extends $b{constructor(t){super(t||{})}call(t,e){return B(()=>{let n=St(t);return Nr(n,1)})}};Yf.className="GlobalMaxPooling1D";J.registerClass(Yf);var Rb=class extends _t{constructor(t){super(t),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Oe(this.dataFormat),this.inputSpec=[new Ie({ndim:4})]}computeOutputShape(t){return t=t,this.dataFormat==="channelsLast"?[t[0],t[3]]:[t[0],t[1]]}call(t,e){throw new kt}getConfig(){let t={dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}},Zf=class extends Rb{call(t,e){return B(()=>{let n=St(t);return this.dataFormat==="channelsLast"?ke(n,[1,2]):ke(n,[2,3])})}};Zf.className="GlobalAveragePooling2D";J.registerClass(Zf);var Jf=class extends Rb{call(t,e){return B(()=>{let n=St(t);return this.dataFormat==="channelsLast"?Nr(n,[1,2]):Nr(n,[2,3])})}};Jf.className="GlobalMaxPooling2D";J.registerClass(Jf);var Ob=class extends _t{constructor(t){super(t),this.layer=t.layer}build(t){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(t){this.layer!=null&&(this.layer.trainable=t)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(t){this.layer.setWeights(t)}getConfig(){let t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},e=super.getConfig();return Object.assign(t,e),t}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(t)}static fromConfig(t,e,n={}){let o=e.layer,s=Cn(o,n);delete e.layer;let i={layer:s};return Object.assign(i,e),new t(i)}},Qf=class extends Ob{constructor(t){super(t),this.supportsMasking=!0}build(t){if(t=Gt(t),t.length<3)throw new z(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(t)}`);this.inputSpec=[{shape:t}];let e=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(e),this.layer.built=!0),super.build(t)}computeOutputShape(t){t=Gt(t);let e=[t[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),o=t[1];return[n[0],o].concat(n.slice(1))}call(t,e){return B(()=>(t=St(t),JN((i,a)=>[St(this.layer.call(i,e)),[]],t,[],!1,null,null,!1,!0)[1]))}};Qf.className="TimeDistributed";J.registerClass(Qf);function pJ(r){ya(q$,"BidirectionalMergeMode",r)}var mJ="concat",td=class extends Ob{constructor(t){super(t);let e=t.layer.getConfig(),n={};n.className=t.layer.getClassName(),n.config=e,this.forwardLayer=Cn(n),e.goBackwards=e.goBackwards!==!0;let o={};if(o.className=t.layer.getClassName(),o.config=e,this.backwardLayer=Cn(o),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=t.mergeMode===void 0?mJ:t.mergeMode,pJ(this.mergeMode),t.weights)throw new kt("weights support is not implemented for Bidirectional layer yet.");this._stateful=t.layer.stateful,this.returnSequences=t.layer.returnSequences,this.returnState=t.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=t.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(t){this._trainable=t,this.forwardLayer!=null&&(this.forwardLayer.trainable=t),this.backwardLayer!=null&&(this.backwardLayer.trainable=t)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(t){let e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))}computeOutputShape(t){let e=this.forwardLayer.computeOutputShape(t);Array.isArray(e)&&Array.isArray(e[0])||(e=[e]),e=e;let n,o,s;return this.returnState&&(s=e.slice(1)),n=e[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,o=[n]):this.mergeMode==null?o=[n,n.slice()]:o=[n],this.returnState?this.mergeMode==null?o.concat(s).concat(s.slice()):[n].concat(s).concat(s.slice()):Tr(o)}apply(t,e){let n=e==null?null:e.initialState,o=e==null?null:e.constants;e==null&&(e={});let s=ZN(t,n,o,this.numConstants);if(t=s.inputs,n=s.initialState,o=s.constants,Array.isArray(t)&&(n=t.slice(1),t=t[0]),(n==null||n.length===0)&&o==null)return super.apply(t,e);let i=[],a=[];if(n!=null){let l=n.length;if(l%2>0)throw new z("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");e.initialState=n,i.push(...n);let c=n.map(p=>new Ie({shape:p.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),a.push(...c)}if(o!=null)throw new kt("Support for constants in Bidirectional layers is not implemented yet.");let u=i[0]instanceof nn;for(let l of i)if(l instanceof nn!==u)throw new z("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(u){let l=[t].concat(i),c=this.inputSpec.concat(a),p=this.inputSpec;this.inputSpec=c;let m=super.apply(l,e);return this.inputSpec=p,m}else return super.apply(t,e)}call(t,e){return B(()=>{let n=e.initialState,o,s;if(n==null)o=this.forwardLayer.call(t,e),s=this.backwardLayer.call(t,e);else{let u=n.slice(0,n.length/2),l=n.slice(n.length/2);o=this.forwardLayer.call(t,Object.assign(e,{initialState:u})),s=this.backwardLayer.call(t,Object.assign(e,{initialState:l}))}let i;this.returnState&&(Array.isArray(o)&&(i=o.slice(1).concat(s.slice(1))),o=o[0],s=s[0]),this.returnSequences&&(s=hr(s,1));let a;return this.mergeMode==="concat"?a=Pm([o,s]):this.mergeMode==="sum"?a=Y(o,s):this.mergeMode==="ave"?a=$(.5,Y(o,s)):this.mergeMode==="mul"?a=$(o,s):this.mergeMode==null&&(a=[o,s]),this.returnState?this.mergeMode==null?a.concat(i):[a].concat(i):a})}resetStates(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(t){hi(this.forwardLayer.name,()=>{this.forwardLayer.build(t)}),hi(this.backwardLayer.name,()=>{this.backwardLayer.build(t)}),this.built=!0}computeMask(t,e){Array.isArray(e)&&(e=e[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[e,e]:n=e:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let s=this.forwardLayer.states.map(i=>null);return Array.isArray(n)?n.concat(s).concat(s):[n].concat(s).concat(s)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(t),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(t)}getConfig(){let t={mergeMode:this.mergeMode},e=super.getConfig();return Object.assign(t,e),t}static fromConfig(t,e){let n=Cn(e.layer);if(delete e.layer,e.numConstants!=null)throw new kt("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let o=e;return o.layer=n,new t(o)}};td.className="Bidirectional";J.registerClass(td);var ed=class extends _t{constructor(t){super(t),this.scale=t.scale,t.offset?this.offset=t.offset:this.offset=0}getConfig(){let t={scale:this.scale,offset:this.offset},e=super.getConfig();return Object.assign(t,e),t}call(t,e){return B(()=>(t=St(t),t.dtype!=="float32"&&(t=rn(t,"float32")),Y($(t,this.scale),this.offset)))}};ed.className="Rescaling";J.registerClass(ed);var{resizeBilinear:fJ,cropAndResize:dJ}=hn,rd=class extends _t{constructor(t){super(t),this.height=t.height,this.width=t.width}centerCrop(t,e,n,o,s,i,a,u){return B(()=>{let l,c=!1,p=e/i,m=n/a,f=(o+e)/i,d=(s+n)/a,h=[p,m,f,d],g=[];t.rank===3?(c=!0,l=qe([t])):l=t;for(let N=0;N<l.shape[0];N++)g.push(h);let x=sr(g,[g.length,4]),b=da(0,g.length,1,"int32"),I=dJ(l,x,b,[o,s],"nearest");return c?rn(St(xr(I)),u):rn(I,u)})}upsize(t,e,n,o){return B(()=>{let s=fJ(t,[e,n]);return rn(s,o)})}call(t,e){return B(()=>{let n=St(t),o=n.dtype,s=n.shape,i=s[s.length-3],a=s[s.length-2],u=0;i!==this.height&&(u=Math.floor((i-this.height)/2));let l=0;return a!==this.width&&(l=Math.floor((a-this.width)/2),l===0&&(l=1)),u>=0&&l>=0?this.centerCrop(n,u,l,this.height,this.width,i,a,o):this.upsize(t,this.height,this.width,o)})}getConfig(){let t={height:this.height,width:this.width},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){t=Gt(t);let e=t.length-3,n=t.length-2;return t[e]=this.height,t[n]=this.width,t}};rd.className="CenterCrop";J.registerClass(rd);function VR(r,t,e,n){let o=St(r);if(o.dtype!=="int32"&&(o=rn(o,"int32")),t==="int")return o;let s=o.shape;if(o.rank===0&&(o=ar(o,-1)),t==="oneHot"&&o.shape[o.shape.length-1]!==1&&(o=ar(o,-1)),o.rank>2)throw new z(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${s} which would result in output rank ${o.rank}.`);let i=["multiHot","oneHot"].includes(t),a=o,u;if(typeof n!="undefined"&&t==="count"?u=gh(a,n,e,i):u=gh(a,[],e,i),t!=="tfIdf")return u;if(n)return $(u,n);throw new z("When outputMode is 'tfIdf', weights must be provided.")}var nd=class extends _t{constructor(t){super(t),this.numTokens=t.numTokens,t.outputMode?this.outputMode=t.outputMode:this.outputMode="multiHot"}getConfig(){let t={numTokens:this.numTokens,outputMode:this.outputMode},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){return t=Gt(t),t==null?[this.numTokens]:this.outputMode==="oneHot"&&t[t.length-1]!==1?(t.push(this.numTokens),t):(t[t.length-1]=this.numTokens,t)}call(t,e){return B(()=>{t=St(t),t.dtype!=="int32"&&(t=rn(t,"int32"));let n;if(typeof e.countWeights!="undefined"){if(this.outputMode!=="count")throw new z(`countWeights is not used when outputMode !== count.
| Received countWeights=${e.countWeights}`);n=St(e.countWeights)}let o=Nr(t),s=bl(t),i=Fe(this.numTokens,o).bufferSync().get(0),a=mn(s,0).bufferSync().get(0);if(!(i&&a))throw new z(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return VR(t,this.outputMode,this.numTokens,n)})}};nd.className="CategoryEncoding";J.registerClass(nd);var gJ=["bilinear","nearest"],GR=new Set(gJ),od=class extends _t{constructor(t){if(super(t),this.height=t.height,this.width=t.width,t.interpolation)if(GR.has(t.interpolation))this.interpolation=t.interpolation;else throw new z(`Invalid interpolation parameter: ${t.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!t.cropToAspectRatio}computeOutputShape(t){t=Gt(t);let e=t[2];return[this.height,this.width,e]}getConfig(){let t={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},e=super.getConfig();return Object.assign(t,e),t}call(t,e){return B(()=>{let n=[this.height,this.width];if(this.interpolation==="bilinear")return hn.resizeBilinear(t,n,!this.cropToAspectRatio);if(this.interpolation==="nearest")return hn.resizeNearestNeighbor(t,n,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...GR]} are supported`)})}};od.className="Resizing";J.registerClass(od);var Wh=class{constructor(t){this.seed=t}next(){if(this.seed!==void 0)return this.seed++}};Wh.className="RandomSeed";var Uh=class extends _t{constructor(t){super(t),this.randomGenerator=new Wh(t.seed)}getConfig(){let t={seed:this.randomGenerator.seed},e=super.getConfig();return Object.assign(t,e),t}};Uh.className="BaseRandomLayer";var xJ=["bilinear","nearest"],WR=new Set(xJ),sd=class extends Uh{constructor(t){super(t);let{factor:e,interpolation:n="bilinear"}=t;if(this.factor=e,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new z(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new z(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new z(`factor cannot have upper bound less than lower bound.
| Got upper bound: ${this.widthUpper}.
| Got lower bound: ${this.widthLower}
| `);if(n)if(WR.has(n))this.interpolation=n;else throw new z(`Invalid interpolation parameter: ${n} is not implemented`)}getConfig(){let t={factor:this.factor,interpolation:this.interpolation},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){t=Gt(t);let e=t[2];return[this.imgHeight,-1,e]}call(t,e){return B(()=>{let n=St(t);this.imgHeight=n.shape[n.shape.length-3];let o=n.shape[n.shape.length-2];this.widthFactor=Hn([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let s=this.widthFactor.dataSync()[0]*o;s=Math.round(s);let i=[this.imgHeight,s];switch(this.interpolation){case"bilinear":return hn.resizeBilinear(t,i);case"nearest":return hn.resizeNearestNeighbor(t,i);default:throw new Error(`Interpolation is ${this.interpolation}
| but only ${[...WR]} are supported`)}})}};sd.className="RandomWidth";J.registerClass(sd);function yJ(r){return new xi(r)}function bJ(r){return new lf(r)}function wJ(r){return new of(r)}function IJ(r){return new sf(r)}function CJ(r){return new af(r)}function vJ(r){return new cf(r)}function SJ(r){return new uf(r)}function NJ(r){return new qu(r)}function kJ(r){return new Dl(r)}function TJ(r){return new pf(r)}function _J(r){return new $l(r)}function EJ(r){return new mf(r)}function AJ(r){return new ff(r)}function DJ(r){return new df(r)}function $J(r){return new hf(r)}function RJ(r){return new gf(r)}function FJ(r){return new Sf(r)}function OJ(r){return new Cf(r)}function PJ(r){return new np(r)}function MJ(r){return new If(r)}function LJ(r){return new vf(r)}function zJ(r){return new Nf(r)}function BJ(r){return new kf(r)}function VJ(r){return new Tf(r)}function GJ(r){return new Ef(r)}function WJ(r){return new Af(r)}function UJ(r){return new $f(r)}function HJ(r){return new Of(r)}function qJ(r){return new Rf(r)}function KJ(r){return new Ff(r)}function jJ(r){return new Df(r)}function XJ(r){return new Pf(r)}function YJ(r){return new Bf(r)}function ZJ(r){return new Vf(r)}function JJ(r){return new Gf(r)}function QN(r){return new Uf(r)}function QJ(r){return QN(r)}function t9(r){return QN(r)}function tk(r){return new qf(r)}function e9(r){return tk(r)}function r9(r){return tk(r)}function ek(r){return new jf(r)}function n9(r){return ek(r)}function o9(r){return ek(r)}function s9(r){return new Xf(r)}function i9(r){return new Zf(r)}function UR(r){return new Yf(r)}function HR(r){return new Jf(r)}function qR(r){return new Wf(r)}function KR(r){return new Hf(r)}function a9(r){return new Kf(r)}function l9(r){return new yf(r)}function u9(r){return new tp(r)}function c9(r){return new bf(r)}function p9(r){return new Fl(r)}function m9(r){return new xf(r)}function f9(r){return new Qc(r)}function d9(r){return new wf(r)}function h9(r){return new rp(r)}function g9(r){return new Dn(r)}function x9(r){return new ep(r)}function y9(r){return new td(r)}function b9(r){return new Qf(r)}var w9=UR,I9=HR,C9=qR,v9=KR;function S9(r){return new Mf(r)}function N9(r){return new Lf(r)}function k9(r){return new zf(r)}function T9(r){return new _f(r)}function _9(r){return new ed(r)}function E9(r){return new rd(r)}function A9(r){return new od(r)}function D9(r){return new nd(r)}function $9(r){return new sd(r)}var XR={};Kt(XR,{MAPE:()=>W9,MSE:()=>q9,binaryAccuracy:()=>R9,binaryCrossentropy:()=>F9,categoricalAccuracy:()=>P9,categoricalCrossentropy:()=>M9,cosineProximity:()=>B9,mape:()=>U9,meanAbsoluteError:()=>V9,meanAbsolutePercentageError:()=>G9,meanSquaredError:()=>H9,mse:()=>K9,precision:()=>L9,recall:()=>z9,sparseCategoricalAccuracy:()=>O9});function R9(r,t){return Ph(r,t)}function F9(r,t){return nb(r,t)}function O9(r,t){return ob(r,t)}function P9(r,t){return Mh(r,t)}function M9(r,t){return Lh(r,t)}function L9(r,t){return VN(r,t)}function z9(r,t){return yR(r,t)}function B9(r,t){return Oh(r,t)}function V9(r,t){return Jm(r,t)}function G9(r,t){return Gu(r,t)}function W9(r,t){return Gu(r,t)}function U9(r,t){return Gu(r,t)}function H9(r,t){return wa(r,t)}function q9(r,t){return wa(r,t)}function K9(r,t){return wa(r,t)}var YR={};Kt(YR,{modelFromJSON:()=>RR});var ZR={};Kt(ZR,{l1:()=>X9,l1l2:()=>j9,l2:()=>Y9});function j9(r){return new Wu(r)}function X9(r){return MR(r)}function Y9(r){return LR(r)}var Mb=class extends Al{constructor(){super(...arguments),this.model=null}setModel(t){if(!(t instanceof jn))throw new Error("model must be a LayersModel, not some other Container");this.model=t}};function Pb(r,t){return r<t}function JR(r,t){return r>t}var Lb=class extends Mb{constructor(t){if(super(),t==null&&(t={}),t.restoreBestWeights)throw new kt("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=t.monitor||"val_loss",this.minDelta=Math.abs(t.minDelta||0),this.patience=t.patience||0,this.verbose=t.verbose||0,this.mode=t.mode||"auto",this.baseline=t.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Pb:this.mode==="max"?this.monitorFunc=JR:this.monitor.indexOf("acc")!==-1?this.monitorFunc=JR:this.monitorFunc=Pb,this.monitorFunc===Pb&&(this.minDelta*=-1)}async onTrainBegin(t){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Pb?1/0:-1/0}async onEpochEnd(t,e){await ba(e);let n=this.getMonitorValue(e);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=t,this.model.stopTraining=!0)))}async onTrainEnd(t){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(t){t==null&&(t={});let e=t[this.monitor];return e==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(t)}`),e}};function Z9(r){return new Lb(r)}var J9={earlyStopping:Z9};var Q9=L();Q9.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,r=>{r&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});var ho;(function(r){r[r.DT_INVALID=0]="DT_INVALID",r[r.DT_FLOAT=1]="DT_FLOAT",r[r.DT_DOUBLE=2]="DT_DOUBLE",r[r.DT_INT32=3]="DT_INT32",r[r.DT_UINT8=4]="DT_UINT8",r[r.DT_INT16=5]="DT_INT16",r[r.DT_INT8=6]="DT_INT8",r[r.DT_STRING=7]="DT_STRING",r[r.DT_COMPLEX64=8]="DT_COMPLEX64",r[r.DT_INT64=9]="DT_INT64",r[r.DT_BOOL=10]="DT_BOOL",r[r.DT_QINT8=11]="DT_QINT8",r[r.DT_QUINT8=12]="DT_QUINT8",r[r.DT_QINT32=13]="DT_QINT32",r[r.DT_BFLOAT16=14]="DT_BFLOAT16",r[r.DT_QINT16=15]="DT_QINT16",r[r.DT_QUINT16=16]="DT_QUINT16",r[r.DT_UINT16=17]="DT_UINT16",r[r.DT_COMPLEX128=18]="DT_COMPLEX128",r[r.DT_HALF=19]="DT_HALF",r[r.DT_RESOURCE=20]="DT_RESOURCE",r[r.DT_VARIANT=21]="DT_VARIANT",r[r.DT_UINT32=22]="DT_UINT32",r[r.DT_UINT64=23]="DT_UINT64",r[r.DT_FLOAT_REF=101]="DT_FLOAT_REF",r[r.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",r[r.DT_INT32_REF=103]="DT_INT32_REF",r[r.DT_UINT8_REF=104]="DT_UINT8_REF",r[r.DT_INT16_REF=105]="DT_INT16_REF",r[r.DT_INT8_REF=106]="DT_INT8_REF",r[r.DT_STRING_REF=107]="DT_STRING_REF",r[r.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",r[r.DT_INT64_REF=109]="DT_INT64_REF",r[r.DT_BOOL_REF=110]="DT_BOOL_REF",r[r.DT_QINT8_REF=111]="DT_QINT8_REF",r[r.DT_QUINT8_REF=112]="DT_QUINT8_REF",r[r.DT_QINT32_REF=113]="DT_QINT32_REF",r[r.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",r[r.DT_QINT16_REF=115]="DT_QINT16_REF",r[r.DT_QUINT16_REF=116]="DT_QUINT16_REF",r[r.DT_UINT16_REF=117]="DT_UINT16_REF",r[r.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",r[r.DT_HALF_REF=119]="DT_HALF_REF",r[r.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",r[r.DT_VARIANT_REF=121]="DT_VARIANT_REF",r[r.DT_UINT32_REF=122]="DT_UINT32_REF",r[r.DT_UINT64_REF=123]="DT_UINT64_REF"})(ho||(ho={}));var QR;(function(r){let t;(function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"})(t=r.CheckpointFormatVersion||(r.CheckpointFormatVersion={}))})(QR||(QR={}));var rk={};function eQ(r,t){let e={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:t};rk[r]=e}function zb(r){return rk[r]}function rQ(r){delete rk[r]}function v(r,t,e,n,o){let s=t.inputParams[r];if(s&&s.inputIndexStart!==void 0){let a=s.inputIndexStart,u=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?a+1:s.inputIndexEnd,l=a<0?t.inputNames.length+a:a;if(s.type==="tensor")return pr(t.inputNames[l],e,n,o);if(s.type==="tensors"){let m=t.inputs.slice(a,u);return t.inputNames.slice(a,u).filter((d,h)=>{var g;return((g=m[h])===null||g===void 0?void 0:g.op)!=="NoOp"}).map(d=>pr(d,e,n,o))}let c=pr(t.inputNames[l],e,n,o),p=c.dataSync();return s.type==="number"?p[0]:y.toNestedArray(c.shape,p)}let i=t.attrParams[r];return i&&i.value}function pr(r,t,e,n){let[o,s]=vn(r,e);if(n!=null){let a=n.getHashTableHandleByName(o);if(a!=null)return a}let i=e.currentContextIds.find(a=>!!t[Bb(o,a)]);return i!==void 0?t[Bb(o,i)][s]:void 0}function nk(r,t,e){return t[Bb(r,e.currentContextId)]}function Ii(r,t){let[e,n,o]=vn(r,t);return[Bb(e,t&&t.currentContextId),n,o]}function Bb(r,t){return t?`${r}-${t}`:r}function vn(r,t){if(r==="")return["",0,void 0];let e=t!=null&&t.parseNodeNameCache!=null;if(e){let s=t.parseNodeNameCache.get(r);if(s!=null)return s}let n=r.split(":"),o;if(n.length===1)o=[r,0,void 0];else{let s=n[0],i=n.length===3?n[1]:void 0,a=Number(n[n.length-1]);o=[s,a,i]}return e&&t.parseNodeNameCache.set(r,o),o}function Hh(r,t,e){let n=v("pad",r,t,e);if(n==="explicit"){n=v("explicitPaddings",r,t,e);let o=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)o[s][0]=n[s*2],o[s][1]=n[s*2+1];return o}return n}function Ci(r){return r.kept?r:cn(r)}var ok={};Kt(ok,{json:()=>nQ});var nQ=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var sk={};Kt(sk,{json:()=>oQ});var oQ=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var ik={};Kt(ik,{json:()=>sQ});var sQ=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}];var ak={};Kt(ak,{json:()=>iQ});var iQ=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];var lk={};Kt(lk,{json:()=>aQ});var aQ=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];var uk={};Kt(uk,{json:()=>lQ});var lQ=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var ck={};Kt(ck,{json:()=>uQ});var uQ=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];var pk={};Kt(pk,{json:()=>cQ});var cQ=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];var mk={};Kt(mk,{json:()=>pQ});var pQ=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}];var fk={};Kt(fk,{json:()=>mQ});var mQ=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}];var dk={};Kt(dk,{json:()=>fQ});var fQ=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}];var hk={};Kt(hk,{json:()=>dQ});var dQ=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}];var gk={};Kt(gk,{json:()=>hQ});var hQ=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}];var xk={};Kt(xk,{json:()=>gQ});var gQ=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];var yk={};Kt(yk,{json:()=>xQ});var xQ=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}];var bk={};Kt(bk,{json:()=>yQ});var yQ=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}];var wk={};Kt(wk,{json:()=>bQ});var bQ=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}];var Ik={};Kt(Ik,{json:()=>wQ});var wQ=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}];var Ck={};Kt(Ck,{json:()=>IQ});var IQ=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}];var qh=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let t=[ok,sk,ik,ak,lk,uk,ck,pk,mk,fk,dk,hk,gk,xk,yk,bk,wk,Ik,Ck],e=[].concat(...t.map(n=>n.json));this.opMappers=e.reduce((n,o)=>(n[o.tfOpName]=o,n),{})}transformGraph(t,e={}){let n=t.node,o=[],s=[],i=[],a=n.reduce((h,g)=>(h[g.name]=this.mapNode(g),g.op.startsWith("Placeholder")?o.push(h[g.name]):g.op==="Const"?s.push(h[g.name]):(g.input==null||g.input.length===0)&&i.push(h[g.name]),h),{}),u=[],l=[],c={},p={};e!=null&&(c=this.mapSignatureEntries(e.inputs),p=this.mapSignatureEntries(e.outputs));let m=Object.keys(a);m.forEach(h=>{let g=a[h];g.inputNames.forEach((x,b)=>{let[w,,I]=Ii(x),N=a[w];if(N.outputs!=null){let E=N.outputs.indexOf(I);if(E!==-1){let A=`${w}:${E}`;g.inputNames[b]=A}}g.inputs.push(N),N.children.push(g)})}),Object.keys(p).length===0?m.forEach(h=>{let g=a[h];g.children.length===0&&l.push(g)}):Object.keys(p).forEach(h=>{let[g]=Ii(h),x=a[g];x!=null&&(x.signatureKey=p[h],l.push(x))}),Object.keys(c).length>0?Object.keys(c).forEach(h=>{let[g]=Ii(h),x=a[g];x&&(x.signatureKey=c[h],u.push(x))}):u=o;let f={};t.library!=null&&t.library.function!=null&&(f=t.library.function.reduce((h,g)=>(h[g.signature.name]=this.mapFunction(g),h),{}));let d={nodes:a,inputs:u,outputs:l,weights:s,placeholders:o,signature:e,functions:f};return i.length>0&&(d.initNodes=i),d}mapSignatureEntries(t){return Object.keys(t||{}).reduce((e,n)=>(e[t[n].name]=n,e),{})}mapNode(t){let e=zb(t.op)||this.opMappers[t.op]||{};t.attr==null&&(t.attr={});let n={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map(o=>o.startsWith("^")?o.slice(1):o),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr,outputs:e.outputs};return e.inputs!=null&&(n.inputParams=e.inputs.reduce((o,s)=>(o[s.name]={type:s.type,inputIndexStart:s.start,inputIndexEnd:s.end},o),{})),e.attrs!=null&&(n.attrParams=e.attrs.reduce((o,s)=>{let i=s.type,a;switch(s.type){case"string":a=Vb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Vb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":a=jb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=jb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":a=Wb(t.attr,s.tfName,s.defaultValue||0),a===void 0&&s.tfDeprecatedName&&(a=Wb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":a=Kb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Kb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":a=Gb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Gb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":a=Yb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Yb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":a=qb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=qb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":a=Xb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Xb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":a=Ub(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Ub(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype[]":a=Hb(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=Hb(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":a=tF(t.attr,s.tfName,s.defaultValue),a===void 0&&s.tfDeprecatedName&&(a=tF(t.attr,s.tfDeprecatedName,s.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${s.type} for op: ${t.op}`)}return o[s.name]={value:a,type:i},o},{})),n}mapFunction(t){let e=t.nodeDef,n=[],o=[],s={};e!=null&&(s=e.reduce((p,m)=>(p[m.name]=this.mapNode(m),m.op==="Const"&&o.push(p[m.name]),p),{}));let i=[],a=[];t.signature.inputArg.forEach(p=>{let[m]=Ii(p.name),f={name:m,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:vk(p.type),type:"dtype"}},children:[]};f.signatureKey=p.name,i.push(f),s[m]=f}),Object.keys(s).forEach(p=>{let m=s[p];m.inputNames.forEach((f,d)=>{let[h,,g]=Ii(f),x=s[h];if(x.outputs!=null){let b=x.outputs.indexOf(g);if(b!==-1){let w=`${h}:${b}`;m.inputNames[d]=w}}m.inputs.push(x),x.children.push(m)})});let l=t.ret;t.signature.outputArg.forEach(p=>{let[m,f]=Ii(l[p.name]),d=s[m];d!=null&&(d.defaultOutput=f,a.push(d))});let c=this.mapArgsToSignature(t);return{nodes:s,inputs:i,outputs:a,weights:o,placeholders:n,signature:c}}mapArgsToSignature(t){return{methodName:t.signature.name,inputs:t.signature.inputArg.reduce((e,n)=>(e[n.name]=this.mapArgToTensorInfo(n),e),{}),outputs:t.signature.outputArg.reduce((e,n)=>(e[n.name]=this.mapArgToTensorInfo(n,t.ret),e),{})}}mapArgToTensorInfo(t,e){let n=t.name;return e!=null&&(n=e[n]),{name:n,dtype:t.type}}};function CQ(r){let t=L().global;if(typeof t.atob!="undefined")return t.atob(r);if(typeof Buffer!="undefined")return new Buffer(r,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function eF(r,t){let e=Array.isArray(r)?String.fromCharCode.apply(null,r):CQ(r);return t?e:e.toLowerCase()}function Vb(r,t,e,n=!1){let o=r[t];return o!=null?eF(o.s,n):e}function Gb(r,t,e){let n=r[t];return n?n.b:e}function Wb(r,t,e){let n=r[t]||{},o=n.i!=null?n.i:n.f!=null?n.f:e;return typeof o=="number"?o:parseInt(o,10)}function vk(r){switch(typeof r=="string"&&(r=ho[r]),r){case ho.DT_FLOAT:case ho.DT_HALF:return"float32";case ho.DT_INT32:case ho.DT_INT64:case ho.DT_INT8:case ho.DT_UINT8:return"int32";case ho.DT_BOOL:return"bool";case ho.DT_DOUBLE:return"float32";case ho.DT_STRING:return"string";default:return null}}function tF(r,t,e){let n=r[t];return n&&n.func?n.func.name:e}function Ub(r,t,e){let n=r[t];return n&&n.type?vk(n.type):e}function Hb(r,t,e){let n=r[t];return n&&n.list&&n.list.type?n.list.type.map(o=>vk(o)):e}function rF(r){if(!r.unknownRank)return r.dim!=null?r.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function qb(r,t,e){let n=r[t];return n&&n.shape?rF(n.shape):e}function Kb(r,t,e){let n=r[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(o=>typeof o=="number"?o:parseInt(o,10)):e}function jb(r,t,e,n=!1){let o=r[t];return o&&o.list&&o.list.s?o.list.s.map(s=>eF(s,n)):e}function Xb(r,t,e){let n=r[t];return n&&n.list&&n.list.shape?n.list.shape.map(o=>rF(o)):e}function Yb(r,t,e){let n=r[t];return n&&n.list&&n.list.b?n.list.b:e}var Zb=class{constructor(t,e,n){this.node=t,this.tensorMap=e,this.context=n,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map(o=>this.getInput(o)),t.rawAttrs!=null&&(this.attrs=Object.keys(t.rawAttrs).reduce((o,s)=>(o[s]=this.getAttr(s),o),{}))}getInput(t){return pr(t,this.tensorMap,this.context)}getAttr(t,e){let n=this.node.rawAttrs[t];if(n.tensor!=null)return pr(t,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return Wb(this.node.rawAttrs,t,e);if(n.s!=null)return Vb(this.node.rawAttrs,t,e);if(n.b!=null)return Gb(this.node.rawAttrs,t,e);if(n.shape!=null)return qb(this.node.rawAttrs,t,e);if(n.type!=null)return Ub(this.node.rawAttrs,t,e);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return Kb(this.node.rawAttrs,t,e);if(n.list.s!=null)return jb(this.node.rawAttrs,t,e);if(n.list.shape!=null)return Xb(this.node.rawAttrs,t,e);if(n.list.b!=null)return Yb(this.node.rawAttrs,t,e);if(n.list.type!=null)return Hb(this.node.rawAttrs,t,e)}return e}};var ae={};Kt(ae,{OP_SCOPE_SUFFIX:()=>M0,abs:()=>Ee,acos:()=>hx,acosh:()=>gx,add:()=>Y,addN:()=>IE,all:()=>lm,any:()=>bc,argMax:()=>oa,argMin:()=>xx,asin:()=>yx,asinh:()=>bx,atan:()=>wx,atan2:()=>Ix,atanh:()=>Cx,avgPool:()=>Su,avgPool3d:()=>vx,basicLSTMCell:()=>SE,batchNorm:()=>aa,batchNorm2d:()=>Sx,batchNorm3d:()=>Nx,batchNorm4d:()=>kx,batchToSpaceND:()=>Nu,bincount:()=>Tx,bitwiseAnd:()=>kE,booleanMaskAsync:()=>F5,broadcastArgs:()=>TE,broadcastTo:()=>la,buffer:()=>wt,cast:()=>Q,ceil:()=>_x,clipByValue:()=>Sr,clone:()=>cn,complex:()=>kn,concat:()=>ie,concat1d:()=>Ex,concat2d:()=>Ax,concat3d:()=>Dx,concat4d:()=>$x,conv1d:()=>cm,conv2d:()=>Tn,conv2dTranspose:()=>mm,conv3d:()=>Rx,conv3dTranspose:()=>Ox,cos:()=>ku,cosh:()=>fm,cosineWindow:()=>Ih,cumprod:()=>Ic,cumsum:()=>dm,denseBincount:()=>gh,depthToSpace:()=>Px,depthwiseConv2d:()=>ua,diag:()=>_E,dilation2d:()=>Mx,div:()=>ct,divNoNan:()=>Lx,dot:()=>zx,dropout:()=>cN,einsum:()=>AE,elu:()=>ca,enclosingPowerOfTwo:()=>pN,ensureShape:()=>DE,equal:()=>Fr,erf:()=>Bx,euclideanNorm:()=>Vx,exp:()=>ir,expandDims:()=>ar,expm1:()=>Gx,eye:()=>Cc,fft:()=>Ou,fill:()=>No,floor:()=>pa,floorDiv:()=>am,fused:()=>Lu,gather:()=>ma,gatherND:()=>U5,greater:()=>Fe,greaterEqual:()=>mn,ifft:()=>vl,imag:()=>Tu,image:()=>hn,inTopKAsync:()=>K5,irfft:()=>Tm,isFinite:()=>Wx,isInf:()=>Ux,isNaN:()=>Hx,leakyRelu:()=>_u,less:()=>Il,lessEqual:()=>Un,linalg:()=>fN,linspace:()=>FE,localResponseNormalization:()=>qx,log:()=>kr,log1p:()=>Eu,logSigmoid:()=>Xx,logSoftmax:()=>hm,logSumExp:()=>gm,logicalAnd:()=>Pr,logicalNot:()=>Au,logicalOr:()=>xm,logicalXor:()=>Yx,losses:()=>j8,lowerBound:()=>OE,matMul:()=>Bt,max:()=>Nr,maxPool:()=>Du,maxPool3d:()=>Jx,maxPoolWithArgmax:()=>PE,maximum:()=>_n,mean:()=>ke,meshgrid:()=>ME,min:()=>bl,minimum:()=>mo,mirrorPad:()=>Qx,mod:()=>ty,moments:()=>vc,movingAverage:()=>M5,mul:()=>$,multiRNNCell:()=>LE,multinomial:()=>zE,neg:()=>Ut,norm:()=>wl,notEqual:()=>mi,oneHot:()=>fa,ones:()=>dr,onesLike:()=>Ir,op:()=>k,outerProduct:()=>BE,pad:()=>dn,pad1d:()=>VE,pad2d:()=>GE,pad3d:()=>WE,pad4d:()=>UE,pool:()=>ey,pow:()=>pn,prelu:()=>Ru,print:()=>dx,prod:()=>ry,raggedGather:()=>HE,raggedRange:()=>qE,raggedTensorToTensor:()=>KE,rand:()=>jE,randomGamma:()=>hA,randomNormal:()=>kc,randomStandardNormal:()=>gA,randomUniform:()=>Hn,randomUniformInt:()=>xA,range:()=>da,real:()=>Cl,reciprocal:()=>ly,relu:()=>Mr,relu6:()=>ym,reshape:()=>R,reverse:()=>hr,reverse1d:()=>yA,reverse2d:()=>bA,reverse3d:()=>wA,reverse4d:()=>IA,rfft:()=>Pu,round:()=>bm,rsqrt:()=>wm,scalar:()=>ft,scatterND:()=>z5,searchSorted:()=>yh,selu:()=>Im,separableConv2d:()=>Cm,setdiff1dAsync:()=>CA,sigmoid:()=>en,sign:()=>uy,signal:()=>K8,sin:()=>vm,sinh:()=>Sm,slice:()=>Pt,slice1d:()=>Nm,slice2d:()=>wh,slice3d:()=>km,slice4d:()=>Tc,softmax:()=>Fu,softplus:()=>pi,spaceToBatchND:()=>$u,sparse:()=>X8,sparseToDense:()=>G5,spectral:()=>q8,split:()=>gr,sqrt:()=>Ne,square:()=>Wt,squaredDifference:()=>_m,squeeze:()=>qn,stack:()=>qe,step:()=>To,stridedSlice:()=>cy,string:()=>Y8,sub:()=>lt,sum:()=>pt,tan:()=>py,tanh:()=>ia,tensor:()=>sr,tensor1d:()=>Ke,tensor2d:()=>fi,tensor3d:()=>my,tensor4d:()=>vA,tensor5d:()=>SA,tensor6d:()=>NA,tensorScatterUpdate:()=>TA,tile:()=>Or,topk:()=>fy,transpose:()=>Vt,truncatedNormal:()=>Am,unique:()=>dy,unsortedSegmentSum:()=>Dm,unstack:()=>xr,upperBound:()=>_A,variable:()=>hy,where:()=>be,whereAsync:()=>xy,zeros:()=>Te,zerosLike:()=>vt});var nF=(r,t,e,n=ae)=>{switch(r.op){case"BiasAdd":case"AddV2":case"Add":return[n.add(v("a",r,t,e),v("b",r,t,e))];case"AddN":return[n.addN(v("tensors",r,t,e))];case"FloorMod":case"Mod":return[n.mod(v("a",r,t,e),v("b",r,t,e))];case"Mul":return[n.mul(v("a",r,t,e),v("b",r,t,e))];case"RealDiv":case"Div":return[n.div(v("a",r,t,e),v("b",r,t,e))];case"DivNoNan":return[n.divNoNan(v("a",r,t,e),v("b",r,t,e))];case"FloorDiv":return[n.floorDiv(v("a",r,t,e),v("b",r,t,e))];case"Sub":return[n.sub(v("a",r,t,e),v("b",r,t,e))];case"Minimum":return[n.minimum(v("a",r,t,e),v("b",r,t,e))];case"Maximum":return[n.maximum(v("a",r,t,e),v("b",r,t,e))];case"Pow":return[n.pow(v("a",r,t,e),v("b",r,t,e))];case"SquaredDifference":return[n.squaredDifference(v("a",r,t,e),v("b",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var oF=(r,t,e,n=ae)=>{switch(r.op){case"Abs":case"ComplexAbs":return[n.abs(v("x",r,t,e))];case"Acos":return[n.acos(v("x",r,t,e))];case"Acosh":return[n.acosh(v("x",r,t,e))];case"Asin":return[n.asin(v("x",r,t,e))];case"Asinh":return[n.asinh(v("x",r,t,e))];case"Atan":return[n.atan(v("x",r,t,e))];case"Atan2":return[n.atan2(v("x",r,t,e),v("y",r,t,e))];case"Atanh":return[n.atanh(v("x",r,t,e))];case"Ceil":return[n.ceil(v("x",r,t,e))];case"Complex":return[n.complex(v("real",r,t,e),v("imag",r,t,e))];case"Cos":return[n.cos(v("x",r,t,e))];case"Cosh":return[n.cosh(v("x",r,t,e))];case"Elu":return[n.elu(v("x",r,t,e))];case"Erf":return[n.erf(v("x",r,t,e))];case"Exp":return[n.exp(v("x",r,t,e))];case"Expm1":return[n.expm1(v("x",r,t,e))];case"Floor":return[n.floor(v("x",r,t,e))];case"Log":return[n.log(v("x",r,t,e))];case"Log1p":return[n.log1p(v("x",r,t,e))];case"Imag":return[n.imag(v("x",r,t,e))];case"Neg":return[n.neg(v("x",r,t,e))];case"Reciprocal":return[n.reciprocal(v("x",r,t,e))];case"Real":return[n.real(v("x",r,t,e))];case"Relu":return[n.relu(v("x",r,t,e))];case"Round":return[n.round(v("x",r,t,e))];case"Selu":return[n.selu(v("x",r,t,e))];case"Sigmoid":return[n.sigmoid(v("x",r,t,e))];case"Sin":return[n.sin(v("x",r,t,e))];case"Sign":return[n.sign(v("x",r,t,e))];case"Sinh":return[n.sinh(v("x",r,t,e))];case"Softplus":return[n.softplus(v("x",r,t,e))];case"Sqrt":return[n.sqrt(v("x",r,t,e))];case"Square":return[n.square(v("x",r,t,e))];case"Tanh":return[n.tanh(v("x",r,t,e))];case"Tan":return[n.tan(v("x",r,t,e))];case"ClipByValue":return[n.clipByValue(v("x",r,t,e),v("clipValueMin",r,t,e),v("clipValueMax",r,t,e))];case"Relu6":return[n.relu6(v("x",r,t,e))];case"Rsqrt":return[n.rsqrt(pr(r.inputNames[0],t,e))];case"LeakyRelu":return[n.leakyRelu(v("x",r,t,e),v("alpha",r,t,e))];case"Prelu":return[n.prelu(v("x",r,t,e),v("alpha",r,t,e))];case"IsNan":return[n.isNaN(pr(r.inputNames[0],t,e))];case"IsInf":return[n.isInf(pr(r.inputNames[0],t,e))];case"IsFinite":return[n.isFinite(pr(r.inputNames[0],t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Xn(r,t,e=""){if(!(typeof r=="number"||typeof t=="number")){y.assert(r.length===t.length,()=>e+` Shapes ${r} and ${t} must match`);for(let n=0;n<r.length;n++){let o=r[n],s=t[n];y.assert(o<0||s<0||o===s,()=>e+` Shapes ${r} and ${t} must match`)}}}function sF(r){return!(typeof r=="number"||r.some(t=>t<0))}function id(r,t,e){let n=Jb(r,e),o=!sF(n);if(o&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);if(o&&t.forEach(s=>{n=Jb(s.shape,n)}),!sF(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function Jb(r,t){if(typeof r=="number")return t;if(typeof t=="number")return r;if(r.length!==t.length)throw new Error(`Incompatible ranks during merge: ${r} vs. ${t}`);let e=[];for(let n=0;n<r.length;++n){let o=r[n],s=t[n];if(o>=0&&s>=0&&o!==s)throw new Error(`Incompatible shape during merge: ${r} vs. ${t}`);e[n]=o>=0?o:s}return e}var Qb=class{constructor(t,e,n,o,s,i,a){this.name=t,this.dtype=e,this.maxSize=n,this.elementShape=o,this.identicalElementShapes=s,this.dynamicSize=i,this.clearAfterRead=a,this.tensors=[],this.closed_=!1,this.idTensor=ft(0),$e(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(t){this.tensors.forEach(e=>{(t==null||!t.has(e.tensor.id))&&e.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(t<0||t>=this.size())throw new Error(`Tried to read from index ${t}, but array size is: ${this.size()}`);let e=this.tensors[t];if(e.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${t} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor}readMany(t){return t.map(e=>this.read(e))}write(t,e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error(`Tried to write to index ${t}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t},
| because the value dtype is ${e.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=e.shape),Xn(this.elementShape,e.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${t}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t}, because it has already been written.`);n.tensor=e,$e(e),n.written=!0,this.tensors[t]=n}writeMany(t,e){if(t.length!==e.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${t.length} is not the same as tensors size: ${e.length}.`);t.forEach((n,o)=>this.write(n,e[o]))}gather(t,e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${e}`);if(t)t=t.slice(0,this.size());else{t=[];for(let o=0;o<this.size();o++)t.push(o)}if(t.length===0)return sr([],[0].concat(this.elementShape));let n=this.readMany(t);return Xn(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),qe(n,0)}concat(t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${t}`);if(this.size()===0)return sr([],[0].concat(this.elementShape));let e=[];for(let o=0;o<this.size();o++)e.push(o);let n=this.readMany(e);return Xn(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),ie(n,0)}scatter(t,e){if(e.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${e.dtype}`);if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let n=Math.max(...t);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(t,xr(e,0))}split(t,e){if(e.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${e.dtype}`);let n=0,o=t.map(u=>(n+=u,n));if(n!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
| tensor.shape[0], but sum of lengths is
| ${n}, and tensor's shape is: ${e.shape}`);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${t.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:e.size/n,i=[];B(()=>{e=R(e,[1,n,s]);for(let u=0;u<t.length;++u){let c=[0,u===0?0:o[u-1],0],p=[1,t[u],s];i[u]=R(Pt(e,c,p),this.elementShape)}return i});let a=[];for(let u=0;u<t.length;u++)a[u]=u;this.writeMany(a,i)}};var Ml=class{get id(){return this.idTensor.id}constructor(t,e,n,o=-1){this.tensors=t,this.elementShape=e,this.elementDtype=n,t!=null&&t.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);Xn(e,s.shape,"TensorList shape mismatch: "),$e(s)}),this.idTensor=ft(0),this.maxNumElements=o,$e(this.idTensor)}copy(){return new Ml([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(t){this.tensors.forEach(e=>{(t==null||!t.has(e.id))&&e.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(t,e,n=-1){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Xn(t,this.elementShape,"TensorList shape mismatch: ");let o=id(this.elementShape,this.tensors,t);return B(()=>{let s=this.tensors.map(i=>R(i,o));return qe(s,0)})}popBack(t,e){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=id(this.elementShape,this.tensors,t),o=this.tensors.pop();return o.kept=!1,Xn(o.shape,t,"TensorList shape mismatch: "),R(o,n)}pushBack(t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(Xn(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");$e(t),this.tensors.push(t)}resize(t){if(t<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${t}`);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error(`TensorListResize input size ${t} is greater maxNumElement ${this.maxNumElements}.`);let e=new Ml([],this.elementShape,this.elementDtype,this.maxNumElements);e.tensors.length=t;for(let n=0;n<Math.min(this.tensors.length,t);++n)e.tensors[n]=this.tensors[n];return e}getItem(t,e,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(t<0||t>this.tensors.length)throw new Error(`Trying to access element ${t} in a list with ${this.tensors.length} elements.`);if(this.tensors[t]==null)throw new Error(`element at index ${t} is null.`);Xn(this.tensors[t].shape,e,"TensorList shape mismatch: ");let o=id(this.elementShape,this.tensors,e);return R(this.tensors[t],o)}setItem(t,e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error(`Trying to set element ${t} in a list with max ${this.maxNumElements} elements.`);Xn(this.elementShape,e.shape,"TensorList shape mismatch: "),$e(e),this.tensors[t]!=null&&(this.tensors[t].kept=!1),this.tensors[t]=e}gather(t,e,n){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);Xn(this.elementShape,n,"TensorList shape mismatch: "),t=t.slice(0,this.size());let o=id(this.elementShape,this.tensors,n);return t.length===0?sr([],[0].concat(o)):B(()=>{let s=t.map(i=>R(this.tensors[i],o));return qe(s,0)})}concat(t,e){if(t&&t!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${t}`);Xn(this.elementShape,e,"TensorList shape mismatch: ");let n=id(this.elementShape,this.tensors,e);return this.size()===0?sr([],[0].concat(n)):B(()=>{let o=this.tensors.map(s=>R(s,n));return ie(o,0)})}};function iF(r,t,e){let n=r.dtype;if(r.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${r.shape}`);if(r.dtype!==e)throw new Error(`Invalid data types; op elements ${r.dtype}, but list elements ${e}`);let o=r.shape.slice(1);Xn(o,t,"TensorList shape mismatch: ");let s=xr(r);return new Ml(s,t,n)}function aF(r,t,e,n){return new Ml([],r,t,n)}function lF(r,t,e,n){if(t.length!==r.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${r.shape[0]}`);let o=Math.max(...t);if(n!=null&&n!==-1&&o>=n)throw new Error(`Max index must be < array size (${o} vs. ${n})`);let s=new Ml([],e,r.dtype,n),i=xr(r,0);return t.forEach((a,u)=>{s.setItem(a,i[u])}),s}function uF(r,t,e){let n=0,o=t.map(c=>(n+=c,n));if(n!==r.shape[0])throw new Error(`Expected sum of lengths to be equal to
| tensor.shape[0], but sum of lengths is
| ${n}, and tensor's shape is: ${r.shape}`);let s=r.shape.slice(1),i=Jb(s,e),a=n===0?0:r.size/n,u=B(()=>{let c=[];r=R(r,[1,n,a]);for(let p=0;p<t.length;++p){let f=[0,p===0?0:o[p-1],0],d=[1,t[p],a];c[p]=R(Pt(r,f,d),i)}return r.dispose(),c}),l=new Ml([],e,r.dtype,t.length);for(let c=0;c<u.length;c++)l.setItem(c,u[c]);return l}var cF=async(r,t,e)=>{switch(r.op){case"If":case"StatelessIf":{let n=v("thenBranch",r,t,e),o=v("elseBranch",r,t,e),s=v("cond",r,t,e),i=v("args",r,t,e);return(await s.data())[0]?e.functionMap[n].executeFunctionAsync(i,e.tensorArrayMap,e.tensorListMap):e.functionMap[o].executeFunctionAsync(i,e.tensorArrayMap,e.tensorListMap)}case"While":case"StatelessWhile":{let n=v("body",r,t,e),o=v("cond",r,t,e),s=v("args",r,t,e),i=await e.functionMap[o].executeFunctionAsync(s,e.tensorArrayMap,e.tensorListMap),a=s.map(c=>c.id),u=await i[0].data();i.forEach(c=>{!c.kept&&a.indexOf(c.id)===-1&&c.dispose()});let l=s;for(;u[0];){let c=l;l=await e.functionMap[n].executeFunctionAsync(l,e.tensorArrayMap,e.tensorListMap);let p=l.map(f=>f.id);c.forEach(f=>{!f.kept&&a.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()});let m=await e.functionMap[o].executeFunctionAsync(l,e.tensorArrayMap,e.tensorListMap);u=await m[0].data(),m.forEach(f=>{!f.kept&&a.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()})}return l}case"LoopCond":{let n=v("pred",r,t,e);return[Ci(n)]}case"Switch":{let n=v("pred",r,t,e),o=v("data",r,t,e);return o.kept||(o=Ci(o)),(await n.data())[0]?[void 0,o]:[o,void 0]}case"Merge":{let n=r.inputNames.find(o=>pr(o,t,e)!==void 0);if(n){let o=pr(n,t,e);return[Ci(o)]}return}case"Enter":{let n=v("frameName",r,t,e),o=v("tensor",r,t,e);return e.enterFrame(n),[Ci(o)]}case"Exit":{let n=v("tensor",r,t,e);return e.exitFrame(),[Ci(n)]}case"NextIteration":{let n=v("tensor",r,t,e);return e.nextIteration(),[Ci(n)]}case"TensorArrayV3":{let n=v("size",r,t,e),o=v("dtype",r,t,e),s=v("elementShape",r,t,e),i=v("dynamicSize",r,t,e),a=v("clearAfterRead",r,t,e),u=v("identicalElementShapes",r,t,e),l=v("name",r,t,e),c=new Qb(l,o,n,s,u,i,a);return e.addTensorArray(c),[c.idTensor,ft(1)]}case"TensorArrayWriteV3":{let n=v("tensorArrayId",r,t,e),o=v("index",r,t,e),s=v("tensor",r,t,e),i=e.getTensorArray(n.id);return i.write(o,s),[i.idTensor]}case"TensorArrayReadV3":{let n=v("tensorArrayId",r,t,e),o=v("index",r,t,e);return[e.getTensorArray(n.id).read(o)]}case"TensorArrayGatherV3":{let n=v("tensorArrayId",r,t,e),o=v("indices",r,t,e),s=v("dtype",r,t,e);return[e.getTensorArray(n.id).gather(o,s)]}case"TensorArrayScatterV3":{let n=v("tensorArrayId",r,t,e),o=v("indices",r,t,e),s=v("tensor",r,t,e),i=e.getTensorArray(n.id);return i.scatter(o,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=v("tensorArrayId",r,t,e),o=e.getTensorArray(n.id),s=v("dtype",r,t,e);return[o.concat(s)]}case"TensorArraySplitV3":{let n=v("tensorArrayId",r,t,e),o=v("tensor",r,t,e),s=v("lengths",r,t,e),i=e.getTensorArray(n.id);return i.split(s,o),[i.idTensor]}case"TensorArraySizeV3":{let n=v("tensorArrayId",r,t,e),o=e.getTensorArray(n.id);return[ft(o.size(),"int32")]}case"TensorArrayCloseV3":{let n=v("tensorArrayId",r,t,e),o=e.getTensorArray(n.id);return o.clearAndClose(),[o.idTensor]}case"TensorListSetItem":{let n=v("tensorListId",r,t,e),o=v("index",r,t,e),s=v("tensor",r,t,e),i=e.getTensorList(n.id);return i.setItem(o,s),[i.idTensor]}case"TensorListGetItem":{let n=v("tensorListId",r,t,e),o=v("index",r,t,e),s=v("elementShape",r,t,e),i=v("elementDType",r,t,e);return[e.getTensorList(n.id).getItem(o,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=v("indices",r,t,e),o=v("tensor",r,t,e),s=v("elementShape",r,t,e),i=v("numElements",r,t,e),a=lF(o,n,s,i);return e.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=v("elementShape",r,t,e),o=v("elementDType",r,t,e),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=v(s,r,t,e),a=r.op==="TensorListReserve"?-1:i,u=aF(n,o,i,a);return e.addTensorList(u),[u.idTensor]}case"TensorListGather":{let n=v("tensorListId",r,t,e),o=v("indices",r,t,e),s=v("elementShape",r,t,e),i=v("elementDType",r,t,e);return[e.getTensorList(n.id).gather(o,i,s)]}case"TensorListStack":{let n=v("tensorListId",r,t,e),o=v("elementShape",r,t,e),s=v("elementDType",r,t,e),i=v("numElements",r,t,e);return[e.getTensorList(n.id).stack(o,s,i)]}case"TensorListFromTensor":{let n=v("tensor",r,t,e),o=v("elementShape",r,t,e),s=v("elementDType",r,t,e),i=iF(n,o,s);return e.addTensorList(i),[i.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let n=v("tensorListId",r,t,e),o=e.getTensorList(n.id),s=v("dtype",r,t,e),i=v("elementShape",r,t,e);return[o.concat(s,i)]}case"TensorListPushBack":{let n=v("tensorListId",r,t,e),o=v("tensor",r,t,e),s=e.getTensorList(n.id);return s.pushBack(o),[s.idTensor]}case"TensorListPopBack":{let n=v("tensorListId",r,t,e),o=v("elementShape",r,t,e),s=v("elementDType",r,t,e);return[e.getTensorList(n.id).popBack(o,s)]}case"TensorListSplit":{let n=v("tensor",r,t,e),o=v("elementShape",r,t,e),s=v("lengths",r,t,e),i=uF(n,s,o);return e.addTensorList(i),[i.idTensor]}case"TensorListLength":{let n=v("tensorListId",r,t,e),o=e.getTensorList(n.id);return[ft(o.size(),"int32")]}case"TensorListResize":{let n=v("tensorListId",r,t,e),o=v("size",r,t,e),i=e.getTensorList(n.id).resize(o);return e.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function pF(r,t,e){let[n,o]=v("fusedOps",r,t,e),s=n==="biasadd",i=!s,a=o==="prelu",u=n==="fusedbatchnorm",l=v("numArgs",r,t,e);if(s){if(a&&l!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&s&&l!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(u)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let c=v("strides",r,t,e),p=Hh(r,t,e),m=v("dataFormat",r,t,e).toUpperCase(),f=v("dilations",r,t,e),[d,h]=v("args",r,t,e);i&&(h=d,d=void 0);let g=v("leakyreluAlpha",r,t,e);return{stride:c,pad:p,dataFormat:m,dilations:f,biasArg:d,preluArg:h,activationFunc:o,leakyreluAlpha:g}}var mF=(r,t,e,n=ae)=>{switch(r.op){case"Conv1D":{let o=v("stride",r,t,e),s=v("pad",r,t,e),i=v("dataFormat",r,t,e).toUpperCase(),a=v("dilation",r,t,e);return[n.conv1d(v("x",r,t,e),v("filter",r,t,e),o,s,i,a)]}case"Conv2D":{let o=v("strides",r,t,e),s=Hh(r,t,e),i=v("dataFormat",r,t,e).toUpperCase(),a=v("dilations",r,t,e);return[n.conv2d(v("x",r,t,e),v("filter",r,t,e),[o[1],o[2]],s,i,[a[1],a[2]])]}case"_FusedConv2D":{let{stride:o,pad:s,dataFormat:i,dilations:a,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=pF(r,t,e);return[n.fused.conv2d({x:v("x",r,t,e),filter:v("filter",r,t,e),strides:[o[1],o[2]],pad:s,dataFormat:i,dilations:[a[1],a[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"FusedDepthwiseConv2dNative":{let{stride:o,pad:s,dataFormat:i,dilations:a,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=pF(r,t,e);return[n.fused.depthwiseConv2d({x:v("x",r,t,e),filter:v("filter",r,t,e),strides:[o[1],o[2]],pad:s,dataFormat:i,dilations:[a[1],a[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let o=v("outputShape",r,t,e),s=v("strides",r,t,e),i=Hh(r,t,e);return[n.conv2dTranspose(v("x",r,t,e),v("filter",r,t,e),o,[s[1],s[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let o=v("strides",r,t,e),s=Hh(r,t,e),i=v("dilations",r,t,e),a=v("dataFormat",r,t,e).toUpperCase();return[n.depthwiseConv2d(v("input",r,t,e),v("filter",r,t,e),[o[1],o[2]],s,a,[i[1],i[2]])]}case"Conv3D":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("dataFormat",r,t,e).toUpperCase(),a=v("dilations",r,t,e);return[n.conv3d(v("x",r,t,e),v("filter",r,t,e),[o[1],o[2],o[3]],s,i,[a[1],a[2],a[3]])]}case"AvgPool":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("kernelSize",r,t,e);return[n.avgPool(v("x",r,t,e),[i[1],i[2]],[o[1],o[2]],s)]}case"MaxPool":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("kernelSize",r,t,e);return[n.maxPool(v("x",r,t,e),[i[1],i[2]],[o[1],o[2]],s)]}case"MaxPoolWithArgmax":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("kernelSize",r,t,e),a=v("includeBatchInIndex",r,t,e),{result:u,indexes:l}=n.maxPoolWithArgmax(v("x",r,t,e),[i[1],i[2]],[o[1],o[2]],s,a);return[u,l]}case"AvgPool3D":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("kernelSize",r,t,e);return[n.avgPool3d(v("x",r,t,e),[i[1],i[2],i[3]],[o[1],o[2],o[3]],s)]}case"MaxPool3D":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("kernelSize",r,t,e);return[n.maxPool3d(v("x",r,t,e),[i[1],i[2],i[3]],[o[1],o[2],o[3]],s)]}case"Dilation2D":{let o=v("strides",r,t,e),s=v("pad",r,t,e),i=v("dilations",r,t,e),a=o[1],u=o[2],l=i[1],c=i[2];return[n.dilation2d(v("x",r,t,e),v("filter",r,t,e),[a,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var fF=(r,t,e,n=ae)=>{switch(r.op){case"Fill":{let o=v("shape",r,t,e),s=v("dtype",r,t,e),i=v("value",r,t,e);return[n.fill(o,i,s)]}case"LinSpace":{let o=v("start",r,t,e),s=v("stop",r,t,e),i=v("num",r,t,e);return[n.linspace(o,s,i)]}case"Multinomial":{let o=v("logits",r,t,e),s=v("numSamples",r,t,e),i=v("seed",r,t,e);return[n.multinomial(o,s,i)]}case"OneHot":{let o=v("indices",r,t,e),s=v("depth",r,t,e),i=v("onValue",r,t,e),a=v("offValue",r,t,e),u=v("dtype",r,t,e);return[n.oneHot(o,s,i,a,u)]}case"Ones":return[n.ones(v("shape",r,t,e),v("dtype",r,t,e))];case"OnesLike":return[n.onesLike(v("x",r,t,e))];case"RandomStandardNormal":return[n.randomStandardNormal(v("shape",r,t,e),v("dtype",r,t,e),v("seed",r,t,e))];case"RandomUniform":return[n.randomUniform(v("shape",r,t,e),v("minval",r,t,e),v("maxval",r,t,e),v("dtype",r,t,e))];case"RandomUniformInt":return[n.randomUniformInt(v("shape",r,t,e),v("minval",r,t,e),v("maxval",r,t,e),v("seed",r,t,e))];case"Range":{let o=v("start",r,t,e),s=v("stop",r,t,e),i=v("step",r,t,e);return[n.range(o,s,i,v("dtype",r,t,e))]}case"TruncatedNormal":{let o=v("shape",r,t,e),s=v("mean",r,t,e),i=v("stdDev",r,t,e),a=v("seed",r,t,e);return[n.truncatedNormal(o,s,i,v("dtype",r,t,e),a)]}case"Zeros":return[n.zeros(v("shape",r,t,e),v("dtype",r,t,e))];case"ZerosLike":return[n.zerosLike(v("x",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Sk(r,t,e){let n=v("boxes",r,t,e),o=v("scores",r,t,e),s=v("maxOutputSize",r,t,e),i=v("iouThreshold",r,t,e),a=v("scoreThreshold",r,t,e),u=v("softNmsSigma",r,t,e);return{boxes:n,scores:o,maxOutputSize:s,iouThreshold:i,scoreThreshold:a,softNmsSigma:u}}var dF=async(r,t,e,n,o=ae)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:i,maxOutputSize:a,iouThreshold:u,scoreThreshold:l,softNmsSigma:c}=Sk(r,t,e),p=await o.image.nonMaxSuppressionWithScoreAsync(s,i,a,u,l,c);return[p.selectedIndices,p.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:i,maxOutputSize:a,iouThreshold:u,scoreThreshold:l}=Sk(r,t,e),c=v("padToMaxOutputSize",r,t,e),p=await o.image.nonMaxSuppressionPaddedAsync(s,i,a,u,l,c);return[p.selectedIndices,p.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:i,maxOutputSize:a,iouThreshold:u,scoreThreshold:l}=Sk(r,t,e);return[await o.image.nonMaxSuppressionAsync(s,i,a,u,l)]}case"Where":{let s=o.cast(v("condition",r,t,e),"bool"),i=[await o.whereAsync(s)];return s.dispose(),i}case"ListDiff":return o.setdiff1dAsync(v("x",r,t,e),v("y",r,t,e));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var hF=(r,t,e,n=ae)=>{switch(r.op){case"LowerBound":{let o=v("sortedSequence",r,t,e),s=v("values",r,t,e);return[n.lowerBound(o,s)]}case"TopKV2":{let o=v("x",r,t,e),s=v("k",r,t,e),i=v("sorted",r,t,e),a=n.topk(o,s,i);return[a.values,a.indices]}case"UpperBound":{let o=v("sortedSequence",r,t,e),s=v("values",r,t,e);return[n.upperBound(o,s)]}case"Unique":{let o=v("x",r,t,e),s=n.unique(o);return[s.values,s.indices]}case"UniqueV2":{let o=v("x",r,t,e),s=v("axis",r,t,e),i=n.unique(o,s);return[i.values,i.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var gF=(r,t,e,n=ae)=>{switch(r.op){case"Const":return t[r.name];case"PlaceholderWithDefault":let o=v("default",r,t,e);return[pr(r.name,t,e)||o];case"Placeholder":return[pr(r.name,t,e)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=v("x",r,t,e);return[Ci(c)]}case"IdentityN":return v("x",r,t,e).map(c=>Ci(c));case"Snapshot":let s=v("x",r,t,e);return[Ci(s)];case"Shape":return[n.tensor1d(v("x",r,t,e).shape,"int32")];case"ShapeN":return v("x",r,t,e).map(c=>n.tensor1d(c.shape));case"Size":return[n.scalar(v("x",r,t,e).size,"int32")];case"Rank":return[n.scalar(v("x",r,t,e).rank,"int32")];case"NoOp":return[n.scalar(1)];case"Print":let i=v("x",r,t,e),a=v("data",r,t,e),u=v("message",r,t,e),l=v("summarize",r,t,e);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(u);for(let c=0;c<a.length;c++)console.log(Array.prototype.slice.call(a[c].dataSync()).slice(0,l));return[i];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var tw=class{get id(){return this.handle.id}constructor(t,e){this.keyDType=t,this.valueDType=e,this.handle=ft(0),this.tensorMap=new Map,$e(this.handle)}clearAndClose(){this.tensorMap.forEach(t=>t.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return ft(this.size(),"int32")}async import(t,e){this.checkKeyAndValueTensor(t,e);let n=await t.data();return this.tensorMap.forEach(o=>o.dispose()),this.tensorMap.clear(),B(()=>{let o=xr(e),s=n.length,i=o.length;y.assert(s===i,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${i} elements.`);for(let a=0;a<s;a++){let u=n[a],l=o[a];$e(l),this.tensorMap.set(u,l)}return this.handle})}async find(t,e){this.checkKeyAndValueTensor(t,e);let n=await t.data();return B(()=>{let o=[];for(let s=0;s<n.length;s++){let i=n[s],a=this.findWithDefault(i,e);o.push(a)}return qe(o)})}findWithDefault(t,e){let n=this.tensorMap.get(t);return n!=null?n:e}checkKeyAndValueTensor(t,e){if(t.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${t.dtype}`);if(e.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${e.dtype}`)}};var xF=async(r,t,e,n)=>{switch(r.op){case"HashTable":case"HashTableV2":{let o=n.getHashTableHandleByName(r.name);if(o!=null)return[o];{let s=v("keyDType",r,t,e),i=v("valueDType",r,t,e),a=new tw(s,i);return n.addHashTable(r.name,a),[a.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{let o=v("tableHandle",r,t,e,n),s=v("keys",r,t,e),i=v("values",r,t,e);return[await n.getHashTableById(o.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let o=v("tableHandle",r,t,e,n),s=v("keys",r,t,e),i=v("defaultValue",r,t,e);return[await n.getHashTableById(o.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let o=v("tableHandle",r,t,e,n);return[n.getHashTableById(o.id).tensorSize()]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var yF=(r,t,e,n=ae)=>{switch(r.op){case"ResizeBilinear":{let o=v("images",r,t,e),s=v("size",r,t,e),i=v("alignCorners",r,t,e),a=v("halfPixelCenters",r,t,e);return[n.image.resizeBilinear(o,[s[0],s[1]],i,a)]}case"ResizeNearestNeighbor":{let o=v("images",r,t,e),s=v("size",r,t,e),i=v("alignCorners",r,t,e),a=v("halfPixelCenters",r,t,e);return[n.image.resizeNearestNeighbor(o,[s[0],s[1]],i,a)]}case"CropAndResize":{let o=v("image",r,t,e),s=v("boxes",r,t,e),i=v("boxInd",r,t,e),a=v("cropSize",r,t,e),u=v("method",r,t,e),l=v("extrapolationValue",r,t,e);return[n.image.cropAndResize(o,s,i,a,u,l)]}case"ImageProjectiveTransformV3":{let o=v("images",r,t,e),s=v("transforms",r,t,e),i=v("outputShape",r,t,e),a=v("fillValue",r,t,e),u=v("interpolation",r,t,e),l=v("fillMode",r,t,e);return[n.image.transform(o,s,u.toLowerCase(),l.toLowerCase(),a,i)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var bF=(r,t,e,n=ae)=>{switch(r.op){case"Equal":return[n.equal(v("a",r,t,e),v("b",r,t,e))];case"NotEqual":return[n.notEqual(v("a",r,t,e),v("b",r,t,e))];case"Greater":return[n.greater(v("a",r,t,e),v("b",r,t,e))];case"GreaterEqual":return[n.greaterEqual(v("a",r,t,e),v("b",r,t,e))];case"Less":return[n.less(v("a",r,t,e),v("b",r,t,e))];case"LessEqual":return[n.lessEqual(v("a",r,t,e),v("b",r,t,e))];case"LogicalAnd":return[n.logicalAnd(v("a",r,t,e),v("b",r,t,e))];case"LogicalNot":return[n.logicalNot(v("a",r,t,e))];case"LogicalOr":return[n.logicalOr(v("a",r,t,e),v("b",r,t,e))];case"Select":case"SelectV2":return[n.where(v("condition",r,t,e),v("a",r,t,e),v("b",r,t,e))];case"BitwiseAnd":return[n.bitwiseAnd(v("a",r,t,e),v("b",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var wF=(r,t,e,n=ae)=>{switch(r.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[n.matMul(v("a",r,t,e),v("b",r,t,e),v("transposeA",r,t,e),v("transposeB",r,t,e))];case"Einsum":return[n.einsum(v("equation",r,t,e),...v("tensors",r,t,e))];case"Transpose":return[n.transpose(v("x",r,t,e),v("perm",r,t,e))];case"_FusedMatMul":let[o,s]=v("fusedOps",r,t,e),i=o==="biasadd",a=s==="prelu",u=v("numArgs",r,t,e),l=v("leakyreluAlpha",r,t,e);if(i){if(a&&u!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&u!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[c,p]=v("args",r,t,e);return[n.fused.matMul({a:v("a",r,t,e),b:v("b",r,t,e),transposeA:v("transposeA",r,t,e),transposeB:v("transposeB",r,t,e),bias:c,activation:s,preluActivationWeights:p,leakyreluAlpha:l})];case"MatrixBandPart":return[n.linalg.bandPart(v("a",r,t,e),v("numLower",r,t,e),v("numUpper",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var IF=(r,t,e,n=ae)=>{switch(r.op){case"EuclideanNorm":return[n.euclideanNorm(v("x",r,t,e),v("axis",r,t,e),v("keepDims",r,t,e))];case"FusedBatchNorm":case"FusedBatchNormV2":return[n.batchNorm(v("x",r,t,e),v("mean",r,t,e),v("variance",r,t,e),v("offset",r,t,e),v("scale",r,t,e),v("epsilon",r,t,e))];case"FusedBatchNormV3":return[n.batchNorm(v("x",r,t,e),v("mean",r,t,e),v("variance",r,t,e),v("offset",r,t,e),v("scale",r,t,e),v("epsilon",r,t,e))];case"LRN":return[n.localResponseNormalization(v("x",r,t,e),v("radius",r,t,e),v("bias",r,t,e),v("alpha",r,t,e),v("beta",r,t,e))];case"Softmax":return[n.softmax(v("x",r,t,e))];case"LogSoftmax":return[n.logSoftmax(v("x",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var CF=(r,t,e,n=ae)=>{switch(r.op){case"RaggedGather":{let{outputNestedSplits:o,outputDenseValues:s}=n.raggedGather(v("paramsNestedSplits",r,t,e),v("paramsDenseValues",r,t,e),v("indices",r,t,e),v("outputRaggedRank",r,t,e));return o.concat(s)}case"RaggedRange":{let{rtNestedSplits:o,rtDenseValues:s}=n.raggedRange(v("starts",r,t,e),v("limits",r,t,e),v("splits",r,t,e));return[o,s]}case"RaggedTensorToTensor":return[n.raggedTensorToTensor(v("shape",r,t,e),v("values",r,t,e),v("defaultValue",r,t,e),v("rowPartitionTensors",r,t,e),v("rowPartitionTypes",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var vF=(r,t,e,n=ae)=>{switch(r.op){case"Max":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.max(v("x",r,t,e),a,u)]}case"Mean":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.mean(v("x",r,t,e),a,u)]}case"Min":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.min(v("x",r,t,e),a,u)]}case"Sum":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.sum(v("x",r,t,e),a,u)]}case"All":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.all(v("x",r,t,e),a,u)]}case"Any":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.any(v("x",r,t,e),a,u)]}case"ArgMax":{let a=v("axis",r,t,e);return[n.argMax(v("x",r,t,e),a)]}case"ArgMin":{let a=v("axis",r,t,e);return[n.argMin(v("x",r,t,e),a)]}case"Prod":{let a=v("axis",r,t,e),u=v("keepDims",r,t,e);return[n.prod(v("x",r,t,e),a,u)]}case"Cumprod":{let a=v("axis",r,t,e),u=v("exclusive",r,t,e),l=v("reverse",r,t,e);return[n.cumprod(v("x",r,t,e),a,u,l)]}case"Cumsum":{let a=v("axis",r,t,e),u=v("exclusive",r,t,e),l=v("reverse",r,t,e);return[n.cumsum(v("x",r,t,e),a,u,l)]}case"Bincount":let o=v("x",r,t,e),s=v("weights",r,t,e),i=v("size",r,t,e);return[n.bincount(o,s,i)];case"DenseBincount":{let a=v("x",r,t,e),u=v("weights",r,t,e),l=v("size",r,t,e),c=v("binaryOutput",r,t,e);return[n.denseBincount(a,u,l,c)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var SF=(r,t,e,n=ae)=>{switch(r.op){case"ConcatV2":case"Concat":{let o=v("n",r,t,e),s=v("axis",r,t,e),i=v("tensors",r,t,e);return i=i.slice(0,o),[n.concat(i,s)]}case"Gather":{let o=v("x",r,t,e),s=v("indices",r,t,e);return[n.gather(o,n.cast(s,"int32"),0)]}case"GatherV2":{let o=v("axis",r,t,e),s=v("batchDims",r,t,e),i=v("x",r,t,e),a=v("indices",r,t,e);return[n.gather(i,n.cast(a,"int32"),o,s)]}case"Reverse":{let o=v("dims",r,t,e),s=[];for(let a=0;a<o.length;a++)o[a]&&s.push(a);let i=v("x",r,t,e);return[n.reverse(i,s)]}case"ReverseV2":{let o=v("axis",r,t,e),s=v("x",r,t,e);return[n.reverse(s,o)]}case"Slice":{let o=v("begin",r,t,e),s=v("size",r,t,e);return[n.slice(v("x",r,t,e),o,s)]}case"StridedSlice":{let o=v("begin",r,t,e),s=v("end",r,t,e),i=v("strides",r,t,e),a=v("beginMask",r,t,e),u=v("endMask",r,t,e),l=v("ellipsisMask",r,t,e),c=v("newAxisMask",r,t,e),p=v("shrinkAxisMask",r,t,e),m=v("x",r,t,e);return[n.stridedSlice(m,o,s,i,a,u,l,c,p)]}case"Pack":return B(()=>{let o=v("axis",r,t,e),s=v("tensors",r,t,e),i=s[0].shape,a=n.squeeze(s[0]).shape,u=s.map(l=>{let c=y.arraysEqual(l.shape,i);if(!c&&!y.arraysEqual(n.squeeze(l).shape,a))throw new Error("the input tensors shape does not match");return c?l:n.reshape(l,i)});return[n.stack(u,o)]});case"Unpack":{let o=v("axis",r,t,e),s=v("tensor",r,t,e);return n.unstack(s,o)}case"Tile":{let o=v("reps",r,t,e);return[n.tile(v("x",r,t,e),o)]}case"Split":case"SplitV":{let o=v("axis",r,t,e),s=v("numOrSizeSplits",r,t,e),i=v("x",r,t,e);return n.split(i,s,o)}case"ScatterNd":{let o=v("indices",r,t,e),s=v("values",r,t,e),i=v("shape",r,t,e);return[n.scatterND(o,s,i)]}case"GatherNd":{let o=v("x",r,t,e),s=v("indices",r,t,e);return[n.gatherND(o,s)]}case"SparseToDense":{let o=v("sparseIndices",r,t,e),s=v("outputShape",r,t,e),i=v("sparseValues",r,t,e),a=v("defaultValue",r,t,e);return[n.sparseToDense(o,i,s,i.dtype===a.dtype?a:n.cast(a,i.dtype))]}case"TensorScatterUpdate":{let o=v("indices",r,t,e),s=v("values",r,t,e),i=v("tensor",r,t,e);return[n.tensorScatterUpdate(i,o,s)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var NF=(r,t,e,n=ae)=>{switch(r.op){case"SparseFillEmptyRows":{let{outputIndices:o,outputValues:s,emptyRowIndicator:i,reverseIndexMap:a}=n.sparse.sparseFillEmptyRows(v("indices",r,t,e),v("values",r,t,e),v("denseShape",r,t,e),v("defaultValue",r,t,e));return[o,s,i,a]}case"SparseReshape":{let{outputIndices:o,outputShape:s}=n.sparse.sparseReshape(v("inputIndices",r,t,e),v("inputShape",r,t,e),v("newShape",r,t,e));return[o,s]}case"SparseSegmentMean":return[n.sparse.sparseSegmentMean(v("data",r,t,e),v("indices",r,t,e),v("segmentIds",r,t,e))];case"SparseSegmentSum":return[n.sparse.sparseSegmentSum(v("data",r,t,e),v("indices",r,t,e),v("segmentIds",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var kF=(r,t,e,n=ae)=>{switch(r.op){case"FFT":return[n.fft(v("x",r,t,e))];case"IFFT":return[n.ifft(v("x",r,t,e))];case"RFFT":return[n.rfft(v("x",r,t,e))];case"IRFFT":return[n.irfft(v("x",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var TF=(r,t,e,n=ae)=>{switch(r.op){case"StaticRegexReplace":return[n.string.staticRegexReplace(v("input",r,t,e),v("pattern",r,t,e),v("rewrite",r,t,e),v("replaceGlobal",r,t,e))];case"StringNGrams":{let{nGrams:o,nGramsSplits:s}=n.string.stringNGrams(v("data",r,t,e),v("dataSplits",r,t,e),v("separator",r,t,e),v("nGramWidths",r,t,e),v("leftPad",r,t,e),v("rightPad",r,t,e),v("padWidth",r,t,e),v("preserveShortSequences",r,t,e));return[o,s]}case"StringSplit":{let{indices:o,values:s,shape:i}=n.string.stringSplit(v("input",r,t,e),v("delimiter",r,t,e),v("skipEmpty",r,t,e));return[o,s,i]}case"StringToHashBucketFast":return[n.string.stringToHashBucketFast(v("input",r,t,e),v("numBuckets",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var _F=(r,t,e,n=ae)=>{switch(r.op){case"Cast":return[n.cast(v("x",r,t,e),v("dtype",r,t,e))];case"ExpandDims":{let o=v("axis",r,t,e);return[n.expandDims(v("x",r,t,e),o)]}case"Squeeze":{let o=v("axis",r,t,e);return[n.squeeze(v("x",r,t,e),o)]}case"Reshape":return[n.reshape(v("x",r,t,e),v("shape",r,t,e))];case"EnsureShape":return[n.ensureShape(v("x",r,t,e),v("shape",r,t,e))];case"MirrorPad":return[n.mirrorPad(v("x",r,t,e),v("padding",r,t,e),v("mode",r,t,e))];case"PadV2":case"Pad":return[n.pad(v("x",r,t,e),v("padding",r,t,e),v("constantValue",r,t,e))];case"SpaceToBatchND":{let o=v("blockShape",r,t,e),s=v("paddings",r,t,e);return[n.spaceToBatchND(v("x",r,t,e),o,s)]}case"BatchToSpaceND":{let o=v("blockShape",r,t,e),s=v("crops",r,t,e);return[n.batchToSpaceND(v("x",r,t,e),o,s)]}case"DepthToSpace":{let o=v("blockSize",r,t,e),s=v("dataFormat",r,t,e).toUpperCase();return[n.depthToSpace(v("x",r,t,e),o,s)]}case"BroadcastTo":return[n.broadcastTo(v("x",r,t,e),v("shape",r,t,e))];case"BroadcastArgs":return[n.broadcastArgs(v("s0",r,t,e),v("s1",r,t,e))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Nk(r,t,e,n,o=B){let s=((i,a,u)=>{switch(i.category){case"arithmetic":return o(()=>nF(i,a,u));case"basic_math":return o(()=>oF(i,a,u));case"control":return cF(i,a,u);case"convolution":return o(()=>mF(i,a,u));case"creation":return o(()=>fF(i,a,u));case"dynamic":return dF(i,a,u);case"evaluation":return o(()=>hF(i,a,u));case"image":return o(()=>yF(i,a,u));case"graph":return o(()=>gF(i,a,u));case"logical":return o(()=>bF(i,a,u));case"matrices":return o(()=>wF(i,a,u));case"normalization":return o(()=>IF(i,a,u));case"ragged":return o(()=>CF(i,a,u));case"reduction":return o(()=>vF(i,a,u));case"slice_join":return o(()=>SF(i,a,u));case"sparse":return o(()=>NF(i,a,u));case"spectral":return o(()=>kF(i,a,u));case"string":return o(()=>TF(i,a,u));case"transformation":return o(()=>_F(i,a,u));case"hash_table":return xF(i,a,u,n);case"custom":let l=zb(i.op);if(l&&l.customExecutor)return l.customExecutor(new Zb(i,a,u));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(r,t,e);return y.isPromise(s)?s.then(i=>[].concat(i)):[].concat(s)}var Kh=class{constructor(t={},e={},n={},o={},s){this.weightMap=t,this.tensorArrayMap=e,this.tensorListMap=n,this.functionMap=o,this.parseNodeNameCache=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(t,e){return{id:t,frameName:e,iterationId:0}}set currentContext(t){this.contexts!==t&&(this.contexts=t,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let t=[];for(let e=0;e<this.contexts.length-1;e++){let n=this.contexts.slice(0,this.contexts.length-e);t.push(this.contextIdforContexts(n))}t.push(""),this._currentContextIds=t}contextIdforContexts(t){return t?t.map(e=>e.id===0&&e.iterationId===0?"":`${e.frameName}-${e.iterationId}`).join("/"):""}enterFrame(t){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,t)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(t){return this.weightMap[t]}addTensorArray(t){this.tensorArrayMap[t.id]=t}getTensorArray(t){return this.tensorArrayMap[t]}addTensorList(t){this.tensorListMap[t.id]=t}getTensorList(t){return this.tensorListMap[t]}dispose(t){for(let e in this.tensorArrayMap)this.tensorArrayMap[e].clearAndClose(t);for(let e in this.tensorListMap)this.tensorListMap[e].clearAndClose(t)}};function kk(r,t,e,n){let o=new Set,s=[],i=null,a=null,u=new Set,l=new Set(Object.keys(r).map(m=>vn(m)[0]));n=n||[];let c=new Set(n.map(m=>vn(m.name)[0])),p=[...t];for(;p.length>0;){let m=p.pop();if((Ku(m)||jQ(m)||XQ(m))&&i==null&&(i=m,a=i.children.map(f=>f.name).filter(f=>o.has(f))),o.add(m.name),e[m.name]==null&&!l.has(m.name)&&!c.has(m.name)){if(m.inputs.length===0){s.push(m.name);continue}m.inputs.forEach(f=>{u.has(f.name)||(u.add(f.name),p.push(f))})}}return{inputs:r,outputs:t,usedNodes:o,missingInputs:s,dynamicNode:i,syncInputs:a}}function EF(r,t){let{usedNodes:e,inputs:n}=t,o=Object.keys(n).map(g=>vn(g)[0]).map(g=>r.nodes[g]),s=r.initNodes||[],i=g=>e.has(typeof g=="string"?g:g.name);function a(g){return[...new Map(g.map(x=>[x.name,x])).values()]}let u=a([...o,...r.weights,...s]).filter(i),l=a([...u,...Object.values(r.nodes)]).filter(i),c=new Map(l.map(g=>[g.name,g])),p={};for(let g of l){p[g.name]=p[g.name]||0;for(let x of g.children)i(x)||(p[x.name]=Number.POSITIVE_INFINITY),p[x.name]=(p[x.name]||0)+1}let m=Object.entries(p).filter(([,g])=>g===0).map(([g])=>g),f=[...m];for(;m.length>0;){let g=m.pop(),x=c.get(g);for(let b of x.children.filter(i))--p[b.name]===0&&(f.push(b.name),m.push(b.name))}let d=f.map(g=>c.get(g)),h=WQ(d,u);return UQ(h,u),h}function WQ(r,t){let e=new Map(r.map(i=>[i.name,i])),n=t.map(i=>i.name),o=new Set(n);for(;n.length>0;){let i=n.pop(),a=e.get(i);for(let u of a.children)!e.has(u.name)||o.has(u.name)||(o.add(u.name),n.push(u.name))}return r.filter(i=>o.has(i.name))}var ad=class extends Error{constructor(t){super(`NodesExecutionOrderError: ${t}`)}};function UQ(r,t){let e=new Map(r.map((a,u)=>[a.name,u])),n=new Set(t.map(a=>a.name)),o=a=>n.has(typeof a=="string"?a:a.name),s=new Set(r.map(a=>a.name)),i=a=>s.has(typeof a=="string"?a:a.name);for(let a of r){for(let u of a.children.filter(i)){if(!e.has(u.name))throw new ad(`Child ${u.name} of node ${a.name} is unreachable.`);if(e.get(a.name)>e.get(u.name))throw new ad(`Node ${a.name} is scheduled to run after its child ${u.name}.`)}if(!o(a))for(let u of a.inputs){if(!e.has(u.name))throw new ad(`Input ${u.name} of node ${a.name} is unreachable.`);if(e.get(u.name)>e.get(a.name))throw new ad(`Node ${a.name} is scheduled to run before its input ${u.name}.`)}}}function AF(r){let t=new Map(r.map((a,u)=>[a.name,u])),e=Number.MAX_SAFE_INTEGER,n=r.map((a,u)=>Ku(a)?e:u),o=a=>{let u=n[t.get(a.name)];return u==null?-1:u},s=r.map((a,u)=>a.children.map(o).reduce((l,c)=>Math.max(l,c),n[u])),i=new Map;for(let a=0;a<r.length;++a){let u=s[a];if(u===e)continue;let l=r[a],c=r[u];i.has(c.name)||i.set(c.name,[]),i.get(c.name).push(l)}return i}var HQ=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),qQ=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),KQ=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Ku(r){return HQ.has(r.op)}function jQ(r){return qQ.has(r.op)}function XQ(r){return KQ.has(r.op)}var op=class{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(t){let e=Object.keys(t).map(n=>t[n].map(o=>o.id));this._weightIds=[].concat(...e),this._weightMap=t}set resourceManager(t){this._resourceManager=t}get inputs(){return this._inputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(t=>t.signatureKey||t.name)}get outputNodes(){return this._outputs.map(t=>{let e=t.signatureKey||t.name;return t.defaultOutput?`${e}:${t.defaultOutput}`:e})}get functions(){return Object.keys(this._functions).reduce((t,e)=>(t[e]=this._functions[e].signature,t),{})}constructor(t,e){this.graph=t,this.parent=e,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=t.outputs,this._inputs=t.inputs,this._initNodes=t.initNodes,this._signature=t.signature,this._functions=t.functions,t.functions!=null&&Object.keys(t.functions).forEach(n=>{this._functionExecutorMap[n]=new op(t.functions[n],this)})}getCompilationKey(t,e){let n=t.map(s=>s.name).sort(),o=e.map(s=>s.name).sort();return n.join(this.SEPARATOR)+"--"+o.join(this.SEPARATOR)}compile(t,e){let n=kk(t,e,this.weightMap,this._initNodes),{missingInputs:o,dynamicNode:s,syncInputs:i}=n;if(s!=null)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${i}]`);if(o.length>0){let l=e.map(p=>p.name),c=Object.keys(t);throw new Error(`Cannot compute the outputs [${l}] from the provided inputs [${c}]. Missing the following inputs: [${o}]`)}let a=EF(this.graph,n),u=AF(a);return{orderedNodes:a,nodeLiveUntilMap:u}}cloneAndKeepTensor(t){if(t==null)return null;let e=t.clone();return $e(e),e}cloneTensorList(t){return t?t.map(n=>this.cloneAndKeepTensor(n)):null}cloneTensorMap(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,this.cloneTensorList(n)]))}execute(t,e){this.disposeIntermediateTensors(),t=this.mapInputs(t);let n=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e);let o=n.map(m=>this.graph.nodes[vn(m)[0]]),s=e.map(m=>vn(m)[0]),i=new Set(s),a=s.map(m=>this.graph.nodes[m]);a.length===0&&(a=this._outputs);let u=this.getCompilationKey(o,a),l=this.compiledMap.get(u);l==null&&(l=this.compile(t,a),this.compiledMap.set(u,l));try{this.keepIntermediateTensors=L().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(m){this.keepIntermediateTensors=!1,console.warn(m.message)}let c={},p={};return B(()=>{let m=new Kh(this.weightMap,c,p,this.functionExecutorMap,this.parseNodeNameCache),f=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(t).forEach(x=>{let[b,w]=vn(x,m),I=[];I[w]=t[x],f[b]=I,this.keepIntermediateTensors&&(this.clonedTensorsMap[b]=this.cloneTensorList(I))});let d=this.getFrozenTensorIds(f),{orderedNodes:h,nodeLiveUntilMap:g}=l;for(let x of h){if(f[x.name])continue;let b=Nk(x,f,m,this._resourceManager);if(y.isPromise(b))throw new Error(`The execution of the op '${x.op}' returned a promise. Please use model.executeAsync() instead.`);f[x.name]=b,this.keepIntermediateTensors&&(this.clonedTensorsMap[x.name]=this.cloneTensorList(b)),this.checkTensorForDisposalWithNodeLiveUntilInfo(x,f,m,d,i,g.get(x.name))}return this.parent==null&&m.dispose(d),e.map(x=>pr(x,f,m))})}getFrozenTensorIds(t){let e=[].concat.apply([],Object.keys(t).map(n=>t[n]).map(n=>n.map(o=>o.id)));return new Set(e)}checkTensorForDisposal(t,e,n,o,s,i,a){if(!(Ku(e)||i.has(t))){for(let u of n[t])u!=null&&(a[u.id]=(a[u.id]||0)+e.children.length);for(let u of e.inputs){if(Ku(u))continue;let l=nk(u.name,n,o);if(l!=null)for(let c of l){if(!c||c.kept||s.has(c.id))continue;let p=a[c.id];p===1?(c.dispose(),delete a[c.id]):p!=null&&a[c.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(t,e,n,o,s,i){function a(u){return Ku(u)||s.has(u.name)}if(!(Ku(t)||i==null))for(let u of i){if(a(u))continue;let l=nk(u.name,e,n);for(let c of l)!c||c.kept||o.has(c.id)||c.dispose()}}async executeAsync(t,e){return this._executeAsync(t,e)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(t=>{for(let e of t)e&&!e.isDisposed&&e.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(t,e,n=!1,o={},s={}){this.disposeIntermediateTensors(),n||(t=this.mapInputs(t),this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e));try{this.keepIntermediateTensors=L().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(m){this.keepIntermediateTensors=!1,console.warn(m.message)}let i=new Kh(this.weightMap,o,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));let a=await this.executeWithControlFlow(t,i,e,n),u=e.map(m=>pr(m,a,i)),l=u.map(m=>m.id),c=Object.keys(t).map(m=>t[m].id),p=new Set([...l,...c,...this.weightIds]);return Object.values(a).forEach(m=>{m.forEach(f=>{f&&!f.isDisposed&&!p.has(f.id)&&f.dispose()})}),this.parent==null&&i.dispose(p),u}async executeFunctionAsync(t,e,n){let o=t.reduce((s,i,a)=>(s[this.inputs[a].name]=i,s),{});return this._executeAsync(o,this.outputNodes,!0,e,n)}async executeWithControlFlow(t,e,n,o){let s=Object.keys(t),i=s.map(I=>this.graph.nodes[vn(I)[0]]),a=n.map(I=>vn(I)[0]),u=new Set(a),l=a.map(I=>this.graph.nodes[I]);l.length===0&&(l=this._outputs);let{usedNodes:c,missingInputs:p,dynamicNode:m,syncInputs:f}=kk(t,l,this.weightMap,this._initNodes),d=[...i,...this.graph.weights,...this._initNodes||[]].map(I=>({node:I,contexts:e.currentContext})),h=Object.assign({},this.weightMap);Object.keys(t).forEach(I=>{let[N,E]=vn(I),A=[];A[E]=t[I],h[N]=A});let g={},x=this.getFrozenTensorIds(h),b={};for(;d.length>0;){let I=this.processStack(i,d,e,h,b,x,u,g,c);await Promise.all(I)}m==null&&!o&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let w=l.filter(I=>!Ku(I)&&!pr(I.name,h,e)).map(I=>I.name);if(w.length>0){let I="";throw m!=null&&(I=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${f}]`),new Error(`Cannot compute the outputs [${w}] from the provided inputs [${s}]. Consider providing the following inputs: [${p}]. ${I}`)}return h}processStack(t,e,n,o,s,i,a,u,l){let c=[];for(;e.length>0;){let p=e.pop();n.currentContext=p.contexts;let m="";if(p.node.op==="Enter"&&v("isConstant",p.node,o,n)&&([m]=Ii(p.node.name,n)),o[p.node.name]==null){let f=Nk(p.node,o,n,this._resourceManager);m||([m]=Ii(p.node.name,n));let d=n.currentContext;y.isPromise(f)?c.push(f.then(h=>(o[m]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[m]=this.cloneTensorList(h)),n.currentContext=d,this.checkTensorForDisposal(m,p.node,o,n,i,a,u),this.processChildNodes(p.node,e,n,o,s,l),h))):(o[m]=f,this.keepIntermediateTensors&&(this.clonedTensorsMap[m]=this.cloneTensorList(f)),this.checkTensorForDisposal(m,p.node,o,n,i,a,u),this.processChildNodes(p.node,e,n,o,s,l))}else this.processChildNodes(p.node,e,n,o,s,l)}return c}processChildNodes(t,e,n,o,s,i){t.children.forEach(a=>{let[u]=Ii(a.name,n);s[u]||!i.has(a.name)||(a.op==="Merge"?a.inputNames.some(l=>!!pr(l,o,n))&&(s[u]=!0,e.push({contexts:n.currentContext,node:a})):a.inputNames.every(l=>!!pr(l,o,n))&&(s[u]=!0,e.push({contexts:n.currentContext,node:a})))})}dispose(){Object.keys(this.weightMap).forEach(t=>this.weightMap[t].forEach(e=>e.dispose()))}checkInputShapeAndType(t){Object.keys(t).forEach(e=>{let n=t[e],[o]=vn(e),s=this.graph.nodes[o];if(s.attrParams.shape&&s.attrParams.shape.value){let i=s.attrParams.shape.value,a=i.length===n.shape.length&&n.shape.every((u,l)=>i[l]===-1||i[l]===u);y.assert(a,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${i}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&y.assert(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(t){var e,n;let o={};for(let s in t){let i=(n=(e=this._signature)===null||e===void 0?void 0:e.inputs)===null||n===void 0?void 0:n[s];i!=null?o[i.name]=t[s]:o[s]=t[s]}return o}checkInputs(t){let e=Object.keys(t).filter(n=>{let[o]=vn(n);return this.graph.nodes[o]==null});if(e.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${e}] that are not part of graph`)}mapOutputs(t){return t.map(e=>{var n,o;let s=(o=(n=this._signature)===null||n===void 0?void 0:n.outputs)===null||o===void 0?void 0:o[e];return s!=null?s.name:e},{})}checkOutputs(t){t.forEach(e=>{let[n]=vn(e);if(!this.graph.nodes[n])throw new Error(`The output '${e}' is not found in the graph`)})}};var ew=class{constructor(t={},e={}){this.hashTableNameToHandle=t,this.hashTableMap=e}addHashTable(t,e){this.hashTableNameToHandle[t]=e.handle,this.hashTableMap[e.id]=e}getHashTableHandleByName(t){return this.hashTableNameToHandle[t]}getHashTableById(t){return this.hashTableMap[t]}dispose(){for(let t in this.hashTableMap)this.hashTableMap[t].clearAndClose(),delete this.hashTableMap[t];for(let t in this.hashTableNameToHandle)this.hashTableNameToHandle[t].dispose(),delete this.hashTableNameToHandle[t]}};var YQ="?tfjs-format=file",ZQ="model.json",jh=class{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(t,e={},n=Lr){this.modelUrl=t,this.loadOptions=e,this.version="n/a",this.io=n,e==null&&(this.loadOptions={}),this.resourceManager=new ew}findIOHandler(){let t=this.modelUrl;if(t.load!=null)this.handler=t;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(t,this.loadOptions);else{let e=this.io.getLoadHandlers(t,this.loadOptions);if(e.length===0)e.push(this.io.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error(`Found more than one (${e.length}) load handlers for URL '${[t]}'`);this.handler=e[0]}}load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let t=this.handler.load();return y.isPromise(t)?t.then(e=>this.loadSync(e)):this.loadSync(t)}loadSync(t){this.artifacts=t;let e=this.artifacts.modelTopology,n=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let s=this.artifacts.userDefinedMetadata;s.signature!=null&&(n=s.signature),s.structuredOutputKeys!=null&&(this.structuredOutputKeys=s.structuredOutputKeys)}this.signature=n,this.version=`${e.versions.producer}.${e.versions.minConsumer}`;let o=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new op(qh.Instance.transformGraph(e,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(o),this.executor.resourceManager=this.resourceManager,t.modelInitializer!=null&&t.modelInitializer.node!=null){let s=qh.Instance.transformGraph(t.modelInitializer);this.initializer=new op(s),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=t.initializerSignature}return!0}async save(t,e){if(typeof t=="string"){let n=this.io.getSaveHandlers(t);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${t}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${t}'`);t=n[0]}if(t.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return t.save(this.artifacts)}addStructuredOutputNames(t){if(this.structuredOutputKeys){let e=t instanceof Ot?[t]:t,n={};return e.forEach((o,s)=>n[this.structuredOutputKeys[s]]=o),n}return t}predict(t,e){let n=this.execute(t,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(t,e){let n=await this.executeAsync(t,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(t){var e;if(!(t instanceof Ot)&&!Array.isArray(t)){let s=(e=this.signature)===null||e===void 0?void 0:e.inputs;if(s!=null)for(let i in s){let a=s[i];a.resourceId!=null&&(t[i]=this.resourceIdToCapturedInput[a.resourceId])}return t}t=Array.isArray(t)?t:[t];let n=Object.keys(this.resourceIdToCapturedInput).length;if(t.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${t.length} input tensors provided.`);let o=0;return this.inputNodes.reduce((s,i)=>{var a,u,l;let c=(l=(u=(a=this.signature)===null||a===void 0?void 0:a.inputs)===null||u===void 0?void 0:u[i])===null||l===void 0?void 0:l.resourceId;return c!=null?s[i]=this.resourceIdToCapturedInput[c]:s[i]=t[o++],s},{})}normalizeOutputs(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]}executeInitializerGraph(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(t){if(this.resourceIdToCapturedInput={},this.initializerSignature){let e=this.initializerSignature.outputs,n=Object.keys(e);for(let o=0;o<n.length;o++){let s=n[o],i=e[s];this.resourceIdToCapturedInput[i.resourceId]=t[o]}}}execute(t,e){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),t=this.normalizeInputs(t),e=this.normalizeOutputs(e);let n=this.executor.execute(t,e);return n.length>1?n:n[0]}async executeAsync(t,e){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),t=this.normalizeInputs(t),e=this.normalizeOutputs(e);let n=await this.executor.executeAsync(t,e);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(t){return Object.keys(t).reduce((e,n)=>(e[n]=[t[n]],e),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Tt(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}};async function JQ(r,t={},e=Lr){if(r==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&typeof r=="string"&&(r=ttt(r));let n=new jh(r,t,e);return await n.load(),n}function QQ(r){if(r==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(r instanceof Array){let[n,o]=r;if(!n)throw new Error("modelJSON must be the first element of the array");if(!o||!(o instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");let s=Lr.getWeightSpecs(n.weightsManifest),i=Lr.getModelArtifactsForJSONSync(n,s,o);t=Lr.fromMemorySync(i)}else if("load"in r)t=r;else if("modelTopology"in r&&"weightSpecs"in r&&"weightData"in r)t=Lr.fromMemorySync(r);else throw new Error("Unknown model format");let e=new jh(t);return e.load(),e}function ttt(r){return r.endsWith("/")||(r=r+"/"),`${r}${ZQ}${YQ}`}var DF="4.7.0";var ZF={};Kt(ZF,{CSVDataset:()=>cd,Dataset:()=>vi,FileDataSource:()=>hd,TextLineDataset:()=>ud,URLDataSource:()=>gd,array:()=>VF,csv:()=>qF,func:()=>KF,generator:()=>jF,microphone:()=>YF,version_data:()=>Kk,webcam:()=>XF,zip:()=>GF});var BF=Xl(bh());var MF=Xl(bh());function $F(r,t){return rw(r,t)}function rw(r,t,e=new Map,n=new Set){if(r==null)return null;if(typeof Blob=="function"&&r instanceof Blob)return r.slice();if(n.has(r))throw new Error("Circular references are not supported.");if(e.has(r))return e.get(r);let o=t(r);if(o.recurse&&o.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(o.recurse)if(ju(r)){let s=Array.isArray(r)?[]:{};n.add(r);for(let i in r){let a=r[i],u=rw(a,t,e,n);s[i]=u}return n.delete(r),r.__proto__&&(s.__proto__=r.__proto__),s}else throw new Error(`Can't recurse into non-iterable type: ${r}`);else return e.set(r,o.value),o.value}function RF(r,t=_k){return FF(r,t)}function FF(r,t,e=new Set){let n=r[0];if(e.has(n))throw new Error("Circular references are not supported.");let o=t(r);if(o.recurse&&o.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(o.recurse)if(ju(n)){let s=Array.isArray(n)?[]:{};e.add(n);for(let i in n){let a=r.map(l=>l[i]),u=FF(a,t,e);s[i]=u}return e.delete(n),s}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return o.value}function _k(r){return r===null?null:ju(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function nw(r,t){let e=new Map;rw(r,t,e);for(let o of Array.from(e.keys())){let s=e.get(o);if(y.isPromise(s)){let i=await s;e.set(o,i)}}return rw(r,t,e)}function ju(r){let t=!1;if(L().get("IS_BROWSER"))t=r instanceof TextDecoder;else{let{StringDecoder:e}=Tk();t=r instanceof e}return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof Ot)&&!(r instanceof Promise)&&!t)}function OF(r){return r==null||ett(r)||Array.isArray(r)||typeof r=="object"&&r instanceof Ot||y.isTypedArray(r)}function ett(r){return r===null||typeof r!="object"&&typeof r!="function"}function PF(r){return $F(r,rtt)}function rtt(r){return r instanceof Ot?{value:r.clone(),recurse:!1}:ju(r)?{value:null,recurse:!0}:{value:r,recurse:!1}}var ld=class{constructor(t){if(this.capacity=t,this.begin=0,this.end=0,t==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(t<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(t),this.doubledCapacity=2*t}wrap(t){for(;t<0;)t+=this.doubledCapacity;return t%this.doubledCapacity}get(t){if(t<0)throw new RangeError("Can't get item at a negative index.");return this.data[t%this.capacity]}set(t,e){if(t<0)throw new RangeError("Can't set item at a negative index.");this.data[t%this.capacity]=e}length(){let t=this.end-this.begin;return t<0&&(t=this.doubledCapacity+t),t}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,t),this.end=this.wrap(this.end+1)}pushAll(t){for(let e of t)this.push(e)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let t=this.get(this.end);return this.set(this.end,void 0),t}unshift(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,t)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),t}shuffleExcise(t){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.wrap(this.begin+t),n=this.get(e);return this.set(e,this.pop()),n}};var sp=class extends ld{constructor(){super(sp.INITIAL_CAPACITY)}isFull(){return!1}push(t){super.isFull()&&this.expand(),super.push(t)}unshift(t){super.isFull()&&this.expand(),super.unshift(t)}expand(){let t=this.capacity*2,e=new Array(t),n=this.length();for(let o=0;o<n;o++)e[o]=this.get(this.wrap(this.begin+o));this.data=e,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}};sp.INITIAL_CAPACITY=32;function Vk(r){return new Ek(r)}function Xh(r){return new Ak(r)}function LF(r,t){return new sw(r,t)}function zF(r,t=Ll.FAIL){return new zk(r,t)}var tr=class{async toArray(){let t=[],e=await this.next();for(;!e.done;)t.push(e.value),e=await this.next();return t}async toArrayForTest(){let t=this.prefetch(100),e=[],n=await t.next();for(;!n.done;)e.push(n.value),n=await t.next();return e}async resolveFully(){let t=await this.next();for(;!t.done;)t=await this.next()}async resolveWhile(t){let e=await this.next(),n=t(e.value);for(;!e.done&&n;)e=await this.next(),n=t(e.value)}handleErrors(t){return new Mk(this,t)}filter(t){return new Ok(this,t)}map(t){return new Pk(this,t)}mapAsync(t){return new ow(this,t)}serialMapAsync(t){return new ow(this,t).serial()}flatmap(t){return new Lk(this,t)}async forEachAsync(t){return this.map(t).resolveFully()}async serialForEach(t){return this.serialMapAsync(t).resolveWhile(e=>e===!0)}rowMajorBatch(t,e=!0){return new Fk(this,t,e)}columnMajorBatch(t,e=!0,n=_k){return this.rowMajorBatch(t,e).map(s=>RF(s,n))}concatenate(t,e){return new sw(Vk([this,t]),e)}take(t){return t<0||t==null?this:new Rk(this,t)}skip(t){return t<0||t==null?this:new $k(this,t)}prefetch(t){return new iw(this,t)}shuffle(t,e){return new Bk(this,t,e)}serial(){return new Dk(this)}},Ek=class extends tr{constructor(t){super(),this.items=t,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let t=this.items[this.trav];return this.trav++,{value:PF(t),done:!1}}},Ak=class extends tr{constructor(t){super(),this.nextFn=t}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(t){throw t.message=`Error thrown while iterating through a dataset: ${t.message}`,t}}},Dk=class extends tr{constructor(t){super(),this.upstream=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},$k=class extends tr{constructor(t,e){super(),this.upstream=t,this.maxCount=e,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let t=await this.upstream.next();if(t.done)return t;Tt(t.value)}return this.upstream.next()}},Rk=class extends tr{constructor(t,e){super(),this.upstream=t,this.maxCount=e,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},Fk=class extends tr{constructor(t,e,n=!0){super(),this.upstream=t,this.batchSize=e,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let t=[];for(;t.length<this.batchSize;){let e=await this.upstream.next();if(e.done)return this.enableSmallLastBatch&&t.length>0?{value:t,done:!1}:{value:null,done:!0};t.push(e.value)}return{value:t,done:!1}}},Ok=class extends tr{constructor(t,e){super(),this.upstream=t,this.predicate=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let t=await this.upstream.next();if(t.done||this.predicate(t.value))return t;Tt(t.value)}}},Pk=class extends tr{constructor(t,e){super(),this.upstream=t,this.transform=e}summary(){return`${this.upstream.summary()} -> Map`}async next(){let t=await this.upstream.next();if(t.done)return{value:null,done:!0};let e=So.getTensorsInContainer(t.value),n=this.transform(t.value),o=So.getTensorsInContainer(n);for(let s of e)So.isTensorInList(s,o)||s.dispose();return{value:n,done:!1}}},Mk=class extends tr{constructor(t,e){super(),this.upstream=t,this.handler=e,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(t){if(!this.handler(t))return{value:null,done:!0}}}},ow=class extends tr{constructor(t,e){super(),this.upstream=t,this.transform=e}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let t=await this.upstream.next();if(t.done)return{value:null,done:!0};let e=So.getTensorsInContainer(t.value),n=await this.transform(t.value),o=So.getTensorsInContainer(n);for(let s of e)So.isTensorInList(s,o)||s.dispose();return{value:n,done:!1}}},ip=class extends tr{constructor(){super(),this.outputQueue=new sp,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}},Lk=class extends ip{constructor(t,e){super(),this.upstream=t,this.transform=e}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let t=await this.upstream.next();if(t.done)return!1;let e=So.getTensorsInContainer(t.value),n=this.transform(t.value),o=So.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let s of e)So.isTensorInList(s,o)||s.dispose();return!0}},sw=class extends tr{constructor(t,e){super(),this.baseErrorHandler=e,this.lastRead=null,this.iterator=null,this.moreIterators=t}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(t){if(await t,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let e=await this.iterator.next();return e.done?(this.iterator=null,this.readFromChain(t)):e}},Ll;(function(r){r[r.FAIL=0]="FAIL",r[r.SHORTEST=1]="SHORTEST",r[r.LONGEST=2]="LONGEST"})(Ll||(Ll={}));var zk=class extends tr{constructor(t,e=Ll.FAIL){super(),this.iterators=t,this.mismatchMode=e,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(t){await t;let e=0,n=0;function o(i){return i instanceof tr?{value:i.next().then(u=>(e++,u.done&&n++,u.value)),recurse:!1}:{value:null,recurse:!0}}let s=await nw(this.iterators,o);if(e===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case Ll.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Ll.SHORTEST:return{value:null,done:!0};case Ll.LONGEST:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},iw=class extends tr{constructor(t,e){super(),this.upstream=t,this.bufferSize=e,this.buffer=new ld(e)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let t=this.upstream.next();this.buffer.push(t)}}next(){return this.refill(),this.buffer.shift()}},Bk=class extends iw{constructor(t,e,n){super(t,e),this.upstream=t,this.windowSize=e,this.upstreamExhausted=!1,this.random=MF.alea(n||y.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(t){return Math.floor(this.random()*t)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let t=this.chooseIndex(),e=await this.buffer.shuffleExcise(t);if(e.done)this.upstreamExhausted=!0;else return this.refill(),e}return{value:null,done:!0}}};var vi=class{constructor(){this.size=null}batch(t,e=!0){let n=this;y.assert(t>0,()=>`batchSize needs to be positive, but it is
| ${t}`);let o;return this.size===1/0||this.size==null?o=this.size:e?o=Math.ceil(this.size/t):o=Math.floor(this.size/t),$n(async()=>(await n.iterator()).columnMajorBatch(t,e,ntt),o)}concatenate(t){let e=this,n;return this.size===1/0||t.size===1/0?n=1/0:this.size!=null&&t.size!=null?n=this.size+t.size:n=null,$n(async()=>(await e.iterator()).concatenate(await t.iterator()),n)}filter(t){let e=this,n;return this.size===1/0?n=1/0:n=null,$n(async()=>(await e.iterator()).filter(o=>B(()=>t(o))),n)}async forEachAsync(t){return(await this.iterator()).forEachAsync(t)}map(t){let e=this;return $n(async()=>(await e.iterator()).map(n=>B(()=>t(n))),this.size)}mapAsync(t){let e=this;return $n(async()=>(await e.iterator()).mapAsync(t),this.size)}prefetch(t){if(t==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let e=this;return $n(async()=>(await e.iterator()).prefetch(t),this.size)}repeat(t){let e=this,n;return this.size!=null&&t>0?n=this.size*t:t===0?n=0:this.size!=null&&(t===void 0||t<0)?n=1/0:n=null,$n(async()=>{let o=Xh(async()=>({value:await e.iterator(),done:!1}));return LF(o.take(t))},n)}skip(t){let e=this,n;return this.size!=null&&t>=0&&this.size>=t?n=this.size-t:this.size!=null&&(this.size<t||t===void 0||t<0)?n=0:n=null,$n(async()=>(await e.iterator()).skip(t),n)}shuffle(t,e,n=!0){if(t==null||t<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let o=this,s=BF.alea(e||y.now().toString());return $n(async()=>{let i=s.int32();return n&&(i+=s.int32()),(await o.iterator()).shuffle(t,i.toString())},this.size)}take(t){let e=this,n;return this.size!=null&&this.size>t?n=t:this.size!=null&&this.size<=t?n=this.size:n=null,$n(async()=>(await e.iterator()).take(t),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};vi.MAX_BUFFER_SIZE=1e4;function $n(r,t=null){return new class extends vi{constructor(){super(...arguments),this.size=t}async iterator(){return r()}}}function VF(r){return $n(async()=>Vk(r),r.length)}function GF(r){if(!ju(r))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(r))for(let e=0;e<r.length;e++)t=t==null?r[e].size:Math.min(t,r[e].size);else if(r instanceof Object)for(let e in r)t=t==null?r[e].size:Math.min(t,r[e].size);return $n(async()=>{let e=await nw(r,n=>{if(n instanceof vi)return{value:n.iterator(),recurse:!1};if(ju(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return zF(e,Ll.SHORTEST)},t)}function ntt(r){if(r===null)return null;let t=r[0];return OF(t)?{value:ott(r),recurse:!1}:{value:null,recurse:!0}}function ott(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Ot?qe(r):sr(r)}var ud=class extends vi{constructor(t){super(),this.input=t}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
| `).map(o=>(o.endsWith("\r")&&(o=o.slice(0,-1)),o))}};var aw='"',Yh=Symbol("out"),WF=Symbol("field"),lw=Symbol("quote"),Gk=Symbol("quoteafterquote"),UF=Symbol("quoteinquote"),cd=class extends vi{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let t=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&t&&y.assert(t.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=t);let e=this.fullColumnNames.reduce((o,s)=>(o[s]=o[s]+1||1,o),{}),n=Object.keys(e).filter(o=>e[o]>1);if(y.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let o of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(o)===-1)throw new Error('The key "'+o+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let n=e.value;return this.parseRow(n,!1)}else return null}constructor(t,e){super(),this.input=t,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new ud(t),e||(e={}),this.hasHeader=e.hasHeader!==!1,this.fullColumnNames=e.columnNames,this.columnConfigs=e.columnConfigs,this.configuredColumnsOnly=e.configuredColumnsOnly,e.delimWhitespace?(y.assert(e.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=e.delimiter?e.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let t=await this.base.iterator();return this.hasHeader&&(t=t.skip(1)),t.map(e=>this.makeDataElement(e))}makeDataElement(t){let e=this.parseRow(t),n={},o={};for(let s=0;s<this.fullColumnNames.length;s++){let i=this.fullColumnNames[s],a=this.columnConfigs?this.columnConfigs[i]:null;if(!(this.configuredColumnsOnly&&!a)){let u=e[s],l=null;if(u==="")if(a&&a.default!==void 0)l=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${i} is empty in this line: ${t}`);l=void 0}else{let c=Number(u);if(isNaN(c))a&&a.dtype==="bool"?l=this.getBoolean(u):l=u;else if(!a||!a.dtype)l=c;else switch(a.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(u);break;default:l=c}}a&&a.isLabel?o[i]=l:n[i]=l}}return Object.keys(o).length===0?n:{xs:n,ys:o}}getBoolean(t){return t==="1"||t.toLowerCase()==="true"?1:0}parseRow(t,e=!0){let n=[],o=0,s=t.length,i=Yh;for(let a=0;a<s;a++)switch(i){case Yh:switch(t.charAt(a)){case aw:o=a+1,i=lw;break;case this.delimiter:if(o=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),i=Yh;break;default:i=WF,o=a;break}break;case WF:switch(t.charAt(a)){case this.delimiter:n.push(t.substring(o,a)),i=Yh,o=a+1;break;default:}break;case lw:switch(t.charAt(a)){case aw:i=Gk;break;default:}break;case Gk:switch(t.charAt(a)){case this.delimiter:n.push(t.substring(o,a-1)),i=Yh,o=a+1;break;case aw:i=lw;break;default:i=UF;break}break;case UF:switch(t.charAt(a)){case aw:i=lw;break;default:}break;default:}if(i===Gk?n.push(t.substring(o,s-1)):n.push(t.substring(o)),e&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}};var pd=class extends tr{constructor(t){super(),this.microphoneConfig=t,this.isClosed=!1,this.fftSize=t.fftSize||1024;let e=Math.log2(this.fftSize);if(this.fftSize<0||e<4||e>14||!Number.isInteger(e))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=t.numFramesPerSpectrogram||43,this.sampleRateHz=t.sampleRateHz,this.columnTruncateLength=t.columnTruncateLength||this.fftSize,this.audioTrackConstraints=t.audioTrackConstraints,this.smoothingTimeConstant=t.smoothingTimeConstant||0,this.includeSpectrogram=t.includeSpectrogram!==!1,this.includeWaveform=t.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(t={}){if(!L().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let e=new pd(t);return await e.start(),e}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let t=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new t,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let e=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,e.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let t,e,n=await this.getAudioData();if(this.includeSpectrogram){let o=this.flattenQueue(n.freqDataQueue);t=this.getTensorFromAudioDataArray(o,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let o=this.flattenQueue(n.timeDataQueue);e=this.getTensorFromAudioDataArray(o,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:t,waveform:e},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let t=[],e=[],n=0;return new Promise(o=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&o({freqDataQueue:t,timeDataQueue:e}),t.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),e.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),o({freqDataQueue:t,timeDataQueue:e}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(t){let e=t[0].length,n=new Float32Array(t.length*e);return t.forEach((o,s)=>n.set(o,s*e)),n}getTensorFromAudioDataArray(t,e){let n=new Float32Array(y.sizeFromShape(e));return n.set(t,n.length-t.length),sr(n,e)}};var md=class extends tr{constructor(t,e){if(super(),this.webcamVideoElement=t,this.webcamConfig=e,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Ke([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,o=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-n)/2,i=(1-o)/2,a=s+n,u=o+i;this.cropBox=fi([i,s,u,a],[1,4])}else this.cropBox=fi([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(t,e={}){if(!L().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!e.resizeWidth||!e.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=e.resizeWidth,t.height=e.resizeHeight}let n=new md(t,e);return await n.start(),n}async start(){this.webcamConfig.facingMode&&y.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(t){throw t.message=`Error thrown while initializing video stream: ${t.message}`,t}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(t=>{this.webcamVideoElement.onloadedmetadata=()=>{t()}})}async next(){if(this.isClosed)return{value:null,done:!0};let t;try{t=Ay.fromPixels(this.webcamVideoElement)}catch(e){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(t),done:!1}}catch(e){throw new Error(`Error thrown cropping the video: ${e.message}`)}finally{t.dispose()}else return{value:t,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(t){return B(()=>{let e=ar(Q(t,"float32"),0),n;n=hn.cropAndResize(e,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let o=n.shape;return R(n,o.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}};var fd=class{};var Zh=class extends tr{split(t){return new Wk(this,t)}},Wk=class extends Zh{constructor(t,e){super(),this.upstream=t,this.impl=new Uk(t,e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Uk=class extends ip{constructor(t,e){super(),this.upstream=t,this.separator=e,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let t=await this.upstream.next();if(t.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let e=t.value.split(this.separator);e[0]=this.carryover+e[0];for(let n of e.slice(0,-1))this.outputQueue.push(n);return this.carryover=e[e.length-1],!0}};var uw=class extends tr{decodeUTF8(){return new Hk(this)}},Hk=class extends Zh{constructor(t){super(),this.upstream=t,this.impl=new qk(t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},qk=class extends ip{constructor(t){if(super(),this.upstream=t,L().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:e}=Tk();this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let t=await this.upstream.next(),e;if(t.done)return!1;e=t.value;let n;return L().get("IS_BROWSER")?n=this.decoder.decode(e,{stream:!0}):n=this.decoder.write(Buffer.from(e.buffer)),this.outputQueue.push(n),!0}};var dd=class extends uw{constructor(t,e={}){super(),this.file=t,this.options=e,y.assert(t instanceof Uint8Array||(L().get("IS_BROWSER")?t instanceof File||t instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=e.offset||0,this.chunkSize=e.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((e,n)=>{let o=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,o)));else{let s=new FileReader;s.onload=a=>{let u=s.result;if(u instanceof ArrayBuffer&&(u=new Uint8Array(u)),!(u instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));e(u)},s.onabort=a=>n(new Error("Aborted")),s.onerror=a=>n(new Error(a.type));let i=this.file.slice(this.offset,o);s.readAsArrayBuffer(i)}this.offset=o}),done:!1}}};async function HF(r,t={},e){let n,o;typeof r=="string"?n=r:(n=r.url,o=stt(r));let s=await(e||y.fetch)(n,o);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new dd(i,t)}else throw new Error(s.statusText)}var stt=r=>({method:r.method,headers:r.headers,body:r.body,mode:r.mode,credentials:r.credentials,cache:r.cache,redirect:r.redirect,referrer:r.referrer,integrity:r.integrity});function cw(r){return typeof r=="string"&&r.slice(0,7)==="file://"}var hd=class extends fd{constructor(t,e={}){super(),this.input=t,this.options=e}async iterator(){if(cw(this.input)&&L().get("IS_NODE")){let t=pw();this.input=t.readFileSync(this.input.slice(7))}return new dd(this.input,this.options)}};var gd=class extends fd{constructor(t,e={}){super(),this.url=t,this.fileOptions=e}async iterator(){return cw(this.url)?new hd(this.url,this.fileOptions).iterator():HF(this.url,this.fileOptions)}};function qF(r,t={}){return new cd(new gd(r),t)}function KF(r){let t=Xh(r);return $n(async()=>t)}function jF(r){return $n(async()=>{let t=await r();return Xh(()=>t.next())})}async function XF(r,t){return md.create(r,t)}async function YF(r){return pd.create(r)}var Kk="4.7.0";function tt(r,t){Array.isArray(r)||(r=[r]),r.forEach(e=>{e!=null&&y.assert(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var itt=jr.whereImpl,Xu=class extends Uo{nextDataId(){return Xu.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Da(this,Wn())}write(t,e,n){this.firstUse&&(this.firstUse=!1,L().get("IS_NODE")&&S.warn(`
| ============================
| Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details.
| ============================`));let o={id:this.nextDataId()};return this.data.set(o,{values:t,dtype:n,refCount:1}),o}makeTensorInfo(t,e,n){let o;if(e==="string"&&n!=null&&n.length>0&&y.isString(n[0])){let s=n.map(i=>y.encodeString(i));o=this.write(s,t,e)}else o=this.write(n,t,e);return{dataId:o,shape:t,dtype:e}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){let e=this.data.get(t);e.refCount++}decRef(t){if(this.data.has(t)){let e=this.data.get(t);e.refCount--}}move(t,e,n,o,s){this.data.set(t,{values:e,dtype:o,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){let{dtype:e,complexTensorInfos:n}=this.data.get(t);if(e==="complex64"){let o=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return S.mergeRealAndImagArrays(o,s)}return y.convertBackendValuesAndArrayBuffer(this.data.get(t).values,e)}bufferSync(t){let e=this.readSync(t.dataId);if(t.dtype==="string")try{let n=e.map(o=>y.decodeString(o));return wt(t.shape,t.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(t.shape,t.dtype,e)}makeOutput(t,e,n){return Wn().makeTensorFromTensorInfo(this.makeTensorInfo(e,n,t),this)}disposeData(t,e=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!e&&this.data.get(t).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(t);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){let e=y.now();return t(),{kernelMs:y.now()-e}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(t){tt([t],"where");let e=this.readSync(t.dataId);return itt(t.shape,e)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Xu.nextDataId=0;var Nw={};Kt(Nw,{addImpl:()=>Yk,bincountImpl:()=>bd,bincountReduceImpl:()=>mw,bitwiseAndImpl:()=>Zk,castImpl:()=>Xk,ceilImpl:()=>Jk,concatImpl:()=>ap,equalImpl:()=>Qk,expImpl:()=>eT,expm1Impl:()=>nT,floorDivImpl:()=>sT,floorImpl:()=>oT,gatherNdImpl:()=>fw,gatherV2Impl:()=>dw,greaterEqualImpl:()=>aT,greaterImpl:()=>iT,lessEqualImpl:()=>uT,lessImpl:()=>lT,linSpaceImpl:()=>hw,logImpl:()=>cT,maxImpl:()=>gw,maximumImpl:()=>pT,minimumImpl:()=>mT,multiplyImpl:()=>Jh,negImpl:()=>fT,notEqualImpl:()=>dT,prodImpl:()=>hT,raggedGatherImpl:()=>xw,raggedRangeImpl:()=>yw,raggedTensorToTensorImpl:()=>bw,rangeImpl:()=>up,rsqrtImpl:()=>gT,scatterImpl:()=>Si,sigmoidImpl:()=>_O,simpleAbsImpl:()=>jk,sliceImpl:()=>cp,sparseFillEmptyRowsImpl:()=>ww,sparseReshapeImpl:()=>Iw,sparseSegmentReductionImpl:()=>Cd,sqrtImpl:()=>DO,squaredDifferenceImpl:()=>yT,staticRegexReplaceImpl:()=>bT,stridedSliceImpl:()=>Cw,stringNGramsImpl:()=>pp,stringSplitImpl:()=>mp,stringToHashBucketFastImpl:()=>fp,subImpl:()=>IT,tileImpl:()=>vw,topKImpl:()=>Sw,transposeImpl:()=>wd,uniqueImpl:()=>dp});function jk(r){let t=new Float32Array(r.length);for(let e=0;e<r.length;++e)t[e]=Math.abs(r[e]);return t}var att=r=>{let{x:t}=r.inputs,e=r.backend;tt(t,"abs");let n=new Float32Array(y.sizeFromShape(t.shape)),o=e.data.get(t.dataId).values;return n=jk(o),e.makeOutput(n,t.shape,t.dtype)},JF={kernelName:$i,backendName:"cpu",kernelFunc:att};function Jt(r){return(t,e,n,o,s)=>{let i=S.assertAndGetBroadcastShape(t,e),a=i.length,u=y.computeStrides(i),l=y.sizeFromShape(i),c=y.getTypedArrayFromDType(s,l),p=t.length,m=e.length,f=y.computeStrides(t),d=y.computeStrides(e),h=S.getBroadcastDims(t,i),g=S.getBroadcastDims(e,i);if(h.length+g.length===0)for(let x=0;x<c.length;++x)c[x]=r(n[x%n.length],o[x%o.length]);else for(let x=0;x<c.length;++x){let b=y.indexToLoc(x,a,u),w=b.slice(-p);h.forEach(A=>w[A]=0);let I=y.locToIndex(w,p,f),N=b.slice(-m);g.forEach(A=>N[A]=0);let E=y.locToIndex(N,m,d);c[x]=r(n[I],o[E])}return[c,i]}}function Cr(r){let{inputs:t,backend:e}=r,{real:n,imag:o}=t,s=e.data.get(n.dataId).values,i=e.data.get(o.dataId).values,a=e.makeTensorInfo(n.shape,"complex64"),u=e.data.get(a.dataId);return u.complexTensorInfos={real:e.makeTensorInfo(n.shape,"float32",s),imag:e.makeTensorInfo(o.shape,"float32",i)},a}var QF={kernelName:zp,backendName:"cpu",kernelFunc:Cr};function xd(r,t,e="float32"){if(e==="complex64"){let o=xd(r,t,"float32"),s=xd(r,t,"float32");return Cr({inputs:{real:o,imag:s},backend:r})}let n=y.makeZerosTypedArray(y.sizeFromShape(t),e);return r.makeTensorInfo(t,e,n)}function Zr(r){let{inputs:t,backend:e}=r,{x:n}=t;return e.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var tO={kernelName:bo,backendName:"cpu",kernelFunc:Zr};function Mo(r){let{inputs:t,backend:e}=r,{input:n}=t,o=e.data.get(n.dataId).complexTensorInfos.real,s=e.data.get(o.dataId).values;return e.makeTensorInfo(o.shape,o.dtype,s)}var eO={kernelName:Yp,backendName:"cpu",kernelFunc:Mo};function Xk(r,t,e,n){if(n==="int32"){let o=Int32Array.from(r);return[t,"int32",o]}if(n==="bool"){let o=y.toTypedArray([0],e),[s,i]=Jt((a,u)=>a!==u?1:0)(t,[],r,o,"bool");return[i,"bool",s]}throw new Error(`Error in Cast: failed to cast ${e} to ${n}`)}function Lo(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return Zr({inputs:{x:o},backend:e});let c=xd(e,o.shape,o.dtype),p=Lo({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),m=Cr({inputs:{real:p,imag:c},backend:e});return e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(p),m}if(o.dtype==="complex64"){let c=Mo({inputs:{input:o},backend:e}),p=Lo({inputs:{x:c},backend:e,attrs:{dtype:s}});return e.disposeIntermediateTensorInfo(c),p}if(!y.hasEncodingLoss(o.dtype,s)){let c=Zr({inputs:{x:o},backend:e});return{dataId:c.dataId,shape:c.shape,dtype:s}}let i=e.data.get(o.dataId).values,[a,u,l]=Xk(i,o.shape,o.dtype,s);return e.makeTensorInfo(a,u,l)}var rO={kernelName:xo,backendName:"cpu",kernelFunc:Lo};function oe(r,t,e,n){return e==null?({inputs:o,backend:s})=>{let{a:i,b:a}=o,u=s;tt([i,a],r);let l=u.data.get(i.dataId).values,c=u.data.get(a.dataId).values,p=i.dtype==="string"?S.fromUint8ToStringArray(l):l,m=i.dtype==="string"?S.fromUint8ToStringArray(c):c,f=n||i.dtype,[d,h]=t(i.shape,a.shape,p,m,f);return u.makeTensorInfo(h,f,d)}:({inputs:o,backend:s})=>{let{a:i,b:a}=o,u=s;if(i.dtype==="complex64"||a.dtype==="complex64"){let l=Lo({inputs:{x:i},backend:u,attrs:{dtype:"complex64"}}),c=u.data.get(l.dataId),p=c.complexTensorInfos.real,m=c.complexTensorInfos.imag,f=u.data.get(p.dataId).values,d=u.data.get(m.dataId).values,h=Lo({inputs:{x:a},backend:u,attrs:{dtype:"complex64"}}),g=u.data.get(h.dataId),x=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,w=u.data.get(x.dataId).values,I=u.data.get(b.dataId).values,[N,E,A]=e(i.shape,a.shape,f,d,w,I),D=u.makeTensorInfo(A,"float32",N),F=u.makeTensorInfo(A,"float32",E),P=Cr({inputs:{real:D,imag:F},backend:u});return u.disposeIntermediateTensorInfo(l),u.disposeIntermediateTensorInfo(h),u.disposeIntermediateTensorInfo(D),u.disposeIntermediateTensorInfo(F),P}else{let l=u.data.get(i.dataId).values,c=u.data.get(a.dataId).values,p=n||i.dtype,[m,f]=t(i.shape,a.shape,l,c,p);return u.makeTensorInfo(f,p,m)}}}function yd(r){return(t,e,n,o,s,i)=>{let a=S.assertAndGetBroadcastShape(t,e),u=y.sizeFromShape(a),l=a.length,c=y.computeStrides(a),p=y.getTypedArrayFromDType("float32",u),m=y.getTypedArrayFromDType("float32",u),f=S.getBroadcastDims(t,a),d=S.getBroadcastDims(e,a),h=S.mergeRealAndImagArrays(n,o),g=S.mergeRealAndImagArrays(s,i),x=t.length,b=y.computeStrides(t),w=e.length,I=y.computeStrides(e);if(f.length+d.length===0)for(let N=0;N<p.length;N++){let E=N%h.length,A=N%g.length,D=r(h[E*2],h[E*2+1],g[A*2],g[A*2+1]);p[N]=D.real,m[N]=D.imag}else for(let N=0;N<p.length;N++){let E=y.indexToLoc(N,l,c),A=E.slice(-x);f.forEach(G=>A[G]=0);let D=y.locToIndex(A,x,b),F=E.slice(-w);d.forEach(G=>F[G]=0);let P=y.locToIndex(F,w,I),V=r(h[D*2],h[D*2+1],g[P*2],g[P*2+1]);p[N]=V.real,m[N]=V.imag}return[p,m,a]}}var Yk=Jt((r,t)=>r+t),ltt=yd((r,t,e,n)=>({real:r+e,imag:t+n})),Ca=oe(ao,Yk,ltt),nO={kernelName:ao,backendName:"cpu",kernelFunc:Ca};function bd(r,t,e,n,o){let s=y.sizeFromShape(n),i=y.makeZerosTypedArray(o,e);for(let a=0;a<r.length;a++){let u=r[a];if(u<0)throw new Error("Input x must be non-negative!");u>=o||(s>0?i[u]+=t[a]:i[u]+=1)}return i}function mw(r,t,e,n=!1){let o=r.shape[0],s=r.shape[1],i=wt([o,e],t.dtype);for(let a=0;a<o;a++)for(let u=0;u<s;u++){let l=r.get(a,u);if(l<0)throw new Error("Input x must be non-negative!");l>=e||(n?i.set(1,a,l):t.size>0?i.set(i.get(a,l)+t.get(a,u),a,l):i.set(i.get(a,l)+1,a,l))}return i}var Zk=Jt((r,t)=>r&t),utt=oe(Pa,Zk),oO={kernelName:Pa,backendName:"cpu",kernelFunc:utt};function Er(r){return(t,e,n)=>{let o=y.getArrayFromDType(e,t.length);for(let s=0;s<t.length;++s)o[s]=r(t[s],n);return o}}function At(r,t,e){let n=Er(t);return Rn(r,n,e)}function Rn(r,t,e){return({inputs:n,attrs:o,backend:s})=>{let{x:i}=n;tt(i,r);let a=s,u=a.data.get(i.dataId).values,l;if(i.dtype==="string"){if(!Array.isArray(u))throw new Error("String tensor's value was not an instance of Array");l=S.fromUint8ToStringArray(u)}else l=u;let c=e||i.dtype,p=t(l,c,o);return a.makeTensorInfo(i.shape,c,p)}}var Jk=Er(r=>Math.ceil(r)),ctt=Rn(rs,Jk),sO={kernelName:rs,backendName:"cpu",kernelFunc:ctt};function ap(r,t,e,n){let o=y.getArrayFromDType(e,y.sizeFromShape(t));if(n&&e!=="string"){let s=0;r.forEach(i=>{let a=y.sizeFromShape(i.shape);o.set(i.vals,s),s+=a})}else{let s=0;r.forEach(i=>{let a=e==="string"?S.fromUint8ToStringArray(i.vals):i.vals,u=0;for(let l=0;l<i.shape[0];++l){let c=l*t[1]+s;for(let p=0;p<i.shape[1];++p)o[c+p]=a[u++]}s+=i.shape[1]})}return o}var Qk=Jt((r,t)=>r===t?1:0),tT=oe(Wa,Qk,null,"bool"),iO={kernelName:Wa,backendName:"cpu",kernelFunc:tT};var eT=Er(r=>Math.exp(r)),rT=Rn(ds,eT,"float32"),aO={kernelName:ds,backendName:"cpu",kernelFunc:rT};var nT=Er(r=>Math.expm1(r)),ptt=Rn(hs,nT),lO={kernelName:hs,backendName:"cpu",kernelFunc:ptt};var oT=Er(r=>Math.floor(r)),mtt=Rn(gs,oT),uO={kernelName:gs,backendName:"cpu",kernelFunc:mtt};var sT=Jt((r,t)=>Math.floor(r/t)),ftt=oe(xs,sT,null,"int32"),cO={kernelName:xs,backendName:"cpu",kernelFunc:ftt};function fw(r,t,e,n,o,s,i,a,u){let l=wt([n,s],e);for(let c=0;c<n;c++){let p=[],m=0;for(let f=0;f<o;f++){let d=r[c*o+f];m+=d*i[f],p.push(d)}if(m<0||m>=u/s)throw new Error(`Invalid indices: ${p} does not index into ${a}`);for(let f=0;f<s;f++)l.values[c*s+f]=t.get(...t.indexToLoc(m*s+f))}return l}function dw(r,t,e){let n=wt(e,r.dtype);for(let o=0;o<n.size;++o){let i=n.indexToLoc(o).slice(),a=i[0],u=i[2],l=t.locToIndex([a,u]);i[2]=t.values[l];let c=r.locToIndex(i);0<=c&&c<r.values.length&&(n.values[o]=r.values[c])}return n}var iT=Jt((r,t)=>r>t?1:0),dtt=oe(qa,iT,null,"bool"),pO={kernelName:qa,backendName:"cpu",kernelFunc:dtt};var aT=Jt((r,t)=>r>=t?1:0),htt=oe(bs,aT,null,"bool"),mO={kernelName:bs,backendName:"cpu",kernelFunc:htt};var lT=Jt((r,t)=>r<t?1:0),gtt=oe(Ka,lT,null,"bool"),fO={kernelName:Ka,backendName:"cpu",kernelFunc:gtt};var uT=Jt((r,t)=>r<=t?1:0),xtt=oe(ja,uT,null,"bool"),dO={kernelName:ja,backendName:"cpu",kernelFunc:xtt};function hw(r,t,e){let n=(t-r)/(e-1),o=y.makeZerosTypedArray(e,"float32");o[0]=r;for(let s=1;s<o.length;s++)o[s]=o[s-1]+n;return o}var cT=Er(r=>Math.log(r)),ytt=Rn(Ss,cT),hO={kernelName:Ss,backendName:"cpu",kernelFunc:ytt};function gw(r,t,e,n){let o=y.getTypedArrayFromDType(n,y.sizeFromShape(e));for(let s=0;s<o.length;++s){let i=s*t,a=r[i];for(let u=0;u<t;++u){let l=r[i+u];(Number.isNaN(l)||l>a)&&(a=l)}o[s]=a}return o}var pT=Jt((r,t)=>Math.max(r,t)),btt=oe(_s,pT),gO={kernelName:_s,backendName:"cpu",kernelFunc:btt};var mT=Jt((r,t)=>Math.min(r,t)),wtt=oe($s,mT),xO={kernelName:$s,backendName:"cpu",kernelFunc:wtt};var Jh=Jt((r,t)=>r*t),Itt=yd((r,t,e,n)=>({real:r*e-t*n,imag:r*n+t*e})),lp=oe(Os,Jh,Itt),yO={kernelName:Os,backendName:"cpu",kernelFunc:lp};function fT(r,t,e){let n=y.createScalarValue(-1,e);return Jh([],t,n,r,e)}function Ctt(r){let{inputs:t,backend:e}=r,{x:n}=t;tt(n,"neg");let o=e.data.get(n.dataId).values,[s,i]=fT(o,n.shape,n.dtype);return e.makeTensorInfo(i,n.dtype,s)}var bO={kernelName:Vi,backendName:"cpu",kernelFunc:Ctt};var dT=Jt((r,t)=>r!==t?1:0),vtt=oe(el,dT,null,"bool"),wO={kernelName:el,backendName:"cpu",kernelFunc:vtt};function wd(r,t,e,n,o){let s=t.length,i=y.sizeFromShape(t),a=y.computeStrides(t),u=y.computeStrides(o),l=y.getTypedArrayFromDType(e,y.sizeFromShape(o));for(let c=0;c<i;++c){let p=y.indexToLoc(c,s,a),m=new Array(p.length);for(let d=0;d<m.length;d++)m[d]=p[n[d]];let f=y.locToIndex(m,s,u);l[f]=r[c]}return l}function Ge(r){let{inputs:t,attrs:e,backend:n}=r,{x:o}=t,{perm:s}=e;tt(o,"transpose");let i=o.shape.length,a=new Array(i);for(let p=0;p<a.length;p++)a[p]=o.shape[s[p]];let u=n.data.get(o.dataId).values,l=wd(u,o.shape,o.dtype,s,a);return{dataId:n.write(l,a,o.dtype),shape:a,dtype:o.dtype}}var IO={kernelName:uo,backendName:"cpu",kernelFunc:Ge};function hT(r,t,e,n){let[o,s]=S.computeOutAndReduceShapes(r,n),i=ur(t,"int32"),a=y.makeZerosTypedArray(y.sizeFromShape(o),i),u=y.sizeFromShape(s);for(let l=0;l<a.length;++l){let c=l*u,p=1;for(let m=0;m<u;++m)p*=e[c+m];a[l]=p}return{outVals:a,outShape:o,outDtype:i}}function Stt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;tt(o,"prod");let a=o.shape.length,u=y.parseAxisParam(s,o.shape),l=S.getAxesPermutation(u,a),c=u,p=o,m=[];l!=null&&(p=Ge({inputs:{x:o},backend:e,attrs:{perm:l}}),m.push(p),c=S.getInnerMostAxes(c.length,a));let f=e.data.get(p.dataId).values,{outVals:d,outShape:h,outDtype:g}=hT(p.shape,p.dtype,f,c),x=h;return i&&(x=S.expandShapeToKeepDim(h,u)),m.forEach(b=>e.disposeIntermediateTensorInfo(b)),e.makeTensorInfo(x,g,d)}var CO={kernelName:Bs,backendName:"cpu",kernelFunc:Stt};function Ntt(r,t,e){r.forEach((n,o)=>{if(n<0||n>=e){let s=y.indexToLoc(o,t.length,y.computeStrides(t)).join(",");throw new Error(`indices[${s}] = ${n} is not in [0, ${e})`)}})}function ktt(r,t){for(let e=0;e<r.length;++e){let n=r[e],o=e===r.length-1?t:r[e+1].length;if(n.length===0)throw new Error("Ragged splits may not be empty");if(n[0]<0)throw new Error("Ragged splits must be non-negative");if(n[n.length-1]>o)throw new Error("Ragged splits must not point past values");for(let s=1;s<n.length;++s)if(n[s-1]>n[s])throw new Error("Ragged splits must be sorted in ascending order")}}function Ttt(r,t,e,n){let o=[],s=0,i=t.length-1+e.length,a=new Array(i).fill(null).map(()=>[0]);ktt(e,n);let u=1;for(let l=0;l<t.length-1;++l){u*=t[l];let c=t[l+1];for(let p=1;p<u+1;++p)a[l].push(p*c)}for(let l=0;l<r.length;++l){let c=r[l],p=r[l]+1;for(let m=0;m<e.length;++m){let f=e[m],d=m+t.length-1;if(d>=0){let h=a[d],g=h[h.length-1]-f[c];for(let x=c;x<p;++x)a[d].push(f[x+1]+g)}c=f[c],p=f[p]}p!==c&&(o.push([c,p]),s+=p-c)}return{outSplits:a,valueSlices:o,numValues:s}}function _tt(r){let t=[];for(let e=0;e<r.length;++e){let n=r[e].length,o=y.getArrayFromDType("int32",n);t.push(o),r[e].forEach((s,i)=>o[i]=s)}return t}function vO(r,t){let e=r.slice(0,t);for(;e.length<t;)e.push(1);for(let n=t;n<r.length;n++)e[t-1]*=r[n];return e}function Ett(r,t,e,n,o,s){let i=vO(t,2)[1],a=vO(s,2)[1],u=0;for(let l of e)for(let c=l[0];c<l[1];++c){for(let p=0;p<n;++p)o[u*a+p]=r[c*i+p];++u}}function Att(r,t,e,n,o){let s=t.slice();s[0]=o;let i=y.getArrayFromDType(e,y.sizeFromShape(s)),a=r.length,u=a===0?0:a/t[0];return Ett(r,t,n,u,i,s),[i,s]}function xw(r,t,e,n,o,s,i,a){if(r.length===0)throw new Error("paramsNestedSplits must be non empty");if(t[0].length===0)throw new Error("Split tensors must not be scalars");let u=t[0][0]-1;if(Ntt(s,i,u),n.length===0)throw new Error("params.rank must be nonzero");let l=n[0],{outSplits:c,valueSlices:p,numValues:m}=Ttt(s,i,r,l),f=_tt(c),d=Att(e,n,o,p,m);return[f,d[0],d[1]]}var SO=2147483647;function yw(r,t,e,n,o,s,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(o.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");let a=t.length===0,u=o.length===0,l=i.length===0,c=[];a||c.push(t[0]),u||c.push(o[0]),l||c.push(i[0]);for(let g=1;g<c.length;++g)if(c[g]!==c[g-1])throw new Error("starts, limits, and deltas must have the same shape");let p=c.length===0?1:c[0],m=y.getArrayFromDType("int32",p+1);m[0]=0;for(let g=0;g<p;++g){let x=a?r[0]:r[g],b=u?n[0]:n[g],w=l?s[0]:s[g];if(w===0)throw new Error("Requires delta != 0");let I;if(w>0&&b<x||w<0&&b>x)I=0;else if(I=Math.ceil(Math.abs((b-x)/w)),I>SO)throw new Error(`Requires ((limit - start) / delta) <= ${SO}`);m[g+1]=m[g]+I}let f=m[p],d=y.getArrayFromDType(e,f),h=0;for(let g=0;g<p;++g){let x=m[g+1]-m[g],b=a?r[0]:r[g],w=l?s[0]:s[g];for(let I=0;I<x;++I)d[h++]=b,b+=w}return[m,d]}var zo=S.RowPartitionType,Id=class{constructor(t,e,n,o,s,i,a,u,l,c){this.shape=t,this.shapeShape=e,this.values=n,this.valuesShape=o,this.valuesDType=s,this.defaultValue=i,this.defaultValueShape=a,this.rowPartitionValues=u,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=S.getRowPartitionTypesHelper(c),this.raggedRank=S.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(t){return this.rowPartitionTypes[0]===zo.FIRST_DIM_SIZE?this.rowPartitionTypes[t+1]:this.rowPartitionTypes[t]}getRowPartitionTensor(t){return this.rowPartitionTypes[0]===zo.FIRST_DIM_SIZE?this.rowPartitionValues[t+1]:this.rowPartitionValues[t]}getMaxWidth(t){let e=this.getRowPartitionTensor(t-1);switch(this.getRowPartitionTypeByDimension(t-1)){case zo.VALUE_ROWIDS:return Id.getMaxWidthValueRowID(e);case zo.ROW_SPLITS:return Id.getMaxWidthRowSplit(e);default:throw new Error(`Cannot handle partition type ${zo[this.getRowPartitionTypeByDimension(t-1)]}`)}}static getMaxWidthRowSplit(t){let e=t.length;if(e===0||e===1)return 0;let n=0;for(let o=0;o<e-1;++o){let s=t[o+1]-t[o];s>n&&(n=s)}return n}static getMaxWidthValueRowID(t){let e=t.length;if(e===0)return 0;let n=0,o=t[0],s=0;for(let i=1;i<e;++i){let a=t[i];a!==o&&(o=a,s=Math.max(i-n,s),n=i)}return Math.max(e-n,s)}tensorShapeFromTensor(t,e,n=!0){if(e.length===0){if(t[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return kO(t,n)}calculateOutputSize(t){let e=this.valuesShape,n=this.defaultValueShape;S.validateDefaultValueShape(n,e);let o=this.tensorShapeFromTensor(this.shape,this.shapeShape),i=S.combineRaggedTensorToTensorShapes(this.raggedRank,o,e);i[0]<0&&(i[0]=t);for(let a=1;a<=this.raggedRank;++a)i[a]<0&&(i[a]=this.getMaxWidth(a));return i}calculateFirstParentOutputIndex(t,e,n){let o=Math.min(t,n),s=[],i=0;for(let a=0;a<o;++a,i+=e)s.push(i);for(let a=o;a<t;++a)s.push(-1);return y.assert(s.length===t,()=>"Final length of result must be equal to firstDimension."),s}calculateOutputIndexRowSplit(t,e,n,o){let s=t.length,i=[];for(let a=0;a<s-1;++a){let u=t[a+1]-t[a],l=Math.min(o,u),c=e[a];c===-1&&(l=0);for(let p=0;p<l;++p)i.push(c),c+=n;for(let p=0;p<u-l;++p)i.push(-1)}if(s>0&&i.length!==t[s-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,e,n,o){let s=t.length,i=[];if(s===0)return[];let a=0,u=t[0];if(u>=e.length)throw new Error(`Got currentValueRowId=${u}, which is not less than ${e.length}`);let l=e[u];i.push(l);for(let c=1;c<s;++c){let p=t[c];if(p===u)l>=0&&(++a,a<o?l+=n:l=-1);else{if(a=0,u=p,p>=e.length)throw new Error(`Got nextValueRowId=${p} which is not less than ${e.length}`);l=e[p]}i.push(l)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,e,n,o){let s=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case zo.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,e,n,o);case zo.ROW_SPLITS:if(s.length-1>e.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${e.length}`);return this.calculateOutputIndexRowSplit(s,e,n,o);default:throw new Error(`Unsupported partition type: ${zo[i]}`)}}getFirstDimensionSize(){let t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let e=this.rowPartitionTypes[0];switch(e){case zo.FIRST_DIM_SIZE:return t[0];case zo.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case zo.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${zo[e]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let e=this.getFirstDimensionSize(),n=this.calculateOutputSize(e),o=new Array(this.raggedRank+1);o[o.length-1]=1;for(let u=o.length-2;u>=0;--u)o[u]=o[u+1]*n[u+1];let s=kO(n,!1),i=y.getArrayFromDType(this.valuesDType,y.sizeFromShape(s));if(o[0]*n[0]>0){let u=this.calculateFirstParentOutputIndex(e,o[0],n[0]);for(let l=1;l<=this.raggedRank;++l)u=this.calculateOutputIndex(l-1,u,o[l],n[l]);this.setOutput(this.raggedRank,u,i,s)}return[s,i]}setOutput(t,e,n,o){if(n.length===0)return;let s=this.values,i=n,a=o.slice();a=a.slice(t+1);let u=y.sizeFromShape(a),l=e.length,c=this.defaultValue;if(c.length!==u&&c.length!==1){let d=this.defaultValueShape;B(()=>{let h=R(c,d);c=la(h,a).dataSync()})}let p=0,m=0,f=0;for(let d=0;d<=l;++d){let h=d<l?e[d]:-1;if(h===f){++f;continue}if(m<f){let g=s.subarray(p*u),x=i.subarray(m*u),b=(f-m)*u;NO(x,g,b)}if(d>=l){let g=n.length;h=Math.floor(g/u)}if(h>f)if(this.defaultValue.length===1)i.subarray(f*u,h*u).fill(this.defaultValue[0]),f=h;else for(;h>f;){let g=i.slice(f*u);NO(g,c,u),++f}h<0?(p=d+1,m=f):(p=d,m=f,f=m+1)}}};function NO(r,t,e){for(let n=0;n<e;n++)r[n]=t[n]}function kO(r,t){let e=[];for(let n of r){if(n<0){if(!t)throw new Error(`Dimension ${n} must be >= 0`);if(n<-1)throw new Error(`Dimension ${n} must be >= -1`);n=-1}e.push(n)}return e}function bw(r,t,e,n,o,s,i,a,u,l){return new Id(r,t,e,n,o,s,i,a,u,l).compute()}function up(r,t,e,n){let o=r===t,s=r<t&&e<0,i=t<r&&e>1;if(o||s||i)return y.makeZerosTypedArray(0,n);let a=Math.abs(Math.ceil((t-r)/e)),u=y.makeZerosTypedArray(a,n);t<r&&e===1&&(e=-1),u[0]=r;for(let l=1;l<u.length;l++)u[l]=u[l-1]+e;return u}var gT=Er(r=>1/Math.sqrt(r)),Dtt=Rn(js,gT),TO={kernelName:js,backendName:"cpu",kernelFunc:Dtt};function Si(r,t,e,n,o,s,i,a,u,l){let c=[n/o,o],p=r.values,m=t.values;if(n===0)return wt(e,t.dtype);let f=u instanceof le?u:wt(c,t.dtype);typeof u=="string"||typeof u=="number"?f.values.fill(u):typeof u=="boolean"&&f.values.fill(+u);for(let d=0;d<s;d++){let h=[],g=0;for(let x=0;x<i;x++){let b=p[d*i+x];h.push(b),g+=b*a[x]}if(g<0||g>=n/o)throw new Error(`Invalid indices: ${h} does not index into ${e}`);for(let x=0;x<o;x++)l?f.values[g*o+x]+=m[d*o+x]:f.values[g*o+x]=t.rank===0?m[0]:m[d*o+x]}return f}var _O=Er(r=>1/(1+Math.exp(-r))),xT=At(Qs,r=>1/(1+Math.exp(-r))),EO={kernelName:Qs,backendName:"cpu",kernelFunc:xT};function cp(r,t,e,n,o){let s=ze.isSliceContinous(n,t,e),i=y.sizeFromShape(e),a=y.computeStrides(n);if(s){let p=ze.computeFlatOffset(t,a);return o==="string"?r.slice(p,p+i):r.subarray(p,p+i)}let u=o==="string"?S.fromUint8ToStringArray(r):r,l=wt(n,o,u),c=wt(e,o);for(let p=0;p<c.size;++p){let m=c.indexToLoc(p),f=m.map((d,h)=>d+t[h]);c.set(l.get(...f),...m)}return o==="string"?S.fromStringArrayToUint8(c.values):c.values}function Bo(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,size:i}=n;tt(o,"slice");let[a,u]=ze.parseSliceParams(o,s,i);ze.assertParamsValid(o,a,u);let l=e.data.get(o.dataId).values,c=cp(l,a,u,o.shape,o.dtype);return e.makeTensorInfo(u,o.dtype,c)}var AO={kernelName:qi,backendName:"cpu",kernelFunc:Bo};function ww(r,t,e,n,o,s,i){let a=t[0],u=s[0],l=new Array(u),c=new Array(a),p=t[1];if(u===0){if(a!==0)throw new Error(S.getSparseFillEmptyRowsIndicesDenseShapeMismatch(a));let g=y.getArrayFromDType(e,0),x=y.getArrayFromDType(o,0);return[g,[0,p],x,l,c]}let m=!0,f=0,d=new Array(u).fill(0);for(let g=0;g<a;++g){let x=r[g*p];if(x<0)throw new Error(S.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,x));if(x>=u)throw new Error(S.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,x,u));++d[x],m=m&&x>=f,f=x}let h=!0;for(let g=0;g<u;++g){let x=d[g]===0;l[g]=x,h=h&&!x,d[g]=Math.max(d[g],1),g>0&&(d[g]+=d[g-1])}if(h&&m){let g=r,x=n;for(let b=0;b<a;++b)c[b]=b;return[g,[a,p],x,l,c]}else{let g=d[u-1],x=y.getArrayFromDType(e,g*p),b=y.getArrayFromDType(o,g),w=new Array(u).fill(0);for(let I=0;I<a;++I){let N=r[I*p],E=w[N],A=(N===0?0:d[N-1])+E;w[N]++;for(let D=0;D<p;++D)x[A*p+D]=r[I*p+D];b[A]=n[I],c[I]=A}for(let I=0;I<u;++I)if(w[I]===0){let E=I===0?0:d[I-1];x[E*p+0]=I;for(let A=1;A<p;++A)x[E*p+A]=0;b[E]=i}return[x,[g,p],b,l,c]}}function Iw(r,t,e,n,o){let s=y.sizeFromShape(n),i=t[0],a=o.length,u=[],l=1,c=-1;for(let g=0;g<a;++g){let x=o[g];if(x===-1){if(c!==-1)throw new Error(S.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(c,g));c=g,u.push(1)}else{if(x<0)throw new Error(S.getSparseReshapeNegativeOutputDimErrorMessage(g,x));l*=x,u.push(x)}}if(c!==-1){if(l<=0)throw new Error(S.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let g=Math.trunc(s/l);if(l*g!==s)throw new Error(S.getSparseReshapeInputOutputMultipleErrorMessage(n,u));u[c]=g}if(y.sizeFromShape(u)!==s)throw new Error(S.getSparseReshapeInputOutputMismatchErrorMessage(n,u));let m=n.length,f=[];if(m>0){f[m-1]=1;for(let g=m-2;g>=0;--g)f[g]=f[g+1]*n[g+1]}let d=[];if(a>0){d[a-1]=1;for(let g=a-2;g>=0;--g)d[g]=d[g+1]*u[g+1]}let h=y.getArrayFromDType(e,i*a);for(let g=0;g<i;++g){let x=0;for(let b=0;b<m;++b)x+=r[g*m+b]*f[b];for(let b=0;b<a;++b)h[g*a+b]=Math.trunc(x/d[b]),x%=d[b]}return[h,[i,a],u]}function Cd(r,t,e,n,o,s=!1,i=0){let a=n.length,u=[t[0],r.length/t[0]],l=u[1],p=a>0?o[a-1]+1:0;if(p<0)throw new Error(S.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=t.slice();m[0]=p;let f=m.reduce((w,I)=>w*I,1),d=y.getArrayFromDType(e,f);if(a===0)return p>0&&d.fill(i),[d,m];if(p<=0)throw new Error(S.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let h=0,g=1,x=0,b=o[h];for(;;){let w=0;if(g<a){if(w=o[g],b===w){++g;continue}if(b>=w)throw new Error(S.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(b<0||b>=p)throw new Error(S.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(b,p));b>x&&d.fill(i,x*l,b*l);for(let I=h;I<g;++I){let N=n[I];if(N<0||N>=u[0])throw new Error(S.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(I,n[I],u[0]));for(let E=0;E<l;E++)d[b*l+E]+=r[N*l+E]}if(s)for(let I=0;I<l;I++)d[b*l+I]/=g-h;if(h=g,++g,x=b+1,b=w,g>a)break}return x<p&&d.fill(i,x*l,p*l),[d,m]}var DO=Er(r=>Math.sqrt(r)),$tt=At(ei,r=>Math.sqrt(r)),$O={kernelName:ei,backendName:"cpu",kernelFunc:$tt};var yT=Jt((r,t)=>{let e=r-t;return e*e}),Rtt=oe(oi,yT),RO={kernelName:oi,backendName:"cpu",kernelFunc:Rtt};var bT=Er((r,t)=>{let{pattern:e,replaceGlobal:n,rewrite:o}=t;return r.replace(new RegExp(e,n?"g":""),o)}),Ftt=Rn(cc,bT),FO={kernelName:cc,backendName:"cpu",kernelFunc:Ftt};function Cw(r,t,e,n){let o=wt(r,t.dtype);for(let s=0;s<o.size;s++){let i=o.indexToLoc(s),a=new Array(i.length);for(let u=0;u<a.length;u++)a[u]=i[u]*e[u]+n[u];o.set(t.get(...a),...i)}return o}var wT=class{constructor(t,e,n,o,s,i){this.separator=y.encodeString(t),this.nGramWidths=e,this.leftPad=y.encodeString(n),this.rightPad=y.encodeString(o),this.padWidth=s,this.preserveShort=i}getPadWidth(t){return Math.min(this.padWidth<0?t-1:this.padWidth,t-1)}getNumNGrams(t,e){let n=this.getPadWidth(e);return Math.max(0,t+2*n-e+1)}createNGrams(t,e,n,o,s,i){for(let a=0;a<s;++a){let u=this.getPadWidth(i),l=Math.max(0,u-a),c=Math.max(0,u-(s-(a+1))),p=i-(l+c),m=e+(l>0?0:a-u),f=0;f+=l*this.leftPad.length;for(let b=0;b<p;++b)f+=t[m+b].length;f+=c*this.rightPad.length;let d=l+c+p-1;f+=d*this.separator.length,n[o+a]=new Uint8Array(f);let h=n[o+a],g=0,x=b=>b.forEach(w=>h[g++]=w);for(let b=0;b<l;++b)x(this.leftPad),x(this.separator);for(let b=0;b<p-1;++b)x(t[m+b]),x(this.separator);if(p>0){x(t[m+p-1]);for(let b=0;b<c;++b)x(this.separator),x(this.rightPad)}else{for(let b=0;b<c-1;++b)x(this.rightPad),x(this.separator);x(this.rightPad)}}}compute(t,e){let n=t.length,o=e.length;if(o>0){let u=e[0];if(u!==0)throw new Error(`First split value must be 0, got ${u}`);for(let l=1;l<o;++l){let c=e[l]>=u;if(c=c&&e[l]<=n,!c)throw new Error(`Invalid split value ${e[l]}, must be in [${u}, ${n}]`);u=e[l]}if(u!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${u}`)}let s=o-1,i=y.getArrayFromDType("int32",o);if(n===0||o===0){let u=new Array(n);for(let l=0;l<=s;++l)i[l]=0;return[u,i]}i[0]=0;for(let u=1;u<=s;++u){let l=e[u]-e[u-1],c=0;this.nGramWidths.forEach(p=>{c+=this.getNumNGrams(l,p)}),this.preserveShort&&l>0&&c===0&&(c=1),i[u]=i[u-1]+c}let a=new Array(i[s]);for(let u=0;u<s;++u){let l=e[u],c=i[u];if(this.nGramWidths.forEach(p=>{let m=e[u+1]-e[u],f=this.getNumNGrams(m,p);this.createNGrams(t,l,a,c,f,p),c+=f}),this.preserveShort&&c===i[u]){let p=e[u+1]-e[u];if(p===0)continue;let m=p+2*this.padWidth,f=1;this.createNGrams(t,l,a,c,f,m)}}return[a,i]}};function pp(r,t,e,n,o,s,i,a){return new wT(e,n,o,s,i,a).compute(r,t)}function Ott(r,t,e,n){if(!r.length)return;if(t.length===0){for(let s=0;s<r.length;++s)n.push(r.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=r.indexOf(s);for(;i!==-1;){let a=r.subarray(0,i);(!e||a.length!==0)&&n.push(a),r=r.subarray(i+1),i=r.indexOf(s)}(!e||r.length!==0)&&n.push(r);return}let o=0;for(let s=0;s<r.length+1;s++)if(s===r.length||t.indexOf(r[s])!==-1){let i=r.subarray(o,s);(!e||i.length!==0)&&n.push(i),o=s+1}}function mp(r,t,e){let n=r.length,o=[],s=0,i=0,a=new Array(n);for(let m=0;m<n;++m){let f=o.length;Ott(r[m],t,e,o);let d=o.length-f;a[m]=d,s+=d,i=Math.max(i,d)}let u=y.getArrayFromDType("int32",s*2),l=new Array(s),c=[n,i],p=0;for(let m=0;m<n;++m)for(let f=0;f<a[m];++f)u[p*2]=m,u[p*2+1]=f,l[p]=o[p],++p;return[u,l,c]}function fp(r,t){let e=y.getArrayFromDType("int32",r.length);for(let n=0;n<r.length;++n)e[n]=y.fingerPrint64(r[n]).modulo(t).getLowBitsUnsigned();return e}var IT=Jt((r,t)=>r-t),Ptt=yd((r,t,e,n)=>({real:r-e,imag:t-n})),Qh=oe(si,IT,Ptt),OO={kernelName:si,backendName:"cpu",kernelFunc:Qh};function vw(r,t){let e=new Array(r.rank);for(let o=0;o<e.length;o++)e[o]=r.shape[o]*t[o];let n=wt(e,r.dtype);for(let o=0;o<n.values.length;++o){let s=n.indexToLoc(o),i=new Array(r.rank);for(let u=0;u<i.length;u++)i[u]=s[u]%r.shape[u];let a=r.locToIndex(i);n.values[o]=r.values[a]}return n}var tg=(r,t)=>{let e=t.value-r.value;return e===0?r.index-t.index:e};function PO(r,t,e=0,n=r.length-1){for(;n>e;){if(n-e>600){let a=n-e+1,u=t-e+1,l=Math.log(a),c=.5*Math.exp(2*l/3),p=.5*Math.sqrt(l*c*(a-c)/a)*Math.sign(u-a/2),m=Math.max(e,Math.floor(t-u*c/a+p)),f=Math.min(n,Math.floor(t+(a-u)*c/a+p));PO(r,t,m,f)}let o=r[t],s=e,i=n;for(y.swap(r,e,t),tg(r[n],o)>0&&y.swap(r,e,n);s<i;){for(y.swap(r,s,i),s++,i--;tg(r[s],o)<0;)s=s+1;for(;tg(r[i],o)>0;)i=i-1}tg(r[e],o)===0?y.swap(r,e,i):(i=i+1,y.swap(r,i,n)),i<=t&&(e=i+1),t<=i&&(n=i-1)}}function Sw(r,t,e,n,o){let s=t[t.length-1],[i,a]=[r.length/s,s],u=y.getTypedArrayFromDType(e,i*n),l=y.getTypedArrayFromDType("int32",i*n);for(let p=0;p<i;p++){let m=p*a,f=r.subarray(m,m+a),d=new Array(f.length);f.forEach((b,w)=>d[w]={value:b,index:w}),n<d.length&&(PO(d,n),d=d.slice(0,n)),o&&d.sort(tg);let h=p*n,g=u.subarray(h,h+n),x=l.subarray(h,h+n);for(let b=0;b<n;b++)g[b]=d[b].value,x[b]=d[b].index}let c=t.slice();return c[c.length-1]=n,[wt(c,e,u),wt(c,"int32",l)]}function dp(r,t,e,n){let o=y.parseAxisParam(t,e)[0],s=[1,e[0],1];for(let d=0;d<o;d++)s[0]*=e[d];s[1]=e[o];for(let d=o+1;d<e.length;d++)s[2]*=e[d];let i=new Map,a=new Int32Array(e[o]),u=new le(s,n,r),l=[],c=s[0]===1&&s[2]===1;for(let d=0;d<e[o];d++){let h;if(c)h=r[d].toString();else{let x=[];for(let b=0;b<s[0];b++)for(let w=0;w<s[2];w++)x.push(u.get(b,d,w));h=x.join(",")}let g=i.get(h);if(g!=null)a[d]=g;else{let x=i.size;i.set(h,x),a[d]=x,l.push(d)}}let p=s.slice();p[1]=i.size;let m=new le(p,n);l.forEach((d,h)=>{for(let g=0;g<s[0];g++)for(let x=0;x<s[2];x++)m.set(u.get(g,d,x),g,h,x)});let f=e.slice();return f[o]=p[1],{outputValues:m.values,outputShape:f,indices:a}}var MO="4.7.0";im("cpu",()=>new Xu,1);var CT=At(ms,r=>r>=0?r:Math.exp(r)-1),LO={kernelName:ms,backendName:"cpu",kernelFunc:CT};function vT(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{alpha:s}=n;tt([o],"leakyRelu");let i=y.sizeFromShape(o.shape),a=e.data.get(o.dataId).values,u=y.getTypedArrayFromDType("float32",i);for(let l=0;l<a.length;l++)u[l]=a[l]<0?s*a[l]:a[l];return e.makeTensorInfo(o.shape,"float32",u)}var zO={kernelName:vs,backendName:"cpu",kernelFunc:vT};var Mtt=Jt((r,t)=>r<0?t*r:r);function ST(r){let{inputs:t,backend:e}=r,{x:n,alpha:o}=t;tt([n,o],"prelu");let s=e.data.get(n.dataId).values,i=e.data.get(o.dataId).values,[a,u]=Mtt(n.shape,o.shape,s,i,"float32");return e.makeTensorInfo(u,"float32",a)}var BO={kernelName:zs,backendName:"cpu",kernelFunc:ST};var NT=At(Gs,r=>Math.max(0,r)),VO={kernelName:Gs,backendName:"cpu",kernelFunc:NT};var kT=At(Hs,r=>Math.min(Math.max(0,r),6)),GO={kernelName:Hs,backendName:"cpu",kernelFunc:kT};function hp(r,t,e,n,o){if(e==="linear")return Zr({inputs:{x:t},backend:r});if(e==="relu")return NT({inputs:{x:t},backend:r});if(e==="elu")return CT({inputs:{x:t},backend:r});if(e==="relu6")return kT({inputs:{x:t},backend:r});if(e==="prelu")return ST({inputs:{x:t,alpha:n},backend:r});if(e==="leakyrelu")return vT({inputs:{x:t},backend:r,attrs:{alpha:o}});if(e==="sigmoid")return xT({inputs:{x:t},backend:r});throw new Error(`Activation ${e} has not been implemented for the CPU backend.`)}function Qt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{shape:s}=n,i=y.sizeFromShape(o.shape),a=y.inferFromImplicitShape(s,i),u=y.sizeFromShape(a);y.assert(i===u,()=>`The new shape (${a}) has ${u} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),e.incRef(o.dataId);let l=e.data.get(o.dataId);if(l.complexTensorInfos!=null){let c=l.complexTensorInfos.real,p=l.complexTensorInfos.imag;c.shape=a,p.shape=a}return{dataId:o.dataId,shape:a,dtype:o.dtype}}var WO={kernelName:Ui,backendName:"cpu",kernelFunc:Qt};function TT(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s}=t,{transposeA:i,transposeB:a}=n;tt([o,s],"matMul");let u=o.shape.length,l=s.shape.length,c=i?o.shape[u-2]:o.shape[u-1],p=a?s.shape[l-1]:s.shape[l-2],m=i?o.shape[u-1]:o.shape[u-2],f=a?s.shape[l-2]:s.shape[l-1],d=o.shape.slice(0,-2),h=s.shape.slice(0,-2),g=y.sizeFromShape(d),x=y.sizeFromShape(h),w=Hr.assertAndGetBroadcastShape(o.shape.slice(0,-2),s.shape.slice(0,-2)).concat([m,f]);y.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${i} and transposeB=${a} must match.`);let I=i?[g,c,m]:[g,m,c],N=a?[x,f,p]:[x,p,f],E=Qt({inputs:{x:o},backend:e,attrs:{shape:I}}),A=Qt({inputs:{x:s},backend:e,attrs:{shape:N}}),D=i?E.shape[1]:E.shape[2],F=i?E.shape[2]:E.shape[1],P=a?A.shape[1]:A.shape[2],V=Math.max(g,x),G=e.data.get(E.dataId).values,W=e.data.get(A.dataId).values,q=y.computeStrides(E.shape),H=y.computeStrides(A.shape),[K,X,Z]=i?[q[0],1,q[1]]:[q[0],q[1],1],[et,nt,st]=a?[1,H[1],H[0]]:[H[1],1,H[0]],at=F*P,ot=wt([V,F,P],E.dtype),it=ot.values,mt=e.blockSize;for(let gt=0;gt<V;gt++){let Ct=gt%g,Rt=gt%x;for(let Dt=0;Dt<F;Dt+=mt){let Ht=Math.min(Dt+mt,F);for(let qt=0;qt<P;qt+=mt){let ce=Math.min(qt+mt,P);for(let ge=0;ge<D;ge+=mt){let re=Math.min(ge+mt,D);for(let xe=Dt;xe<Ht;xe++)for(let fe=qt;fe<ce;fe++){let Ae=0;for(let De=ge;De<re;De++){let Ln=G[Ct*K+xe*X+De*Z],lr=W[De*et+fe*nt+Rt*st];Ae+=Ln*lr}it[gt*at+(xe*P+fe)]+=Ae}}}}}return e.disposeIntermediateTensorInfo(E),e.disposeIntermediateTensorInfo(A),e.makeTensorInfo(w,ot.dtype,ot.values)}var UO={kernelName:es,backendName:"cpu",kernelFunc:TT};function Ltt(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=n,m,f,d,h=[];m=TT({inputs:{a:o,b:s},attrs:{transposeA:u,transposeB:l},backend:e}),i&&(f=Ca({inputs:{a:m,b:i},backend:e}),h.push(m),m=f),c&&(d=hp(e,m,c,a,p),h.push(m),m=d);for(let x of h)e.disposeIntermediateTensorInfo(x);return m}var HO={kernelName:Zi,backendName:"cpu",kernelFunc:Ltt};var ztt=At(qo,r=>Math.acos(r)),qO={kernelName:qo,backendName:"cpu",kernelFunc:ztt};var Btt=At(Ko,r=>Math.acosh(r)),KO={kernelName:Ko,backendName:"cpu",kernelFunc:Btt};function Vtt(r){let{inputs:t,backend:e}=r,n=t;tt(t,"addN");let o=n.map(a=>e.data.get(a.dataId).values),s=wt(n[0].shape,n[0].dtype),i=s.values;for(let a=0;a<n.length;a++){let u=o[a];for(let l=0;l<i.length;l++)i[l]+=u[l]}return e.makeTensorInfo(s.shape,s.dtype,s.values)}var jO={kernelName:jo,backendName:"cpu",kernelFunc:Vtt};function Gtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;tt(o,"all");let a=y.parseAxisParam(s,o.shape),u=a,l=S.getAxesPermutation(u,o.shape.length),c=o;l!=null&&(c=Ge({inputs:{x:o},backend:e,attrs:{perm:l}}),u=S.getInnerMostAxes(u.length,o.shape.length)),S.assertAxesAreInnerMostDims("all",u,c.shape.length);let[p,m]=S.computeOutAndReduceShapes(c.shape,u),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=e.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let I=0;I<f;++I){let N=h[b+I];w=w&&N}d[x]=w}l!=null&&e.disposeIntermediateTensorInfo(c);let g=e.makeTensorInfo(p,c.dtype,d);if(i){let x=S.expandShapeToKeepDim(p,a),b=Qt({inputs:{x:g},backend:e,attrs:{shape:x}});return e.disposeIntermediateTensorInfo(g),b}return g}var XO={kernelName:Ra,backendName:"cpu",kernelFunc:Gtt};function Wtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;tt(o,"any");let a=y.parseAxisParam(s,o.shape),u=a,l=S.getAxesPermutation(u,o.shape.length),c=o;l!=null&&(c=Ge({inputs:{x:o},backend:e,attrs:{perm:l}}),u=S.getInnerMostAxes(u.length,o.shape.length)),S.assertAxesAreInnerMostDims("any",u,c.shape.length);let[p,m]=S.computeOutAndReduceShapes(c.shape,u),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=e.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let I=0;I<f;++I){let N=h[b+I];w=w||N}d[x]=w}l!=null&&e.disposeIntermediateTensorInfo(c);let g=e.makeTensorInfo(p,c.dtype,d);if(i){let x=S.expandShapeToKeepDim(p,a),b=Qt({inputs:{x:g},backend:e,attrs:{shape:x}});return e.disposeIntermediateTensorInfo(g),b}return g}var YO={kernelName:Fa,backendName:"cpu",kernelFunc:Wtt};function Utt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s}=n;tt(o,"argMax");let i=y.parseAxisParam(s,o.shape),a=S.getAxesPermutation(i,o.shape.length),u=o,l=[];a!=null&&(u=Ge({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(u),i=S.getInnerMostAxes(i.length,u.shape.length)),i=[i[0]],S.assertAxesAreInnerMostDims("argMax",i,u.shape.length);let[c,p]=S.computeOutAndReduceShapes(u.shape,i),m=y.sizeFromShape(c),f=y.makeZerosTypedArray(m,"int32"),d=y.sizeFromShape(p),h=e.data.get(u.dataId).values;for(let g=0;g<f.length;++g){let x=g*d,b=h[x],w=0;for(let I=0;I<d;++I){let N=h[x+I];N>b&&(b=N,w=I)}f[g]=w}return l.forEach(g=>e.disposeIntermediateTensorInfo(g)),e.makeTensorInfo(c,"int32",f)}var ZO={kernelName:Ri,backendName:"cpu",kernelFunc:Utt};function Htt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s}=n;tt(o,"argMin");let i=y.parseAxisParam(s,o.shape),a=S.getAxesPermutation(i,o.shape.length),u=o,l=[];a!=null&&(u=Ge({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(u),i=S.getInnerMostAxes(i.length,u.shape.length)),i=[i[0]],S.assertAxesAreInnerMostDims("argMin",i,u.shape.length);let[c,p]=S.computeOutAndReduceShapes(u.shape,i),m=y.sizeFromShape(c),f=y.makeZerosTypedArray(m,"int32"),d=y.sizeFromShape(p),h=e.data.get(u.dataId).values;for(let g=0;g<f.length;++g){let x=g*d,b=h[x],w=0;for(let I=0;I<d;++I){let N=h[x+I];N<b&&(b=N,w=I)}f[g]=w}return l.forEach(g=>e.disposeIntermediateTensorInfo(g)),e.makeTensorInfo(c,"int32",f)}var JO={kernelName:Fi,backendName:"cpu",kernelFunc:Htt};var qtt=At(Xo,r=>Math.asin(r)),QO={kernelName:Xo,backendName:"cpu",kernelFunc:qtt};var Ktt=At(Yo,r=>Math.asinh(r)),tP={kernelName:Yo,backendName:"cpu",kernelFunc:Ktt};var jtt=At(Zo,r=>Math.atan(r)),eP={kernelName:Zo,backendName:"cpu",kernelFunc:jtt};var Xtt=Jt((r,t)=>Math.atan2(r,t)),Ytt=oe(Qo,Xtt),rP={kernelName:Qo,backendName:"cpu",kernelFunc:Ytt};var Ztt=At(Jo,r=>Math.atanh(r)),nP={kernelName:Jo,backendName:"cpu",kernelFunc:Ztt};function vd(r,t,e,n,o,s){let i=o.strideHeight,a=o.strideWidth,u=o.dilationHeight,l=o.dilationWidth,c=o.effectiveFilterHeight,p=o.effectiveFilterWidth,m=o.padInfo.top,f=o.padInfo.left,d=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=wt(o.outShape,e),g=h.values,x=o.outShape[1]*o.outShape[2]*o.outShape[3],b=o.outShape[2]*o.outShape[3],w=o.outShape[3];for(let I=0;I<o.batchSize;++I){let N=I*x,E=I*n[0];for(let A=0;A<o.inChannels;++A)for(let D=0;D<o.outHeight;++D){let F=D*i-m,P=Math.max(0,F),V=Math.min(o.inHeight,c+F),G=N+D*b;for(let W=0;W<o.outWidth;++W){let q=W*a-f,H=Math.max(0,q),K=Math.min(o.inWidth,p+q),X=d,Z=0,et=0;for(let st=P;st<V;st+=u){let at=E+st*n[1];for(let ot=H;ot<K;ot+=l){let it=at+ot*n[2],mt=r[it+A];s==="max"&&mt>X?X=mt:s==="avg"&&(Z+=mt,et++)}if(isNaN(X))break}let nt=G+W*w+A;g[nt]=s==="avg"?Z/et:X}}}return h}function kw(r,t,e,n,o=!1,s=!1){let i=wt(n.outShape,"int32"),a=n.strideHeight,u=n.strideWidth,l=n.dilationHeight,c=n.dilationWidth,p=n.effectiveFilterHeight,m=n.effectiveFilterWidth,f=n.padInfo.top,d=n.padInfo.left,h=wt(t,e,r);for(let g=0;g<n.batchSize;++g)for(let x=0;x<n.inChannels;++x)for(let b=0;b<n.outHeight;++b){let w=b*a-f,I=w;for(;I<0;)I+=l;let N=Math.min(n.inHeight,p+w);for(let E=0;E<n.outWidth;++E){let A=E*u-d,D=A;for(;D<0;)D+=c;let F=Math.min(n.inWidth,m+A),P=Number.NEGATIVE_INFINITY,V=-1;for(let G=I;G<N;G+=l){let W=G-w;for(let q=D;q<F;q+=c){let H=q-A,K=h.get(g,G,q,x);K>P&&(P=K,o?V=s?((g*n.inHeight+G)*n.inWidth+q)*n.inChannels+x:(G*n.inWidth+q)*n.inChannels+x:V=W*m+H)}}i.set(V,g,b,E,x)}}return i}function Tw(r,t,e,n,o,s){let i=o.strideDepth,a=o.strideHeight,u=o.strideWidth,l=o.dilationDepth,c=o.dilationHeight,p=o.dilationWidth,m=o.effectiveFilterDepth,f=o.effectiveFilterHeight,d=o.effectiveFilterWidth,h=o.padInfo.front,g=o.padInfo.top,x=o.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,w=wt(o.outShape,e),I=w.values,N=o.outShape[1]*o.outShape[2]*o.outShape[3]*o.outShape[4],E=o.outShape[2]*o.outShape[3]*o.outShape[4],A=o.outShape[3]*o.outShape[4],D=o.outShape[4];for(let F=0;F<o.batchSize;++F){let P=F*N,V=F*n[0];for(let G=0;G<o.inChannels;++G)for(let W=0;W<o.outDepth;++W){let q=W*i-h,H=q;for(;H<0;)H+=l;let K=Math.min(o.inDepth,m+q),X=P+W*E;for(let Z=0;Z<o.outHeight;++Z){let et=Z*a-g,nt=et;for(;nt<0;)nt+=c;let st=Math.min(o.inHeight,f+et),at=X+Z*A;for(let ot=0;ot<o.outWidth;++ot){let it=ot*u-x,mt=it;for(;mt<0;)mt+=p;let gt=Math.min(o.inWidth,d+it),Ct=at+ot*D,Rt=b,Dt=0,Ht=0;for(let ce=H;ce<K;ce+=l){let ge=V+ce*n[1];for(let re=nt;re<st;re+=c){let xe=ge+re*n[2];for(let fe=mt;fe<gt;fe+=p){let Ae=xe+fe*n[3],De=r[Ae+G];if(s==="max"&&De>Rt?Rt=De:s==="avg"&&(Dt+=De,Ht++),isNaN(Rt))break}if(isNaN(Rt))break}if(isNaN(Rt))break}let qt=Ct+G;I[qt]=s==="avg"?Dt/Math.max(Ht,1):Rt}}}}return w}function oP(r,t){let e=wt(t.outShape,"int32"),n=t.strideDepth,o=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,a=t.dilationHeight,u=t.dilationWidth,l=t.effectiveFilterDepth,c=t.effectiveFilterHeight,p=t.effectiveFilterWidth,m=t.padInfo.front,f=t.padInfo.top,d=t.padInfo.left;for(let h=0;h<t.batchSize;++h)for(let g=0;g<t.inChannels;++g)for(let x=0;x<t.outDepth;++x){let b=x*n-m,w=b;for(;w<0;)w+=i;let I=Math.min(t.inDepth,l+b);for(let N=0;N<t.outHeight;++N){let E=N*o-f,A=E;for(;A<0;)A+=a;let D=Math.min(t.inHeight,c+E);for(let F=0;F<t.outWidth;++F){let P=F*s-d,V=P;for(;V<0;)V+=u;let G=Math.min(t.inWidth,p+P),W=Number.NEGATIVE_INFINITY,q=-1;for(let H=w;H<I;H+=i){let K=H-b;for(let X=A;X<D;X+=a){let Z=X-E;for(let et=V;et<G;et+=u){let nt=et-P,st=r.get(h,H,X,et,g);st>=W&&(W=st,q=K*c*p+Z*c+nt)}}}e.set(q,h,x,N,F,g)}}}return e}function Jtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;tt(o,"avgPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=n,l=1;y.assert(S.eitherStridesOrDilationsAreOne(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=S.computePool2DInfo(o.shape,s,i,l,a,u),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Zr({inputs:{x:o},backend:e});else{let m=e.data.get(o.dataId).values,f=y.computeStrides(o.shape),d=vd(m,o.shape,o.dtype,f,c,"avg");p=e.makeTensorInfo(c.outShape,o.dtype,d.values)}return p}var sP={kernelName:ts,backendName:"cpu",kernelFunc:Jtt};function Qtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u,dataFormat:l}=n;tt(o,"avgPool3d");let c=S.computePool3DInfo(o.shape,s,i,1,a,u,l),p=e.data.get(o.dataId).values,m=Tw(p,o.shape,o.dtype,y.computeStrides(o.shape),c,"avg");return e.makeTensorInfo(m.shape,"float32",m.values)}var iP={kernelName:Oi,backendName:"cpu",kernelFunc:Qtt};function tet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=n;tt([o,s],"avgPool3DGrad");let c=S.computePool3DInfo(s.shape,i,a,1,u,l),p=c.strideDepth,m=c.strideHeight,f=c.strideWidth,d=c.filterDepth,h=c.filterHeight,g=c.filterWidth,x=c.dilationDepth,b=c.dilationHeight,w=c.dilationWidth,I=c.effectiveFilterDepth,N=c.effectiveFilterHeight,E=c.effectiveFilterWidth,A=I-1-c.padInfo.front,D=E-1-c.padInfo.left,F=N-1-c.padInfo.top,P=wt(s.shape,"float32"),V=1/(d*h*g),G=e.bufferSync(o);for(let W=0;W<c.batchSize;++W)for(let q=0;q<c.inChannels;++q)for(let H=0;H<c.inDepth;++H)for(let K=0;K<c.inHeight;++K)for(let X=0;X<c.inWidth;++X){let Z=H-A,et=K-F,nt=X-D,st=0;for(let at=0;at<I;at+=x){let ot=(Z+at)/p;if(!(ot<0||ot>=c.outDepth||Math.floor(ot)!==ot))for(let it=0;it<N;it+=b){let mt=(et+it)/m;if(!(mt<0||mt>=c.outHeight||Math.floor(mt)!==mt))for(let gt=0;gt<E;gt+=w){let Ct=(nt+gt)/f;if(Ct<0||Ct>=c.outWidth||Math.floor(Ct)!==Ct)continue;let Rt=G.get(W,ot,mt,Ct,q);st+=Rt}}}P.set(st*V,W,H,K,X,q)}return e.makeTensorInfo(P.shape,P.dtype,P.values)}var aP={kernelName:Jl,backendName:"cpu",kernelFunc:tet};function eet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s;tt([o,s],"avgPoolGrad");let{filterSize:a,strides:u,pad:l}=n,c=S.computePool2DInfo(i.shape,a,u,1,l),p=c.strideHeight,m=c.strideWidth,f=c.filterHeight,d=c.filterWidth,h=c.dilationHeight,g=c.dilationWidth,x=c.effectiveFilterHeight,b=c.effectiveFilterWidth,w=b-1-c.padInfo.left,I=x-1-c.padInfo.top,N=wt(i.shape,"float32"),E=1/(f*d),A=e.data.get(o.dataId).values,D=wt(o.shape,"float32",A);for(let F=0;F<c.batchSize;++F)for(let P=0;P<c.inChannels;++P)for(let V=0;V<c.inHeight;++V)for(let G=0;G<c.inWidth;++G){let W=V-I,q=G-w,H=0;for(let K=0;K<x;K+=h){let X=(W+K)/p;if(!(X<0||X>=c.outHeight||Math.floor(X)!==X))for(let Z=0;Z<b;Z+=g){let et=(q+Z)/m;if(et<0||et>=c.outWidth||Math.floor(et)!==et)continue;let nt=D.get(F,X,et,P);H+=nt}}N.set(H*E,F,V,G,P)}return e.makeTensorInfo(N.shape,N.dtype,N.values)}var lP={kernelName:Zl,backendName:"cpu",kernelFunc:eet};function ret(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,scale:s,offset:i,mean:a,variance:u}=t;y.assert(a.shape.length===u.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(s==null||a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),tt([o,a,u,s,i],"batchNorm");let{varianceEpsilon:l}=n;l==null&&(l=.001);let c=e.data.get(o.dataId).values,p=e.data.get(a.dataId).values,m=e.data.get(u.dataId).values,f=s?e.data.get(s.dataId).values:new Float32Array([1]),d=i?e.data.get(i.dataId).values:new Float32Array([0]),h=new Float32Array(c.length),g=d.length,x=f.length,b=m.length,w=p.length,I=0,N=0,E=0,A=0;for(let D=0;D<c.length;++D)h[D]=d[I++]+(c[D]-p[N++])*f[E++]/Math.sqrt(m[A++]+l),I>=g&&(I=0),N>=w&&(N=0),E>=x&&(E=0),A>=b&&(A=0);return e.makeTensorInfo(o.shape,o.dtype,h)}var uP={kernelName:ys,backendName:"cpu",kernelFunc:ret};function net(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,crops:i}=n;tt([o],"batchToSpaceND");let a=s.reduce((x,b)=>x*b),u=S.getReshaped(o.shape,s,a),l=S.getPermuted(u.length,s.length),c=S.getReshapedPermuted(o.shape,s,a),p=S.getSliceBeginCoords(i,s.length),m=S.getSliceSize(c,i,s.length),f=Qt({inputs:{x:o},backend:e,attrs:{shape:u}}),d=Ge({inputs:{x:f},backend:e,attrs:{perm:l}}),h=Qt({inputs:{x:d},backend:e,attrs:{shape:c}}),g=Bo({inputs:{x:h},backend:e,attrs:{begin:p,size:m}});return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),g}var cP={kernelName:Pi,backendName:"cpu",kernelFunc:net};function oet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,weights:s}=t,{size:i}=n,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,l=bd(a,u,s.dtype,s.shape,i);return e.makeTensorInfo([i],s.dtype,l)}var pP={kernelName:Oa,backendName:"cpu",kernelFunc:oet};function set(r){let{inputs:t,backend:e}=r,{s0:n,s1:o}=t,s=e.data.get(n.dataId).values,i=e.data.get(o.dataId).values,a=S.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}var mP={kernelName:Ql,backendName:"cpu",kernelFunc:set};var iet=At(yo,(r,t)=>{let e=t;return r>e.clipValueMax?e.clipValueMax:r<e.clipValueMin?e.clipValueMin:r}),fP={kernelName:yo,backendName:"cpu",kernelFunc:iet};var aet=r=>{let{x:t}=r.inputs,e=r.backend,n=new Float32Array(y.sizeFromShape(t.shape)),o=e.data.get(t.dataId),s=o.complexTensorInfos.real,i=o.complexTensorInfos.imag,a=e.data.get(s.dataId).values,u=e.data.get(i.dataId).values;for(let l=0;l<a.length;l++){let c=a[l],p=u[l];n[l]=Math.hypot(c,p)}return e.makeOutput(n,t.shape,"float32")},dP={kernelName:tu,backendName:"cpu",kernelFunc:aet};function va(r){let{inputs:t,backend:e}=r,{input:n}=t,o=e.data.get(n.dataId).complexTensorInfos.imag,s=e.data.get(o.dataId).values;return e.makeTensorInfo(o.shape,o.dtype,s)}var hP={kernelName:qp,backendName:"cpu",kernelFunc:va};function Yu(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n,s=y.parseAxisParam(o,t[0].shape)[0],i=t.map(h=>h.shape);S.assertParamsConsistent(i,s);let a=S.computeOutShape(t.map(h=>h.shape),s);if(y.sizeFromShape(a)===0)return e.makeTensorInfo(a,t[0].dtype,[]);let u=t.filter(h=>y.sizeFromShape(h.shape)>0);if(u.length===1)return Zr({inputs:{x:u[0]},backend:e});if(u[0].dtype==="complex64"){let h=u.map(I=>Mo({inputs:{input:I},backend:e})),g=u.map(I=>va({inputs:{input:I},backend:e})),x=Yu({inputs:h,backend:e,attrs:{axis:s}}),b=Yu({inputs:g,backend:e,attrs:{axis:s}}),w=Cr({inputs:{real:x,imag:b},backend:e});return h.forEach(I=>e.disposeIntermediateTensorInfo(I)),g.forEach(I=>e.disposeIntermediateTensorInfo(I)),e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(b),w}let l=u.map(h=>{let x=[-1,y.sizeFromShape(h.shape.slice(s))];return Qt({inputs:{x:h},backend:e,attrs:{shape:x}})}),c=l.map(h=>({vals:e.data.get(h.dataId).values,shape:h.shape}));a=S.computeOutShape(l.map(h=>h.shape),1);let p=l[0].shape[0]===1,m=ap(c,a,t[0].dtype,p),f=S.computeOutShape(u.map(h=>h.shape),s),d=e.makeTensorInfo(f,t[0].dtype,m);return l.forEach(h=>e.disposeIntermediateTensorInfo(h)),d}var gP={kernelName:Mi,backendName:"cpu",kernelFunc:Yu};function _T(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dataFormat:u,dilations:l,dimRoundingMode:c}=n;tt([o,s],"conv2d");let p=S.convertConv2DDataFormat(u),m=S.computeConv2DInfo(o.shape,s.shape,i,l,a,c,!1,p),f=m.filterHeight,d=m.filterWidth,h=m.dilationHeight,g=m.dilationWidth,x=m.padInfo.left,b=m.padInfo.top,w=m.dataFormat==="channelsLast",I=new le(m.outShape,o.dtype),N=y.computeStrides(o.shape),E=y.computeStrides(s.shape),A=N[0],D=w?N[1]:N[2],F=w?N[2]:1,P=w?1:N[1],V=I.strides[0],G=w?I.strides[1]:I.strides[2],W=w?I.strides[2]:1,q=w?1:I.strides[1],H=e.data.get(o.dataId).values,K=e.data.get(s.dataId).values,X=I.values;for(let Z=0;Z<m.batchSize;++Z){let et=Z*A,nt=Z*V;for(let st=0;st<m.outHeight;++st){let at=nt+st*G,ot=st*m.strideHeight-b;for(let it=0;it<f;++it){let mt=ot+it*h;if(mt<0||mt>=m.inHeight)continue;let gt=it*E[0],Ct=et+mt*D;for(let Rt=0;Rt<m.outWidth;++Rt){let Dt=at+Rt*W,Ht=Rt*m.strideWidth-x;for(let qt=0;qt<d;++qt){let ce=Ht+qt*g;if(ce<0||ce>=m.inWidth)continue;let ge=gt+qt*E[1],re=Ct+ce*F,xe=ge;for(let fe=0;fe<m.inChannels;++fe){let Ae=H[re+fe*P];for(let De=0;De<m.outChannels;++De)X[Dt+De*q]+=Ae*K[xe+De];xe+=m.outChannels}}}}}}return e.makeTensorInfo(I.shape,I.dtype,X)}var xP={kernelName:ns,backendName:"cpu",kernelFunc:_T};function uet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,dataFormat:u,dimRoundingMode:l,filterShape:c}=n;tt([o,s],"conv2dBackpropFilter");let p=S.convertConv2DDataFormat(u),m=S.computeConv2DInfo(o.shape,c,i,1,a,l,!1,p),{strideHeight:f,strideWidth:d,filterHeight:h,filterWidth:g}=m,x=m.dataFormat==="channelsLast",b=new le(m.filterShape,"float32"),w=m.padInfo.left,I=m.padInfo.top,N=e.data.get(o.dataId).values,E=e.data.get(s.dataId).values,A=new le(o.shape,o.dtype,N),D=new le(s.shape,s.dtype,E);for(let F=0;F<h;++F){let P=Math.max(0,Math.ceil((I-F)/f)),V=Math.min(m.outHeight,(m.inHeight+I-F)/f);for(let G=0;G<g;++G){let W=Math.max(0,Math.ceil((w-G)/d)),q=Math.min(m.outWidth,(m.inWidth+w-G)/d);for(let H=0;H<m.inChannels;++H)for(let K=0;K<m.outChannels;++K){let X=0;for(let Z=0;Z<m.batchSize;++Z)for(let et=P;et<V;++et){let nt=F+et*f-I;for(let st=W;st<q;++st){let at=G+st*d-w;x?X+=A.get(Z,nt,at,H)*D.get(Z,et,st,K):X+=A.get(Z,H,nt,at)*D.get(Z,K,et,st)}}b.set(X,F,G,H,K)}}}return e.makeTensorInfo(b.shape,b.dtype,b.values)}var yP={kernelName:Bp,backendName:"cpu",kernelFunc:uet};function cet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{inputShape:i,strides:a,pad:u,dataFormat:l,dimRoundingMode:c}=n;tt([o,s],"conv2dBackpropInput");let p=y.computeStrides(s.shape),m=y.computeStrides(o.shape),f=S.convertConv2DDataFormat(l),d=S.computeConv2DInfo(i,s.shape,a,1,u,c,!1,f),h=new le(d.inShape,"float32"),g=h.values,x=e.data.get(o.dataId).values,b=e.data.get(s.dataId).values,[w,I,N]=p,{batchSize:E,filterHeight:A,filterWidth:D,inChannels:F,inHeight:P,inWidth:V,outChannels:G,outHeight:W,outWidth:q,strideHeight:H,strideWidth:K}=d;f=d.dataFormat;let X=A-1-d.padInfo.top,Z=D-1-d.padInfo.left,et=f==="channelsLast",nt=h.strides[0],st=et?h.strides[1]:h.strides[2],at=et?h.strides[2]:1,ot=et?1:h.strides[1],it=m[0],mt=et?m[1]:m[2],gt=et?m[2]:1,Ct=et?1:m[1];for(let Rt=0;Rt<E;++Rt)for(let Dt=0;Dt<F;++Dt)for(let Ht=0;Ht<P;++Ht){let qt=Ht-X,ce=Math.max(0,Math.ceil(qt/H)),ge=Math.min(W,(A+qt)/H);for(let re=0;re<V;++re){let xe=re-Z,fe=Math.max(0,Math.ceil(xe/K)),Ae=Math.min(q,(D+xe)/K),De=0;for(let lr=ce;lr<ge;++lr){let eo=lr*H-qt;for(let Vr=fe;Vr<Ae;++Vr){let je=Vr*K-xe,Gr=it*Rt+mt*lr+gt*Vr,Wr=w*(A-1-eo)+I*(D-1-je)+N*Dt;for(let ro=0;ro<G;++ro){let no=x[Gr+Ct*ro],Qr=b[Wr+ro];De+=no*Qr}}}let Ln=nt*Rt+st*Ht+at*re+ot*Dt;g[Ln]=De}}return e.makeTensorInfo(h.shape,h.dtype,h.values)}var bP={kernelName:os,backendName:"cpu",kernelFunc:cet};function pet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n;tt([o,s],"conv3d");let l=S.computeConv3DInfo(o.shape,s.shape,i,u,a),{filterDepth:c,filterHeight:p,filterWidth:m,dilationDepth:f,dilationHeight:d,dilationWidth:h,padInfo:g}=l,x=g.front,b=g.left,w=g.top,I=new le(l.outShape,o.dtype),N=e.data.get(o.dataId).values,E=e.data.get(s.dataId).values,A=I.values,D=y.computeStrides(o.shape),F=y.computeStrides(s.shape);for(let P=0;P<l.batchSize;++P){let V=P*D[0],G=P*I.strides[0];for(let W=0;W<l.outDepth;++W){let q=G+W*I.strides[1],H=W*l.strideDepth-x;for(let K=0;K<c;++K){let X=H+K*f;if(X<0||X>=l.inDepth)continue;let Z=K*F[0],et=V+X*D[1];for(let nt=0;nt<l.outHeight;++nt){let st=q+nt*I.strides[2],at=nt*l.strideHeight-w;for(let ot=0;ot<p;++ot){let it=at+ot*d;if(it<0||it>=l.inHeight)continue;let mt=Z+ot*F[1],gt=et+it*D[2];for(let Ct=0;Ct<l.outWidth;++Ct){let Rt=st+Ct*l.outChannels,Dt=Ct*l.strideWidth-b;for(let Ht=0;Ht<m;++Ht){let qt=Dt+Ht*h;if(qt<0||qt>=l.inWidth)continue;let ce=mt+Ht*F[2],ge=gt+qt*l.inChannels,re=ce;for(let xe=0;xe<l.inChannels;++xe){let fe=N[ge+xe];for(let Ae=0;Ae<l.outChannels;++Ae)A[Rt+Ae]+=fe*E[re+Ae];re+=l.outChannels}}}}}}}}return e.makeTensorInfo(I.shape,I.dtype,I.values)}var wP={kernelName:ss,backendName:"cpu",kernelFunc:pet};function met(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,filterShape:u}=n;tt([o,s],"conv3dBackpropFilterV2");let l=y.computeStrides(o.shape),c=y.computeStrides(s.shape),p=S.computeConv3DInfo(o.shape,u,i,1,a),m=p.strideDepth,f=p.strideHeight,d=p.strideWidth,h=p.filterDepth,g=p.filterHeight,x=p.filterWidth,b=new le(p.filterShape,"float32"),w=b.values,[I,N,E,A]=b.strides,D=e.data.get(s.dataId).values,[F,P,V,G]=c,W=e.data.get(o.dataId).values,[q,H,K,X]=l,Z=p.padInfo.front,et=p.padInfo.left,nt=p.padInfo.top;for(let st=0;st<h;++st){let at=Math.max(0,Math.ceil((Z-st)/m)),ot=Math.min(p.outDepth,(p.inDepth+Z-st)/m),it=st*I;for(let mt=0;mt<g;++mt){let gt=Math.max(0,Math.ceil((nt-mt)/f)),Ct=Math.min(p.outHeight,(p.inHeight+nt-mt)/f),Rt=mt*N+it;for(let Dt=0;Dt<x;++Dt){let Ht=Math.max(0,Math.ceil((et-Dt)/d)),qt=Math.min(p.outWidth,(p.inWidth+et-Dt)/d),ce=Dt*E+Rt;for(let ge=0;ge<p.inChannels;++ge){let re=ge*A+ce;for(let xe=0;xe<p.outChannels;++xe){let fe=0;for(let Ae=0;Ae<p.batchSize;++Ae){let De=Ae*q,Ln=Ae*F;for(let lr=at;lr<ot;++lr){let Vr=(st+lr*m-Z)*H+De,je=lr*P+Ln;for(let Gr=gt;Gr<Ct;++Gr){let ro=(mt+Gr*f-nt)*K+Vr,no=Gr*V+je;for(let Qr=Ht;Qr<qt;++Qr){let Wo=(Dt+Qr*d-et)*X+ro,Ei=Qr*G+no;fe+=W[Wo+ge]*D[Ei+xe]}}}}w[re+xe]=fe}}}}}return e.makeTensorInfo(b.shape,b.dtype,b.values)}var IP={kernelName:Ma,backendName:"cpu",kernelFunc:met};function fet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{pad:i,strides:a,inputShape:u}=n;tt([o],"conv3dBackpropInputV2");let l=y.computeStrides(o.shape),c=y.computeStrides(s.shape),p=S.computeConv3DInfo(u,s.shape,a,1,i),m=new le(p.inShape,"float32"),f=m.values,[d,h,g,x]=m.strides,b=e.data.get(o.dataId).values,[w,I,N,E]=l,A=e.data.get(s.dataId).values,[D,F,P,V]=c,{batchSize:G,filterDepth:W,filterHeight:q,filterWidth:H,inChannels:K,inDepth:X,inHeight:Z,inWidth:et,outChannels:nt,outDepth:st,outHeight:at,outWidth:ot,strideDepth:it,strideHeight:mt,strideWidth:gt}=p,Ct=W-1-p.padInfo.front,Rt=q-1-p.padInfo.top,Dt=H-1-p.padInfo.left;for(let Ht=0;Ht<G;++Ht)for(let qt=0;qt<K;++qt)for(let ce=0;ce<X;++ce){let ge=ce-Ct,re=Math.max(0,Math.ceil(ge/it)),xe=Math.min(st,(W+ge)/it);for(let fe=0;fe<Z;++fe){let Ae=fe-Rt,De=Math.max(0,Math.ceil(Ae/mt)),Ln=Math.min(at,(q+Ae)/mt);for(let lr=0;lr<et;++lr){let eo=lr-Dt,Vr=Math.max(0,Math.ceil(eo/gt)),je=Math.min(ot,(H+eo)/gt),Gr=0;for(let Wr=re;Wr<xe;++Wr){let ro=Wr*it-ge;for(let no=De;no<Ln;++no){let Qr=no*mt-Ae;for(let ka=Vr;ka<je;++ka){let Wo=ka*gt-eo,Ei=w*Ht+I*Wr+N*no+E*ka,Ar=D*(W-1-ro)+F*(q-1-Qr)+P*(H-1-Wo)+V*qt;for(let Ta=0;Ta<nt;++Ta){let qd=b[Ei+Ta],Kd=A[Ar+Ta];Gr+=qd*Kd}}}}f[d*Ht+h*ce+g*fe+x*lr+qt]=Gr}}}return e.makeTensorInfo(m.shape,m.dtype,m.values)}var CP={kernelName:La,backendName:"cpu",kernelFunc:fet};var det=At(is,r=>Math.cos(r)),vP={kernelName:is,backendName:"cpu",kernelFunc:det};var het=At(as,r=>Math.cosh(r)),SP={kernelName:as,backendName:"cpu",kernelFunc:het};function get(r){let{inputs:t,backend:e,attrs:n}=r,{image:o,boxes:s,boxInd:i}=t,{cropSize:a,method:u,extrapolationValue:l}=n,[c,p,m,f]=o.shape,d=s.shape[0],[h,g]=a,x=wt([d,h,g,f],"float32"),b=e.data.get(s.dataId).values,w=e.data.get(i.dataId).values,I=e.data.get(o.dataId).values,N=y.computeStrides(o.shape),E=y.computeStrides(x.shape);for(let A=0;A<d;A++){let D=A*4,F=b[D],P=b[D+1],V=b[D+2],G=b[D+3],W=w[A];if(W>=c)continue;let q=h>1?(V-F)*(p-1)/(h-1):0,H=g>1?(G-P)*(m-1)/(g-1):0;for(let K=0;K<h;K++){let X=h>1?F*(p-1)+K*q:.5*(F+V)*(p-1);if(X<0||X>p-1){for(let Z=0;Z<g;Z++)for(let et=0;et<f;et++){let nt=et+Z*E[2]+K*E[1]+A*E[0];x.values[nt]=l}continue}if(u==="bilinear"){let Z=Math.floor(X),et=Math.ceil(X),nt=X-Z;for(let st=0;st<g;st++){let at=g>1?P*(m-1)+st*H:.5*(P+G)*(m-1);if(at<0||at>m-1){for(let gt=0;gt<f;gt++){let Ct=gt+st*E[2]+K*E[1]+A*E[0];x.values[Ct]=l}continue}let ot=Math.floor(at),it=Math.ceil(at),mt=at-ot;for(let gt=0;gt<f;gt++){let Ct=gt+ot*N[2]+Z*N[1]+W*N[0],Rt=I[Ct];Ct=gt+it*N[2]+Z*N[1]+W*N[0];let Dt=I[Ct];Ct=gt+ot*N[2]+et*N[1]+W*N[0];let Ht=I[Ct];Ct=gt+it*N[2]+et*N[1]+W*N[0];let qt=I[Ct],ce=Rt+(Dt-Rt)*mt,ge=Ht+(qt-Ht)*mt;Ct=gt+st*E[2]+K*E[1]+A*E[0],x.values[Ct]=ce+(ge-ce)*nt}}}else for(let Z=0;Z<g;++Z){let et=g>1?P*(m-1)+Z*H:.5*(P+G)*(m-1);if(et<0||et>m-1){for(let at=0;at<f;at++){let ot=at+Z*E[2]+K*E[1]+A*E[0];x.values[ot]=l}continue}let nt=Math.round(et),st=Math.round(X);for(let at=0;at<f;at++){let ot=at+nt*N[2]+st*N[1]+W*N[0],it=at+Z*E[2]+K*E[1]+A*E[0];x.values[it]=I[ot]}}}}return e.makeTensorInfo(x.shape,x.dtype,x.values)}var NP={kernelName:Ba,backendName:"cpu",kernelFunc:get};function xet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n;tt(o,"cumprod");let u=S.getAxesPermutation([s],o.shape.length),l=o;u!=null&&(l=Ge({inputs:{x:o},backend:e,attrs:{perm:u}}));let c=S.getInnerMostAxes(1,o.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);let p=ur(l.dtype,"int32"),m=y.makeOnesTypedArray(y.sizeFromShape(l.shape),p),f=e.data.get(l.dataId).values,d=l.shape[l.shape.length-1],h=a?(x,b)=>x+d-b-1:(x,b)=>x+b;for(let x=0;x<f.length;x+=d)for(let b=0;b<d;b++){let w=h(x,b);if(b===0)m[w]=i?1:f[w];else{let I=h(x,b-1);m[w]=i?f[I]*m[I]:f[w]*m[I]}}let g=e.makeTensorInfo(l.shape,p,m);if(u!=null){let x=S.getUndoAxesPermutation(u),b=Ge({inputs:{x:g},backend:e,attrs:{perm:x}});return e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(l),b}return g}var kP={kernelName:za,backendName:"cpu",kernelFunc:xet};function yet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n;tt(o,"cumsum");let u=S.getAxesPermutation([s],o.shape.length),l=o;u!=null&&(l=Ge({inputs:{x:o},backend:e,attrs:{perm:u}}));let c=S.getInnerMostAxes(1,o.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);let p=ur(l.dtype,"int32"),m=y.makeZerosTypedArray(y.sizeFromShape(l.shape),p),f=e.data.get(l.dataId).values,d=l.shape[l.shape.length-1],h=a?(x,b)=>x+d-b-1:(x,b)=>x+b;for(let x=0;x<f.length;x+=d)for(let b=0;b<d;b++){let w=h(x,b);if(b===0)m[w]=i?0:f[w];else{let I=h(x,b-1);m[w]=i?f[I]+m[I]:f[w]+m[I]}}let g=e.makeTensorInfo(l.shape,p,m);if(u!=null){let x=S.getUndoAxesPermutation(u),b=Ge({inputs:{x:g},backend:e,attrs:{perm:x}});return e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(l),b}return g}var TP={kernelName:ls,backendName:"cpu",kernelFunc:yet};function bet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,weights:s}=t,{size:i,binaryOutput:a}=n;if(o.shape.length===1){let u=e.data.get(o.dataId).values,l=e.data.get(s.dataId).values,c=bd(u,l,s.dtype,s.shape,i);return e.makeTensorInfo([i],s.dtype,c)}else if(o.shape.length===2){let u=e.bufferSync(o),l=e.bufferSync(s),c=mw(u,l,i,a);return e.makeTensorInfo(c.shape,s.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var _P={kernelName:eu,backendName:"cpu",kernelFunc:bet};function wet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockSize:s,dataFormat:i}=n;y.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let a=o.shape[0],u=o.shape[1],l=o.shape[2],c=o.shape[3],p=u*s,m=l*s,f=c/(s*s),d=e.data.get(o.dataId).values,h=new Float32Array(a*p*m*f),g=0;for(let x=0;x<a;++x)for(let b=0;b<p;++b){let w=Math.floor(b/s),I=b%s;for(let N=0;N<m;++N){let E=Math.floor(N/s),A=N%s,D=(I*s+A)*f;for(let F=0;F<f;++F){let V=F+D+c*(E+l*(w+u*x));h[g++]=d[V]}}}return e.makeTensorInfo([a,p,m,f],o.dtype,h)}var EP={kernelName:Va,backendName:"cpu",kernelFunc:wet};function ET(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u,dimRoundingMode:l}=n;tt([o,s],"depthwiseConv2DNative");let c=y.computeStrides(o.shape),p=y.computeStrides(s.shape),m=u;m==null&&(m=[1,1]),y.assert(S.eitherStridesOrDilationsAreOne(i,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${m}'`);let f=S.computeConv2DInfo(o.shape,s.shape,i,m,a,l,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:x,padInfo:b}=f,w=b.left,I=b.top,N=f.outChannels/f.inChannels,E=new le(f.outShape,o.dtype),A=e.data.get(o.dataId).values,D=e.data.get(s.dataId).values,F=E.values;for(let P=0;P<f.batchSize;++P){let V=P*c[0],G=P*E.strides[0];for(let W=0;W<f.outHeight;++W){let q=G+W*E.strides[1],H=W*f.strideHeight-I;for(let K=0;K<d;++K){let X=H+K*g;if(X<0||X>=f.inHeight)continue;let Z=K*p[0],et=V+X*c[1];for(let nt=0;nt<f.outWidth;++nt){let st=q+nt*E.strides[2],at=nt*f.strideWidth-w;for(let ot=0;ot<h;++ot){let it=at+ot*x;if(it<0||it>=f.inWidth)continue;let mt=Z+ot*p[1],gt=et+it*f.inChannels,Ct=st,Rt=mt;for(let Dt=0;Dt<f.inChannels;++Dt){let Ht=A[gt+Dt];for(let qt=0;qt<N;++qt)F[Ct+qt]+=Ht*D[Rt+qt];Ct+=N,Rt+=N}}}}}}return e.makeTensorInfo(E.shape,E.dtype,E.values)}var AP={kernelName:us,backendName:"cpu",kernelFunc:ET};function Iet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,dilations:a,pad:u,dimRoundingMode:l,filterShape:c}=n;tt([o,s],"depthwiseConv2dNativeBackpropFilter");let p=S.computeConv2DInfo(o.shape,c,i,a,u,l,!0),{strideHeight:m,strideWidth:f,filterHeight:d,filterWidth:h}=p,g=new le(p.filterShape,"float32"),x=p.padInfo.left,b=p.padInfo.top,w=p.outChannels/p.inChannels,I=e.data.get(o.dataId).values,N=new le(o.shape,o.dtype,I),E=e.data.get(s.dataId).values,A=new le(s.shape,s.dtype,E);for(let D=0;D<d;++D){let F=Math.max(0,Math.ceil((b-D)/m)),P=Math.min(p.outHeight,(p.inHeight+b-D)/m);for(let V=0;V<h;++V){let G=Math.max(0,Math.ceil((x-V)/f)),W=Math.min(p.outWidth,(p.inWidth+x-V)/f);for(let q=0;q<p.outChannels;++q){let H=Math.trunc(q/w),K=q%w,X=0;for(let Z=0;Z<p.batchSize;++Z)for(let et=F;et<P;++et){let nt=D+et*m-b;for(let st=G;st<W;++st){let at=V+st*f-x;X+=N.get(Z,nt,at,H)*A.get(Z,et,st,q)}}g.set(X,D,V,H,K)}}}return e.makeTensorInfo(g.shape,g.dtype,g.values)}var DP={kernelName:Vp,backendName:"cpu",kernelFunc:Iet};function Cet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{strides:i,dilations:a,pad:u,dimRoundingMode:l,inputShape:c}=n;tt([o,s],"depthwiseConv2DNativeBackpropInput");let p=y.computeStrides(o.shape),m=y.computeStrides(s.shape),f=S.computeConv2DInfo(c,s.shape,i,a,u,l,!0),d=new le(f.inShape,"float32"),h=d.values,[g,x,b]=d.strides,w=e.data.get(o.dataId).values,[I,N,E]=p,A=e.data.get(s.dataId).values,[D,F,P]=m,{batchSize:V,filterHeight:G,filterWidth:W,inChannels:q,inHeight:H,inWidth:K,outChannels:X,outHeight:Z,outWidth:et,strideHeight:nt,strideWidth:st}=f,at=G-1-f.padInfo.top,ot=W-1-f.padInfo.left,it=X/q;for(let mt=0;mt<V;++mt)for(let gt=0;gt<q;++gt)for(let Ct=0;Ct<H;++Ct){let Rt=Ct-at,Dt=Math.max(0,Math.ceil(Rt/nt)),Ht=Math.min(Z,(G+Rt)/nt);for(let qt=0;qt<K;++qt){let ce=qt-ot,ge=Math.max(0,Math.ceil(ce/st)),re=Math.min(et,(W+ce)/st),xe=0;for(let fe=Dt;fe<Ht;++fe){let Ae=fe*nt-Rt;for(let De=ge;De<re;++De){let Ln=De*st-ce,lr=I*mt+N*fe+E*De,eo=D*(G-1-Ae)+F*(W-1-Ln)+P*gt;for(let Vr=0;Vr<it;++Vr){let je=gt*it+Vr,Gr=w[lr+je],Wr=A[eo+Vr];xe+=Gr*Wr}}}h[g*mt+x*Ct+b*qt+gt]=xe}}return e.makeTensorInfo(d.shape,d.dtype,d.values)}var $P={kernelName:Gp,backendName:"cpu",kernelFunc:Cet};function vet(r){let{inputs:t,backend:e}=r,{x:n}=t,o=y.sizeFromShape(n.shape),s=e.data.get(n.dataId).values,i=wt([o,o],n.dtype),a=i.values;for(let l=0;l<s.length;l++)a[l*o+l]=s[l];let u=[...n.shape,...n.shape];return e.makeTensorInfo(u,i.dtype,i.values)}var RP={kernelName:ru,backendName:"cpu",kernelFunc:vet};var FP={kernelName:cs,backendName:"cpu",kernelFunc:({inputs:r,backend:t,attrs:e})=>{let{x:n,filter:o}=r,{strides:s,pad:i,dilations:a}=e,u=t,l=u.data.get(n.dataId).values,c=n.shape.length,p=u.data.get(o.dataId).values,m=o.shape.length,{batchSize:f,inHeight:d,inWidth:h,inChannels:g,outHeight:x,outWidth:b,padInfo:w,strideHeight:I,strideWidth:N,filterHeight:E,filterWidth:A,dilationHeight:D,dilationWidth:F,outShape:P}=S.computeDilation2DInfo(n.shape,o.shape,s,i,"NHWC",a),V=y.sizeFromShape(P),G=P.length,W=y.getArrayFromDType(n.dtype,V);for(let H=0;H<f;++H)for(let K=0;K<x;++K){let X=K*I-w.top;for(let Z=0;Z<b;++Z){let et=Z*N-w.left;for(let nt=0;nt<g;++nt){let st=Number.MIN_SAFE_INTEGER;for(let ot=0;ot<E;++ot){let it=X+ot*D;if(it>=0&&it<d)for(let mt=0;mt<A;++mt){let gt=et+mt*F;if(gt>=0&><h){let Ct=y.locToIndex([H,it,gt,nt],c,y.computeStrides(n.shape)),Rt=y.locToIndex([ot,mt,nt],m,y.computeStrides(o.shape)),Dt=l[Ct]+p[Rt];Dt>st&&(st=Dt)}}}let at=y.locToIndex([H,K,Z,nt],G,y.computeStrides(P));W[at]=st}}}return{dataId:u.write(y.toTypedArray(W,n.dtype),P,n.dtype),shape:P,dtype:n.dtype}}};var OP={kernelName:ou,backendName:"cpu",kernelFunc:({inputs:r,backend:t,attrs:e})=>{let{x:n,filter:o,dy:s}=r,{strides:i,pad:a,dilations:u}=e,l=t,c=y.toNestedArray(n.shape,l.data.get(n.dataId).values),p=y.toNestedArray(o.shape,l.data.get(o.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:w,strideWidth:I,filterHeight:N,filterWidth:E,dilationHeight:A,dilationWidth:D,outShape:F}=S.computeDilation2DInfo(n.shape,o.shape,i,a,"NHWC",u);y.assert(s.rank===F.length,()=>`Error in ${ou}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let P=y.toNestedArray(F,l.data.get(s.dataId).values),V=y.makeZerosNestedTypedArray(o.shape,o.dtype);for(let W=0;W<m;++W)for(let q=0;q<g;++q){let H=q*w-b.top;for(let K=0;K<x;++K){let X=K*I-b.left;for(let Z=0;Z<h;++Z){let et=Number.MIN_SAFE_INTEGER,nt=0,st=0;for(let at=0;at<N;++at){let ot=H+at*A;if(ot>=0&&ot<f)for(let it=0;it<E;++it){let mt=X+it*D;if(mt>=0&&mt<d){let gt=c[W][ot][mt][Z]+p[at][it][Z];gt>et&&(et=gt,nt=at,st=it)}}}V[nt][st][Z]+=P[W][q][K][Z]}}}return{dataId:l.write(y.toTypedArray(V,n.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var PP={kernelName:nu,backendName:"cpu",kernelFunc:({inputs:r,backend:t,attrs:e})=>{let{x:n,filter:o,dy:s}=r,{strides:i,pad:a,dilations:u}=e,l=t,c=y.toNestedArray(n.shape,l.data.get(n.dataId).values),p=y.toNestedArray(o.shape,l.data.get(o.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:w,strideWidth:I,filterHeight:N,filterWidth:E,dilationHeight:A,dilationWidth:D,outShape:F}=S.computeDilation2DInfo(n.shape,o.shape,i,a,"NHWC",u);y.assert(s.rank===F.length,()=>`Error in ${nu}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let P=y.toNestedArray(F,l.data.get(s.dataId).values),V=y.makeZerosNestedTypedArray(n.shape,n.dtype);for(let W=0;W<m;++W)for(let q=0;q<g;++q){let H=q*w-b.top;for(let K=0;K<x;++K){let X=K*I-b.left;for(let Z=0;Z<h;++Z){let et=Number.MIN_SAFE_INTEGER,nt=H<0?0:H,st=X<0?0:X;for(let at=0;at<N;++at){let ot=H+at*A;if(ot>=0&&ot<f)for(let it=0;it<E;++it){let mt=X+it*D;if(mt>=0&&mt<d){let gt=c[W][ot][mt][Z]+p[at][it][Z];gt>et&&(et=gt,nt=ot,st=mt)}}}V[W][nt][st][Z]+=P[W][q][K][Z]}}}return{dataId:l.write(y.toTypedArray(V,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function Net(r){let{inputs:t,backend:e,attrs:n}=r,{image:o}=t,{canvas:s,options:i}=n,{contextOptions:a,imageOptions:u}=i||{},l=(u==null?void 0:u.alpha)||1,c=(a==null?void 0:a.contextType)||"2d";if(c!=="2d")throw new Error(`Context type ${a.contextType} is not supported by the CPU backend.`);let p=s.getContext(c,(a==null?void 0:a.contextAttributes)||{});if(p==null)throw new Error(`Could not get the context with ${c} type.`);let[m,f]=o.shape.slice(0,2),d=o.shape.length===2?1:o.shape[2],h=e.data.get(o.dataId).values,g=o.dtype==="float32"?255:1,x=new Uint8ClampedArray(f*m*4);for(let w=0;w<m*f;++w){let I=[0,0,0,255*l];for(let E=0;E<d;E++){let A=h[w*d+E];if(o.dtype==="float32"){if(A<0||A>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${A}.`)}else if(o.dtype==="int32"&&(A<0||A>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${A}.`);d===1?(I[0]=A*g,I[1]=A*g,I[2]=A*g):I[E]=A*g}let N=w*4;x[N+0]=Math.round(I[0]),x[N+1]=Math.round(I[1]),x[N+2]=Math.round(I[2]),x[N+3]=Math.round(I[3])}s.width=f,s.height=m;let b=new ImageData(x,f,m);return p.putImageData(b,0,0),o}var MP={kernelName:Zg,backendName:"cpu",kernelFunc:Net};function zl(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;tt(o,"sum");let a;o.dtype==="bool"?a=Lo({inputs:{x:o},backend:e,attrs:{dtype:"int32"}}):a=Zr({inputs:{x:o},backend:e});let u=a.shape.length,l=y.parseAxisParam(s,a.shape),c=S.getAxesPermutation(l,u),p=l,m=a;c!=null&&(m=Ge({inputs:{x:a},backend:e,attrs:{perm:c}}),p=S.getInnerMostAxes(p.length,u)),S.assertAxesAreInnerMostDims("sum",p,m.shape.length);let[f,d]=S.computeOutAndReduceShapes(m.shape,p),h=S.upcastType(m.dtype,"int32"),g=xd(e,f,h),x=y.sizeFromShape(d),b=e.data.get(g.dataId).values,w=e.data.get(m.dataId).values;for(let I=0;I<b.length;++I){let N=I*x,E=0;for(let A=0;A<x;++A)E+=w[N+A];b[I]=E}if(i){let I=S.expandShapeToKeepDim(g.shape,l),N=g;g=Qt({inputs:{x:g},backend:e,attrs:{shape:I}}),e.disposeIntermediateTensorInfo(N)}return e.disposeIntermediateTensorInfo(a),c!=null&&e.disposeIntermediateTensorInfo(m),g}var LP={kernelName:ri,backendName:"cpu",kernelFunc:zl};function ket(r){let{inputs:t,backend:e,attrs:n}=r,{equation:o}=n,s=t,{allDims:i,summedDims:a,idDims:u}=S.decodeEinsumEquation(o,s.length);S.checkEinsumDimSizes(i.length,u,s);let{path:l,steps:c}=S.getEinsumComputePath(a,u),p=c.length,m=null,f=i.length,d=[];for(let h=0;h<p;++h){for(let g of c[h]){let{permutationIndices:x,expandDims:b}=S.getEinsumPermutation(f,u[g]),w;S.isIdentityPermutation(x)?w=s[g]:(w=Ge({inputs:{x:s[g]},backend:e,attrs:{perm:x}}),d.push(w));let I=w.shape.slice();for(let N=0;N<b.length;++N)I.splice(b[N],0,1);y.arraysEqual(w.shape,I)||(w=Qt({inputs:{x:w},backend:e,attrs:{shape:I}}),d.push(w)),m===null?m=w:(m=lp({inputs:{a:w,b:m},backend:e}),d.push(m))}h<p-1&&(l[h]>=0&&(m=zl({inputs:{x:m},backend:e,attrs:{axis:l[h]-(i.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&e.disposeIntermediateTensorInfo(h);return m}var zP={kernelName:Wp,backendName:"cpu",kernelFunc:ket};function Tet(r){let{inputs:t,backend:e}=r,{dy:n,y:o}=t;tt([n,o],"eluGrad");let s=new Float32Array(y.sizeFromShape(o.shape)),i=e.data.get(o.dataId).values,a=e.data.get(n.dataId).values;for(let u=0;u<i.length;++u){let l=i[u];l>=0?s[u]=a[u]:s[u]=a[u]*(l+1)}return e.makeTensorInfo(o.shape,"float32",s)}var BP={kernelName:Ga,backendName:"cpu",kernelFunc:Tet};var _et=S.ERF_P,Eet=S.ERF_A1,Aet=S.ERF_A2,Det=S.ERF_A3,$et=S.ERF_A4,Ret=S.ERF_A5,Fet=At(fs,r=>{let t=Math.sign(r),e=Math.abs(r),n=1/(1+_et*e);return t*(1-((((Ret*n+$et)*n+Det)*n+Aet)*n+Eet)*n*Math.exp(-e*e))}),VP={kernelName:fs,backendName:"cpu",kernelFunc:Fet};function Sd(r){let{inputs:t,backend:e,attrs:n}=r,{input:o}=t,{dim:s}=n,i=o.shape.length,a=o.shape.slice(),u=s;return s<0&&(y.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),u=i+s+1),a.splice(u,0,1),Qt({inputs:{x:o},backend:e,attrs:{shape:a}})}var GP={kernelName:Li,backendName:"cpu",kernelFunc:Sd};var Oet=Jt((r,t)=>r/t),eg=oe(ps,Oet),rg={kernelName:ps,backendName:"cpu",kernelFunc:eg};function _w(r,t,e){let n=r.shape,o=n[0],s=n[1],i=e.data.get(r.dataId),a=i.complexTensorInfos.real,u=i.complexTensorInfos.imag,l=[o,s],c=y.sizeFromShape(l),p=y.getTypedArrayFromDType("float32",c),m=y.getTypedArrayFromDType("float32",c);for(let g=0;g<o;g++){let x=Bo({inputs:{x:a},backend:e,attrs:{begin:[g,0],size:[1,s]}}),b=Bo({inputs:{x:u},backend:e,attrs:{begin:[g,0],size:[1,s]}}),w=Cr({inputs:{real:x,imag:b},backend:e}),{real:I,imag:N}=Pet(w,t,e),E=S.mergeRealAndImagArrays(I,N);for(let A=0;A<s;A++){let D=S.getComplexWithIndex(E,A);p[g*s+A]=D.real,m[g*s+A]=D.imag}e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(w)}let f=e.makeTensorInfo(l,"float32",p),d=e.makeTensorInfo(l,"float32",m),h=Cr({inputs:{real:f,imag:d},backend:e});return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),h}function Pet(r,t,e){let n=y.sizeFromShape(r.shape),o=e.data.get(r.dataId),s=e.data.get(o.complexTensorInfos.real.dataId).values,i=e.data.get(o.complexTensorInfos.imag.dataId).values;if(Met(n)){let a=AT(s,i,n,t,e),u=[r.shape[0],r.shape[1]];if(t){let l=e.makeTensorInfo(u,"float32",a.real),c=e.makeTensorInfo(u,"float32",a.imag),p=e.makeTensorInfo([],"float32",y.createScalarValue(n,"float32")),m=Zr({inputs:{x:p},backend:e}),f=rg.kernelFunc({inputs:{a:l,b:p},backend:e}),d=rg.kernelFunc({inputs:{a:c,b:m},backend:e}),h=e.data.get(f.dataId).values,g=e.data.get(d.dataId).values;return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),{real:h,imag:g}}return a}else{let a=S.mergeRealAndImagArrays(s,i),u=Let(a,n,t);return S.splitRealAndImagArrays(u)}}function Met(r){return(r&r-1)===0}function AT(r,t,e,n,o){if(e===1)return{real:r,imag:t};let s=S.mergeRealAndImagArrays(r,t),i=e/2,a=S.complexWithEvenIndex(s),u=a.real,l=a.imag,c=[u.length],p=o.makeTensorInfo(c,"float32",u),m=o.makeTensorInfo(c,"float32",l),f=Cr({inputs:{real:p,imag:m},backend:o}),d=S.complexWithOddIndex(s),h=d.real,g=d.imag,x=[h.length],b=o.makeTensorInfo(x,"float32",h),w=o.makeTensorInfo(x,"float32",g),I=Cr({inputs:{real:b,imag:w},backend:o}),N=AT(u,l,i,n,o),E=N.real,A=N.imag,D=[E.length],F=o.makeTensorInfo(D,"float32",E),P=o.makeTensorInfo(D,"float32",A),V=Cr({inputs:{real:F,imag:P},backend:o}),G=AT(h,g,i,n,o),W=G.real,q=G.imag,H=[W.length],K=o.makeTensorInfo(H,"float32",W),X=o.makeTensorInfo(H,"float32",q),Z=Cr({inputs:{real:K,imag:X},backend:o}),et=S.exponents(e,n),nt=[et.real.length],st=o.makeTensorInfo(nt,"float32",et.real),at=o.makeTensorInfo(nt,"float32",et.imag),ot=Cr({inputs:{real:st,imag:at},backend:o}),it=lp({inputs:{a:ot,b:Z},backend:o}),mt=Ca({inputs:{a:V,b:it},backend:o}),gt=Qh({inputs:{a:V,b:it},backend:o}),Ct=Mo({inputs:{input:mt},backend:o}),Rt=Mo({inputs:{input:gt},backend:o}),Dt=va({inputs:{input:mt},backend:o}),Ht=va({inputs:{input:gt},backend:o}),qt=Yu({inputs:[Ct,Rt],backend:o,attrs:{axis:0}}),ce=Yu({inputs:[Dt,Ht],backend:o,attrs:{axis:0}}),ge=o.data.get(qt.dataId).values,re=o.data.get(ce.dataId).values;return o.disposeIntermediateTensorInfo(p),o.disposeIntermediateTensorInfo(m),o.disposeIntermediateTensorInfo(f),o.disposeIntermediateTensorInfo(b),o.disposeIntermediateTensorInfo(w),o.disposeIntermediateTensorInfo(I),o.disposeIntermediateTensorInfo(F),o.disposeIntermediateTensorInfo(P),o.disposeIntermediateTensorInfo(V),o.disposeIntermediateTensorInfo(K),o.disposeIntermediateTensorInfo(X),o.disposeIntermediateTensorInfo(Z),o.disposeIntermediateTensorInfo(st),o.disposeIntermediateTensorInfo(at),o.disposeIntermediateTensorInfo(ot),o.disposeIntermediateTensorInfo(it),o.disposeIntermediateTensorInfo(mt),o.disposeIntermediateTensorInfo(gt),o.disposeIntermediateTensorInfo(Ct),o.disposeIntermediateTensorInfo(Dt),o.disposeIntermediateTensorInfo(Rt),o.disposeIntermediateTensorInfo(Ht),o.disposeIntermediateTensorInfo(qt),o.disposeIntermediateTensorInfo(ce),{real:ge,imag:re}}function Let(r,t,e){let n=new Float32Array(t*2);for(let o=0;o<t;o++){let s=0,i=0;for(let a=0;a<t;a++){let u=S.exponent(o*a,t,e),l=S.getComplexWithIndex(r,a);s+=l.real*u.real-l.imag*u.imag,i+=l.real*u.imag+l.imag*u.real}e&&(s/=t,i/=t),S.assignToTypedArray(n,s,i,o)}return n}function zet(r){let{inputs:t,backend:e}=r,{input:n}=t,o=y.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=o/s,a=Qt({inputs:{x:n},backend:e,attrs:{shape:[i,s]}}),u=_w(a,!1,e),l=Qt({inputs:{x:u},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(u),l}var WP={kernelName:Up,backendName:"cpu",kernelFunc:zet};function ng(r){let{backend:t,attrs:e}=r,{shape:n,value:o,dtype:s}=e,i=s||y.inferDtype(o),a=y.getArrayFromDType(i,y.sizeFromShape(n));return Bet(a,o,i),t.makeTensorInfo(n,i,a)}var UP={kernelName:su,backendName:"cpu",kernelFunc:ng};function Bet(r,t,e){r.fill(t)}var HP={kernelName:Ua,backendName:"cpu",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{image:n}=r,o=e,s=y.getTypedArrayFromDType(n.dtype,y.sizeFromShape(n.shape)),[i,a,u,l]=n.shape,c=o.data.get(n.dataId).values;for(let m=0;m<i;m++){let f=m*u*a*l;for(let d=0;d<a;d++){let h=d*(u*l);for(let g=0;g<u;g++){let x=g*l;for(let b=0;b<l;b++){let w=Math.round(u-g-1),I=f+h+x+b,N=c[I];if(w>=0&&w<u){let E=w*l,A=f+h+E+b;N=c[A]}s[I]=N}}}}return{dataId:o.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function Vet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=_T({inputs:{x:o,filter:s},backend:e,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:m}});if(i){let g=h;if(c==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let x=Qt({inputs:{x:i},backend:e,attrs:{shape:[i.shape[0],1,1]}});h=Ca({inputs:{a:h,b:x},backend:e}),e.disposeIntermediateTensorInfo(x)}else h=Ca({inputs:{a:h,b:i},backend:e});e.disposeIntermediateTensorInfo(g)}if(f){let g=h;if(c==="NCHW"&&f==="prelu"&&a.shape.length===1&&a.shape[0]!==1){let x=Qt({inputs:{x:a},backend:e,attrs:{shape:[a.shape[0],1,1]}});h=hp(e,h,f,x,d),e.disposeIntermediateTensorInfo(x)}else h=hp(e,h,f,a,d);e.disposeIntermediateTensorInfo(g)}return h}var qP={kernelName:Ji,backendName:"cpu",kernelFunc:Vet};function Get(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=ET({inputs:{x:o,filter:s},backend:e,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:m}});if(i){let g=h;h=Ca({inputs:{a:h,b:i},backend:e}),e.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=hp(e,h,f,a,d),e.disposeIntermediateTensorInfo(g)}return h}var KP={kernelName:Qi,backendName:"cpu",kernelFunc:Get};function Wet(r){let{inputs:t,backend:e}=r,{params:n,indices:o}=t,s=y.sizeFromShape(n.shape),i=o.shape,a=i[i.length-1],[u,l,c,p]=S.prepareAndValidate(n,o);if(l===0)return e.makeTensorInfo(u,n.dtype,[]);let m=e.data.get(o.dataId).values,f=e.bufferSync(n),d=fw(m,f,n.dtype,l,a,c,p,n.shape,s);return e.makeTensorInfo(u,n.dtype,d.values)}var jP={kernelName:Ha,backendName:"cpu",kernelFunc:Wet};function Uet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,indices:s}=t,{axis:i,batchDims:a}=n;tt([o,s],"gatherV2");let u=y.parseAxisParam(i,o.shape)[0],l=e.data.get(s.dataId).values,c=o.shape[u];for(let I=0;I<l.length;++I){let N=l[I];y.assert(N<=c-1&&N>=0,()=>`GatherV2: the index value ${N} is not in [0, ${c-1}]`)}let p=a;a==null&&(p=0);let m=y.sizeFromShape(s.shape),f=S.segment_util.collectGatherOpShapeInfo(o,s,u,p),d=Qt({inputs:{x:o},backend:e,attrs:{shape:[f.batchSize,f.outerSize,f.dimSize,f.sliceSize]}}),h=Qt({inputs:{x:s},backend:e,attrs:{shape:[f.batchSize,m/f.batchSize]}}),g=[f.batchSize,f.outerSize,m/f.batchSize,f.sliceSize],x=e.bufferSync(h),b=e.bufferSync(d),w=dw(b,x,g);return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.makeTensorInfo(f.outputShape,w.dtype,w.values)}var XP={kernelName:zi,backendName:"cpu",kernelFunc:Uet};function Het(r){let{inputs:t,backend:e}=r,{input:n}=t,o=y.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=o/s,a=Qt({inputs:{x:n},backend:e,attrs:{shape:[i,s]}}),u=_w(a,!0,e),l=Qt({inputs:{x:u},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(u),l}var YP={kernelName:Hp,backendName:"cpu",kernelFunc:Het};var qet=At(ws,r=>Number.isFinite(r)?1:0,"bool"),ZP={kernelName:ws,backendName:"cpu",kernelFunc:qet};var Ket=At(Is,r=>Math.abs(r)===1/0?1:0,"bool"),JP={kernelName:Is,backendName:"cpu",kernelFunc:Ket};var jet=At(Cs,r=>Number.isNaN(r)?1:0,"bool"),QP={kernelName:Cs,backendName:"cpu",kernelFunc:jet};function Xet(r){let{backend:t,attrs:e}=r,{start:n,stop:o,num:s}=e,i=hw(n,o,s);return t.makeTensorInfo([i.length],"float32",i)}var tM={kernelName:Xa,backendName:"cpu",kernelFunc:Xet};var Yet=At(Ns,r=>Math.log1p(r)),eM={kernelName:Ns,backendName:"cpu",kernelFunc:Yet};var Zet=Jt((r,t)=>r&&t),Jet=oe(Ya,Zet,null,"bool"),rM={kernelName:Ya,backendName:"cpu",kernelFunc:Jet};var Qet=At(Za,r=>r?0:1,"bool"),nM={kernelName:Za,backendName:"cpu",kernelFunc:Qet};var trt=Jt((r,t)=>r||t),ert=oe(Ja,trt,null,"bool"),oM={kernelName:Ja,backendName:"cpu",kernelFunc:ert};function rrt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{depthRadius:s,bias:i,alpha:a,beta:u}=n;tt(o,"LRN");let l=o.shape[3],c=l-1,p=e.data.get(o.dataId).values,m=y.sizeFromShape(o.shape),f=new Float32Array(m);function d(h){let g=h%l,x=h-g+Math.max(0,g-s),b=h-g+Math.min(g+s,c),w=0;for(;x<=b;x++){let I=p[x];w+=I*I}return w}for(let h=0;h<m;h++){let g=d(h),x=p[h]*Math.pow(i+a*g,-u);f[h]=x}return e.makeTensorInfo(o.shape,o.dtype,f)}var sM={kernelName:ks,backendName:"cpu",kernelFunc:rrt};function nrt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,y:s,dy:i}=t,{depthRadius:a,bias:u,alpha:l,beta:c}=n;tt(i,"LRNGrad");let p=y.sizeFromShape(i.shape),m=i.shape[3],f=e.data.get(i.dataId).values,d=e.data.get(o.dataId).values,h=e.data.get(s.dataId).values,g=new Float32Array(p),x=p;for(let b=0;b<x;b++){let w=b%m,I=b-w+Math.max(0,w-a),N=b-w+Math.min(m,w+a+1),E=0;for(let A=I;A<N;A++)E+=Math.pow(d[A],2);E=l*E+u;for(let A=I;A<N;A++){let D=-2*l*c*d[A]*h[b]/E;b===A&&(D+=Math.pow(E,-c)),D*=f[b],g[A]+=D}}return e.makeTensorInfo(i.shape,o.dtype,g)}var iM={kernelName:Qa,backendName:"cpu",kernelFunc:nrt};function DT(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reductionIndices:s,keepDims:i}=n,a=e,u=o.shape,l=u.length,c=y.parseAxisParam(s,u),p=c,m=S.getAxesPermutation(p,l),f=a.data.get(o.dataId).values;if(m!=null){let I=new Array(l);for(let N=0;N<I.length;N++)I[N]=u[m[N]];f=wd(f,u,o.dtype,m,I),p=S.getInnerMostAxes(p.length,l),u=I}tt(o,"max"),S.assertAxesAreInnerMostDims("max",p,l);let[d,h]=S.computeOutAndReduceShapes(u,p),g=y.sizeFromShape(h),x=gw(f,g,d,o.dtype),b=a.write(x,d,o.dtype),w=d;return i&&(w=S.expandShapeToKeepDim(d,c)),{dataId:b,shape:w,dtype:o.dtype}}var aM={kernelName:Ts,backendName:"cpu",kernelFunc:DT};function ort(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;tt(o,"maxPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=n,l=1;y.assert(S.eitherStridesOrDilationsAreOne(i,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=S.computePool2DInfo(o.shape,s,i,l,a,u),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Zr({inputs:{x:o},backend:e});else{let m=e.data.get(o.dataId).values,f=y.computeStrides(o.shape),d=vd(m,o.shape,o.dtype,f,c,"max");p=e.makeTensorInfo(c.outShape,o.dtype,d.values)}return p}var lM={kernelName:Es,backendName:"cpu",kernelFunc:ort};function srt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u,dataFormat:l}=n;tt(o,"maxPool3d");let c=S.computePool3DInfo(o.shape,s,i,1,a,u,l),p=e.data.get(o.dataId).values,m=Tw(p,o.shape,o.dtype,y.computeStrides(o.shape),c,"max");return e.makeTensorInfo(m.shape,"float32",m.values)}var uM={kernelName:Bi,backendName:"cpu",kernelFunc:srt};function irt(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=n;tt([o,s],"maxPool3DGrad");let c=S.computePool3DInfo(s.shape,i,a,1,u,l),p=e.bufferSync(s),m=oP(p,c),f=c.strideDepth,d=c.strideHeight,h=c.strideWidth,g=c.dilationDepth,x=c.dilationHeight,b=c.dilationWidth,w=c.effectiveFilterDepth,I=c.effectiveFilterHeight,N=c.effectiveFilterWidth,E=w-1-c.padInfo.front,A=N-1-c.padInfo.left,D=I-1-c.padInfo.top,F=wt(s.shape,"float32"),P=e.bufferSync(o);for(let V=0;V<c.batchSize;++V)for(let G=0;G<c.inChannels;++G)for(let W=0;W<c.inDepth;++W)for(let q=0;q<c.inHeight;++q)for(let H=0;H<c.inWidth;++H){let K=W-E,X=q-D,Z=H-A,et=0;for(let nt=0;nt<w;nt+=g){let st=(K+nt)/f;if(!(st<0||st>=c.outDepth||Math.floor(st)!==st))for(let at=0;at<I;at+=x){let ot=(X+at)/d;if(!(ot<0||ot>=c.outHeight||Math.floor(ot)!==ot))for(let it=0;it<N;it+=b){let mt=(Z+it)/h;if(mt<0||mt>=c.outWidth||Math.floor(mt)!==mt)continue;let gt=w*I*N-1-m.get(V,st,ot,mt,G),Ct=nt*I*N+at*N+it,Rt=gt===Ct?1:0;if(Rt===0)continue;let Dt=P.get(V,st,ot,mt,G);et+=Dt*Rt}}}F.set(et,V,W,q,H,G)}return e.makeTensorInfo(F.shape,F.dtype,F.values)}var cM={kernelName:au,backendName:"cpu",kernelFunc:irt};function art(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s,output:i}=t,a=s;tt([s,i],"maxPoolGrad");let{filterSize:u,strides:l,pad:c,dimRoundingMode:p}=n,m=S.computePool2DInfo(a.shape,u,l,1,c,p),f=e.data.get(a.dataId).values,d=wt(m.outShape,a.dtype,kw(f,a.shape,a.dtype,m).values),h=m.strideHeight,g=m.strideWidth,x=m.dilationHeight,b=m.dilationWidth,w=m.effectiveFilterHeight,I=m.effectiveFilterWidth,N=I-1-m.padInfo.left,E=w-1-m.padInfo.top,A=wt(a.shape,"float32"),D=e.data.get(o.dataId).values,F=wt(o.shape,"float32",D);for(let P=0;P<m.batchSize;++P)for(let V=0;V<m.inChannels;++V)for(let G=0;G<m.inHeight;++G)for(let W=0;W<m.inWidth;++W){let q=G-E,H=W-N,K=0;for(let X=0;X<w;X+=x){let Z=(q+X)/h;if(!(Z<0||Z>=m.outHeight||Math.floor(Z)!==Z))for(let et=0;et<I;et+=b){let nt=(H+et)/g;if(nt<0||nt>=m.outWidth||Math.floor(nt)!==nt)continue;let st=w*I-1-d.get(P,Z,nt,V),at=X*I+et,ot=st===at?1:0;if(ot===0)continue;let it=F.get(P,Z,nt,V);K+=it*ot}}A.set(K,P,G,W,V)}return e.makeTensorInfo(A.shape,A.dtype,A.values)}var pM={kernelName:iu,backendName:"cpu",kernelFunc:art};function mM(r,t,e,n,o){let s=y.computeStrides(t),i=vd(r,t,e,s,o,"max"),a=kw(r,t,e,o,!0,n);return[i.values,a.values]}var fM={kernelName:lu,backendName:"cpu",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{x:n}=r,{filterSize:o,strides:s,pad:i,includeBatchInIndex:a}=t,u=e;tt(n,"MaxPoolWithArgmax");let l=u.data.get(n.dataId).values,c=S.computePool2DInfo(n.shape,o,s,[1,1],i),[p,m]=mM(l,n.shape,n.dtype,a,c),f=u.write(p,c.outShape,n.dtype),d=u.write(m,c.outShape,n.dtype);return[{dataId:f,shape:c.outShape,dtype:n.dtype},{dataId:d,shape:c.outShape,dtype:"int32"}]}};function lrt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=y.parseAxisParam(s,o.shape),l=S.computeOutAndReduceShapes(o.shape,a)[1],c=y.sizeFromShape(l),p=[],m=e.makeTensorInfo([],"float32",new Float32Array([c]));p.push(m);let f=Lo({inputs:{x:o},backend:e,attrs:{dtype:"float32"}});p.push(f);let d=eg({inputs:{a:f,b:m},backend:e});p.push(d);let h=zl({inputs:{x:d},backend:e,attrs:{axis:s,keepDims:i}});return p.forEach(g=>e.disposeIntermediateTensorInfo(g)),h}var dM={kernelName:As,backendName:"cpu",kernelFunc:lrt};function urt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;tt(o,"min");let a=y.parseAxisParam(s,o.shape),u=a,l=S.getAxesPermutation(u,o.shape.length),c=o;l!=null&&(c=Ge({inputs:{x:o},backend:e,attrs:{perm:l}}),u=S.getInnerMostAxes(u.length,o.shape.length)),S.assertAxesAreInnerMostDims("min",u,c.shape.length);let[p,m]=S.computeOutAndReduceShapes(c.shape,u),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=e.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let I=0;I<f;++I){let N=h[b+I];(Number.isNaN(N)||N<w)&&(w=N)}d[x]=w}l!=null&&e.disposeIntermediateTensorInfo(c);let g=e.makeTensorInfo(p,c.dtype,d);if(i){let x=S.expandShapeToKeepDim(p,a),b=Qt({inputs:{x:g},backend:e,attrs:{shape:x}});return e.disposeIntermediateTensorInfo(g),b}return g}var hM={kernelName:Ds,backendName:"cpu",kernelFunc:urt};function crt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{paddings:s,mode:i}=n;tt(o,"mirrorPad");let a=s.map((w,I)=>w[0]+o.shape[I]+w[1]),u=s.map(w=>w[0]),l=s.map((w,I)=>w[0]+o.shape[I]),c=i==="reflect"?0:1,p=e.data.get(o.dataId).values,m=o.shape.length,f=y.computeStrides(o.shape),d=y.sizeFromShape(a),h=a.length,g=y.computeStrides(a),x=y.getTypedArrayFromDType(o.dtype,d);for(let w=0;w<d;w++){let I=y.indexToLoc(w,h,g);for(let E=0;E<h;E++)I[E]<u[E]?I[E]=u[E]*2-I[E]-c:I[E]>=l[E]&&(I[E]=(l[E]-1)*2-I[E]+c);I=I.map((E,A)=>E-u[A]);let N=y.locToIndex(I,m,f);x[w]=p[N]}return{dataId:e.write(x,a,o.dtype),shape:a,dtype:o.dtype}}var gM={kernelName:Rs,backendName:"cpu",kernelFunc:crt};var prt=Jt((r,t)=>{let e=r%t;return r<0&&t<0||r>=0&&t>=0?e:(e+t)%t}),mrt=oe(Fs,prt),xM={kernelName:Fs,backendName:"cpu",kernelFunc:mrt};var bM=Xl(bh());function $T(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{dim:s}=n,i=o.shape.length,a=s;if(a===-1&&(a=i-1),a!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${a}`);let u=y.parseAxisParam([a],o.shape),l=DT({inputs:{x:o},backend:e,attrs:{reductionIndices:u,keepDims:!1}}),c=S.expandShapeToKeepDim(l.shape,u),p=Qt({inputs:{x:l},backend:e,attrs:{shape:c}}),m=Qh({inputs:{a:o,b:p},backend:e}),f=rT({inputs:{x:m},backend:e}),d=zl({inputs:{x:f},backend:e,attrs:{axis:u,keepDims:!1}}),h=Qt({inputs:{x:d},backend:e,attrs:{shape:c}}),g=eg({inputs:{a:f,b:h},backend:e});return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),g}var yM={kernelName:ni,backendName:"cpu",kernelFunc:$T};function frt(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{numSamples:s,seed:i,normalized:a}=n;tt(o,"multinomial");let u=a?o:$T({inputs:{logits:o},backend:e,attrs:{dim:-1}}),l=u.shape[0],c=u.shape[1],p=e.data.get(u.dataId).values,m=[l,s],f=y.makeZerosTypedArray(y.sizeFromShape(m),"int32");for(let d=0;d<l;++d){let h=d*c,g=new Float32Array(c-1);g[0]=p[h];for(let w=1;w<g.length;++w)g[w]=g[w-1]+p[h+w];let x=bM.alea(i.toString()),b=d*s;for(let w=0;w<s;++w){let I=x();f[b+w]=g.length;for(let N=0;N<g.length;N++)if(I<g[N]){f[b+w]=N;break}}}return a||e.disposeIntermediateTensorInfo(u),e.makeTensorInfo(m,"int32",f)}var wM={kernelName:tl,backendName:"cpu",kernelFunc:frt};var drt=jr.nonMaxSuppressionV3Impl;function hrt(r){let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u}=n;tt(o,"NonMaxSuppression");let l=e.data.get(o.dataId).values,c=e.data.get(s.dataId).values,{selectedIndices:p}=drt(l,c,i,a,u);return e.makeTensorInfo([p.length],"int32",new Int32Array(p))}var IM={kernelName:rl,backendName:"cpu",kernelFunc:hrt};var grt=jr.nonMaxSuppressionV4Impl;function xrt(r){let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u,padToMaxOutputSize:l}=n;tt(o,"NonMaxSuppressionPadded");let c=e.data.get(o.dataId).values,p=e.data.get(s.dataId).values,{selectedIndices:m,validOutputs:f}=grt(c,p,i,a,u,l);return[e.makeTensorInfo([m.length],"int32",new Int32Array(m)),e.makeTensorInfo([],"int32",new Int32Array([f]))]}var CM={kernelName:nl,backendName:"cpu",kernelFunc:xrt};var yrt=jr.nonMaxSuppressionV5Impl;function brt(r){let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u,softNmsSigma:l}=n;tt(o,"NonMaxSuppressionWithScore");let c=e.data.get(o.dataId).values,p=e.data.get(s.dataId).values,m=i,f=a,d=u,h=l,{selectedIndices:g,selectedScores:x}=yrt(c,p,m,f,d,h);return[e.makeTensorInfo([g.length],"int32",new Int32Array(g)),e.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var vM={kernelName:ol,backendName:"cpu",kernelFunc:brt};function wrt(r){let{inputs:t,backend:e,attrs:n}=r,{indices:o}=t,{dtype:s,depth:i,onValue:a,offValue:u}=n;tt(o,"oneHot");let l=y.sizeFromShape(o.shape),c=new Float32Array(l*i);c.fill(u);let p=e.data.get(o.dataId).values;for(let m=0;m<l;++m)p[m]>=0&&p[m]<i&&(c[m*i+p[m]]=a);return e.makeTensorInfo([...o.shape,i],s,c)}var SM={kernelName:Ps,backendName:"cpu",kernelFunc:wrt};function og(r){let{inputs:t,backend:e}=r,{x:n}=t;if(n.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(n.dtype==="complex64"){let o=Mo({inputs:{input:n},backend:e}),s=og({inputs:{x:o},backend:e}),i=va({inputs:{input:n},backend:e}),a=og({inputs:{x:i},backend:e}),u=Cr({inputs:{real:s,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),u}else return ng({backend:e,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var NM={kernelName:Yi,backendName:"cpu",kernelFunc:og};function kM(r){let{inputs:t,backend:e}=r,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(n.dtype==="complex64"){let o=Mo({inputs:{input:n},backend:e}),s=kM({inputs:{x:o},backend:e}),i=va({inputs:{input:n},backend:e}),a=og({inputs:{x:i},backend:e}),u=Cr({inputs:{real:s,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),u}else return ng({backend:e,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var TM={kernelName:Gi,backendName:"cpu",kernelFunc:kM};function RT(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n;if(t.length===1)return Sd({inputs:{input:t[0]},backend:e,attrs:{dim:o}});let s=t[0].shape,i=t[0].dtype;t.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(i===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],u=t.map(c=>{let p=Sd({inputs:{input:c},backend:e,attrs:{dim:o}});return a.push(p),p}),l=Yu({inputs:u,backend:e,attrs:{axis:o}});return a.forEach(c=>e.disposeIntermediateTensorInfo(c)),l}var _M={kernelName:Wi,backendName:"cpu",kernelFunc:RT};function Irt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{paddings:s,constantValue:i}=n;tt(o,"pad");let a=s.map((b,w)=>b[0]+o.shape[w]+b[1]),u=s.map(b=>b[0]),l=e.data.get(o.dataId).values,c=y.sizeFromShape(o.shape),p=o.shape.length,m=y.computeStrides(o.shape),f=y.sizeFromShape(a),d=a.length,h=y.computeStrides(a),g=y.getTypedArrayFromDType(o.dtype,f);i!==0&&g.fill(i);for(let b=0;b<c;b++){let I=y.indexToLoc(b,p,m).map((E,A)=>E+u[A]),N=y.locToIndex(I,d,h);g[N]=l[b]}return{dataId:e.write(g,a,o.dtype),shape:a,dtype:o.dtype}}var Ew={kernelName:Ms,backendName:"cpu",kernelFunc:Irt};var Crt=Jt((r,t)=>Math.pow(r,t)),vrt=oe(Ls,Crt),EM={kernelName:Ls,backendName:"cpu",kernelFunc:vrt};function Srt(r){let{inputs:t,backend:e,attrs:n}=r,{paramsNestedSplits:o,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:a}=n,u=o.map(x=>e.data.get(x.dataId).values),l=o.map(x=>x.shape),c=e.data.get(s.dataId).values,p=e.data.get(i.dataId).values,[m,f,d]=xw(u,l,c,s.shape,s.dtype,p,i.shape,a),h=m.map(x=>e.makeTensorInfo([x.length],"int32",x)),g=e.makeTensorInfo(d,s.dtype,f);return h.concat([g])}var AM={kernelName:Kp,backendName:"cpu",kernelFunc:Srt};function Nrt(r){let{inputs:t,backend:e}=r,{starts:n,limits:o,deltas:s}=t,i=e.data.get(n.dataId).values,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,[l,c]=yw(i,n.shape,n.dtype,a,o.shape,u,s.shape),p=e.makeTensorInfo([l.length],"int32",l),m=e.makeTensorInfo([c.length],n.dtype,c);return[p,m]}var DM={kernelName:jp,backendName:"cpu",kernelFunc:Nrt};function krt(r){let{inputs:t,backend:e,attrs:n}=r,{shape:o,values:s,defaultValue:i,rowPartitionTensors:a}=t,{rowPartitionTypes:u}=n,l=e.data.get(o.dataId).values,c=e.data.get(s.dataId).values,p=e.data.get(i.dataId).values,m=a.map(g=>e.data.get(g.dataId).values),f=a.map(g=>g.shape),[d,h]=bw(l,o.shape,c,s.shape,s.dtype,p,i.shape,m,f,u);return e.makeTensorInfo(d,s.dtype,h)}var $M={kernelName:Xp,backendName:"cpu",kernelFunc:krt};function Trt(r){let{backend:t,attrs:e}=r,{start:n,stop:o,dtype:s,step:i}=e,a=up(n,o,i,s);return t.makeTensorInfo([a.length],s,a)}var RM={kernelName:uu,backendName:"cpu",kernelFunc:Trt};var _rt=At(Vs,r=>1/r),FM={kernelName:Vs,backendName:"cpu",kernelFunc:_rt};function Ert(r){let{inputs:t,backend:e,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n;tt(o,"resizeBilinear");let u=y.computeStrides(o.shape),[l,c]=a,[p,m,f,d]=o.shape,h=e.data.get(o.dataId).values,g=new Float32Array(y.sizeFromShape([p,l,c,d])),x=[s&&l>1?m-1:m,s&&c>1?f-1:f],b=[s&&l>1?l-1:l,s&&c>1?c-1:c],w=0,I=x[0]/b[0],N=x[1]/b[1];for(let E=0;E<p;E++)for(let A=0;A<l;A++){let D;i?D=I*(A+.5)-.5:D=I*A;let F=Math.max(0,Math.floor(D)),P=D-F,V=Math.min(m-1,Math.ceil(D)),G=E*u[0]+F*u[1],W=E*u[0]+V*u[1];for(let q=0;q<c;q++){let H;i?H=N*(q+.5)-.5:H=N*q;let K=Math.max(0,Math.floor(H)),X=H-K,Z=Math.min(f-1,Math.ceil(H)),et=G+K*u[2],nt=W+K*u[2],st=G+Z*u[2],at=W+Z*u[2];for(let ot=0;ot<d;ot++){let it=h[et+ot],mt=h[nt+ot],gt=h[st+ot],Ct=h[at+ot],Rt=it+(gt-it)*X,Dt=mt+(Ct-mt)*X,Ht=Rt+(Dt-Rt)*P;g[w++]=Ht}}}return e.makeTensorInfo([p,l,c,d],"float32",g)}var OM={kernelName:Us,backendName:"cpu",kernelFunc:Ert};function Art(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n;tt([s,o],"resizeBilinearGrad");let a=y.computeStrides(o.shape),[u,l,c,p]=o.shape,[,m,f]=s.shape,d=new Float32Array(u*l*c*p),h=[i&&m>1?l-1:l,i&&f>1?c-1:c],g=[i&&m>1?m-1:m,i&&f>1?f-1:f],x=h[0]/g[0],b=h[1]/g[1],w=e.data.get(s.dataId).values,I=0;for(let N=0;N<u;N++){let E=N*a[0];for(let A=0;A<m;A++){let D=A*x,F=Math.floor(D),P=Math.min(Math.ceil(D),l-1),V=E+F*a[1],G=E+P*a[1],W=D-F,q=1-W;for(let H=0;H<f;H++){let K=H*b,X=Math.floor(K),Z=Math.min(Math.ceil(K),c-1),et=K-X,nt=1-et,st=V+X*a[2],at=V+Z*a[2],ot=G+X*a[2],it=G+Z*a[2],mt=q*nt,gt=q*et,Ct=W*nt,Rt=W*et;for(let Dt=0;Dt<p;Dt++){let Ht=w[I++];d[st+Dt]+=Ht*mt,d[at+Dt]+=Ht*gt,d[ot+Dt]+=Ht*Ct,d[it+Dt]+=Ht*Rt}}}}return e.makeTensorInfo([u,c,l,p],"float32",d)}var PM={kernelName:il,backendName:"cpu",kernelFunc:Art};function Drt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n;tt(o,"resizeNearestNeighbor");let u=y.computeStrides(o.shape),[l,c]=a,[p,m,f,d]=o.shape,h=e.data.get(o.dataId).values,g=new Float32Array(p*l*c*d),x=[s&&l>1?m-1:m,s&&c>1?f-1:f],b=[s&&l>1?l-1:l,s&&c>1?c-1:c],w=x[0]/b[0],I=x[1]/b[1],N=0;for(let E=0;E<p;E++){let A=E*u[0];for(let D=0;D<l;D++){let F=i?w*(D+.5):w*D,P=Math.min(m-1,s?Math.round(F):Math.floor(F));i&&(P=Math.max(0,P));let V=A+P*u[1];for(let G=0;G<c;G++){let W=i?I*(G+.5):I*G,q=Math.min(f-1,s?Math.round(W):Math.floor(W));i&&(q=Math.max(0,q));let H=V+q*u[2];for(let K=0;K<d;K++){let X=h[H+K];g[N++]=X}}}}return e.makeTensorInfo([p,l,c,d],o.dtype,g)}var MM={kernelName:Ws,backendName:"cpu",kernelFunc:Drt};function $rt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n;tt([s,o],"resizeNearestNeighborGrad");let a=y.computeStrides(o.shape),u=y.computeStrides(s.shape),[l,c,p,m]=o.shape,[,f,d]=s.shape,h=new Float32Array(l*c*p*m),g=e.data.get(s.dataId).values,x=[i&&f>1?c-1:c,i&&d>1?p-1:p],b=[i&&f>1?f-1:f,i&&d>1?d-1:d],w=x[0]/b[0],I=x[1]/b[1],N=1/w,E=1/I,A=Math.ceil(N)*2+2,D=Math.ceil(E)*2+2;for(let F=0;F<l;F++){let P=F*a[0];for(let V=0;V<c;V++){let G=P+V*a[1],W=Math.floor(V*N),q=Math.floor(W-A/2);for(let H=0;H<p;H++){let K=G+H*a[2],X=Math.floor(H*E),Z=Math.floor(X-D/2);for(let et=0;et<m;et++){let nt=0;for(let st=0;st<A;st++){let at=st+q;if(at<0||at>=f)continue;let ot=P+at*u[1],it=at*w,mt=Math.min(c-1,i?Math.round(it):Math.floor(it));if(V===mt)for(let gt=0;gt<D;gt++){let Ct=gt+Z;if(Ct<0||Ct>=d)continue;let Rt=ot+Ct*u[2],Dt=Ct*I,Ht=Math.min(p-1,i?Math.round(Dt):Math.floor(Dt));H===Ht&&(nt+=g[Rt+et])}}h[K+et]=nt}}}}return e.makeTensorInfo(o.shape,o.dtype,h)}var LM={kernelName:sl,backendName:"cpu",kernelFunc:$rt};function Rrt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dims:s}=n;tt(o,"reverse");let i=o.shape.length,a=y.parseAxisParam(s,o.shape);if(i===0)return Zr({inputs:{x:o},backend:e});let u=new le(o.shape,o.dtype),l=e.bufferSync(o);for(let c=0;c<u.size;c++){let p=u.indexToLoc(c),m=p.slice();a.forEach(f=>m[f]=o.shape[f]-1-m[f]),u.set(l.get(...m),...p)}return e.makeTensorInfo(u.shape,u.dtype,u.values)}var zM={kernelName:qs,backendName:"cpu",kernelFunc:Rrt};var BM={kernelName:hl,backendName:"cpu",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{image:n}=r,{radians:o,fillValue:s,center:i}=t,a=e,u=y.getTypedArrayFromDType(n.dtype,y.sizeFromShape(n.shape)),[l,c,p,m]=n.shape,[f,d]=S.getImageCenter(i,c,p),h=255,g=Math.sin(o),x=Math.cos(o),b=a.data.get(n.dataId).values;for(let I=0;I<l;I++){let N=I*p*c*m;for(let E=0;E<c;E++){let A=E*(p*m);for(let D=0;D<p;D++){let F=D*m;for(let P=0;P<m;P++){let V=[l,E,D,P],G=V[2],W=V[1],q=(G-f)*x-(W-d)*g,H=(G-f)*g+(W-d)*x;q=Math.round(q+f),H=Math.round(H+d);let K=s;if(typeof s!="number"&&(P===3?K=h:K=s[P]),q>=0&&q<p&&H>=0&&H<c){let Z=H*(p*m),et=q*m,nt=N+Z+et+P;K=b[nt]}let X=N+A+F+P;u[X]=K}}}}return{dataId:a.write(u,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var Frt=At(Ks,r=>{let t=Math.floor(r);return r-t<.5?Math.floor(r):r-t>.5?Math.ceil(r):t%2===0?t:t+1}),VM={kernelName:Ks,backendName:"cpu",kernelFunc:Frt};function Ort(r){let{inputs:t,backend:e,attrs:n}=r,{indices:o,updates:s}=t,{shape:i}=n,{sliceRank:a,numUpdates:u,sliceSize:l,strides:c,outputSize:p}=S.calculateShapes(s,o,i),m=!0,f=e.bufferSync(o),d=e.bufferSync(s),h=Si(f,d,i,p,l,u,a,c,0,m);return e.makeTensorInfo(i,h.dtype,h.values)}var GM={kernelName:al,backendName:"cpu",kernelFunc:Ort};function Prt(r,t){let e=0,n=r.length,o=0;for(;e<n;)o=Math.floor((e+n)/2),r[o]<t?e=o+1:n=o;return n}function Mrt(r,t){let e=0,n=r.length,o=0;for(;e<n;)o=Math.floor((e+n)/2),r[o]<=t?e=o+1:n=o;return n}function WM(r,t,e,n,o,s){let i=y.getArrayFromDType("int32",e*o);for(let a=0;a<e;++a){let u=r.slice(a*n,(a+1)*n),l=a*o;for(let c=0;c<o;++c)i[l+c]=s==="left"?Prt(u,t[c+l]):Mrt(u,t[c+l])}return i}function Lrt(r){let{inputs:t,backend:e,attrs:n}=r,{sortedSequence:o,values:s}=t,{side:i}=n,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,l=WM(a,u,o.shape[0],o.shape[1],s.shape[1],i);return e.makeTensorInfo(s.shape,"int32",l)}var UM={kernelName:ul,backendName:"cpu",kernelFunc:Lrt};function zrt(r){let{inputs:t,backend:e}=r,{condition:n,t:o,e:s}=t;tt([n,o,s],"select");let i=n.shape.length,a=e.data.get(n.dataId).values,u=e.data.get(o.dataId).values,l=e.data.get(s.dataId).values,c=ur(o.dtype,s.dtype),p=y.makeZerosTypedArray(y.sizeFromShape(o.shape),c),m=0,f=i===0||i>1||o.shape.length===1?1:y.sizeFromShape(o.shape.slice(1));for(let d=0;d<a.length;d++)for(let h=0;h<f;h++)a[d]===1?p[m++]=u[d]:p[m++]=l[d];return e.makeTensorInfo(o.shape,c,p)}var HM={kernelName:Hi,backendName:"cpu",kernelFunc:zrt};var Brt=S.SELU_SCALEALPHA,Vrt=S.SELU_SCALE,Grt=At(Xs,r=>r>=0?Vrt*r:Brt*(Math.exp(r)-1)),qM={kernelName:Xs,backendName:"cpu",kernelFunc:Grt};var Wrt=At(Js,r=>r<0?-1:r>0?1:0),KM={kernelName:Js,backendName:"cpu",kernelFunc:Wrt};var Urt=At(Ys,r=>Math.sin(r)),jM={kernelName:Ys,backendName:"cpu",kernelFunc:Urt};var Hrt=At(Zs,r=>Math.sinh(r)),XM={kernelName:Zs,backendName:"cpu",kernelFunc:Hrt};var qrt=11920928955078125e-23,YM=Math.log(qrt)+2,Krt=At(ti,r=>{let t=r>-YM,e=r<YM,n=Math.exp(r),o;return e?o=n:t?o=r:o=Math.log(1+n),o}),ZM={kernelName:ti,backendName:"cpu",kernelFunc:Krt};function jrt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,paddings:i}=n;tt([o],"spaceToBatchND");let a=y.sizeFromShape(s),u=[[0,0]];u.push(...i);for(let E=1+s.length;E<o.shape.length;++E)u.push([0,0]);let l=Ew.kernelFunc({inputs:{x:o},backend:e,attrs:{paddings:u,constantValue:0}}),c=S.getReshaped(l.shape,s,a,!1),p=S.getPermuted(c.length,s.length,!1),m=S.getReshapedPermuted(l.shape,s,a,!1),h=Qt({inputs:{x:l},backend:e,attrs:{shape:c}}),b=Ge({inputs:{x:h},backend:e,attrs:{perm:p}}),N=Qt({inputs:{x:b},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(b),N}var JM={kernelName:Ki,backendName:"cpu",kernelFunc:jrt};function Xrt(r){let{inputs:t,backend:e}=r,{indices:n,values:o,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
| ${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
| ${n.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
| ${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
| ${i.shape}`);let a=e.data.get(n.dataId).values,u=e.data.get(o.dataId).values,l=e.data.get(s.dataId).values,c=e.data.get(i.dataId).values[0],[p,m,f,d,h]=ww(a,n.shape,n.dtype,u,o.dtype,l,c);return[e.makeTensorInfo(m,n.dtype,p),e.makeTensorInfo([m[0]],o.dtype,f),e.makeTensorInfo([d.length],"bool",new Uint8Array(d.map(g=>Number(g)))),e.makeTensorInfo([h.length],n.dtype,new Int32Array(h))]}var QM={kernelName:cu,backendName:"cpu",kernelFunc:Xrt};function Yrt(r){let{inputs:t,backend:e}=r,{inputIndices:n,inputShape:o,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
| ${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
| ${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(e.data.get(o.dataId).values),a=e.data.get(n.dataId).values,u=Array.from(e.data.get(s.dataId).values),[l,c,p]=Iw(a,n.shape,n.dtype,i,u);return[e.makeTensorInfo(c,n.dtype,l),e.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var tL={kernelName:cl,backendName:"cpu",kernelFunc:Yrt};function Zrt(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
| ${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
| ${s.shape}`);if(o.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=e.data.get(n.dataId).values,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,[l,c]=Cd(i,n.shape,n.dtype,a,u,!0);return e.makeTensorInfo(c,n.dtype,l)}var eL={kernelName:pu,backendName:"cpu",kernelFunc:Zrt};function Jrt(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
| ${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
| ${s.shape}`);if(o.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=e.data.get(n.dataId).values,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,[l,c]=Cd(i,n.shape,n.dtype,a,u);return e.makeTensorInfo(c,n.dtype,l)}var rL={kernelName:mu,backendName:"cpu",kernelFunc:Jrt};function Qrt(r){let{inputs:t,backend:e,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=t,{outputShape:a}=n,{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:m}=S.calculateShapes(s,o,a),f=!1,d=e.bufferSync(o),h;switch(s.dtype){case"bool":{let g=e.bufferSync(s),x=!!e.data.get(i.dataId).values[0];h=Si(d,g,a,m,c,l,u,p,x,f);break}case"float32":{let g=e.bufferSync(s),x=e.data.get(i.dataId).values[0];h=Si(d,g,a,m,c,l,u,p,x,f);break}case"int32":{let g=e.bufferSync(s),x=e.data.get(i.dataId).values[0];h=Si(d,g,a,m,c,l,u,p,x,f);break}case"string":{let g=e.bufferSync(s),x=y.decodeString(e.data.get(i.dataId).values[0]);h=Si(d,g,a,m,c,l,u,p,x,f);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return e.makeTensorInfo(a,h.dtype,h.values)}var nL={kernelName:pl,backendName:"cpu",kernelFunc:Qrt};function tnt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{numOrSizeSplits:s,axis:i}=n,a=y.parseAxisParam(i,o.shape)[0],u=S.prepareSplitSize(o,s,a),l=new Array(o.shape.length).fill(0),c=o.shape.slice();return u.map(p=>{let m=[...c];m[a]=p;let f=Bo({inputs:{x:o},backend:e,attrs:{begin:l,size:m}});return l[a]+=p,f})}var oL={kernelName:ji,backendName:"cpu",kernelFunc:tnt};var sL={kernelName:fu,backendName:"cpu",kernelFunc:({inputs:r,backend:t})=>{let{x:e}=r,n=t;tt(e,"square");let o=n.data.get(e.dataId).values,s=new Float32Array(o.length);for(let a=0;a<o.length;++a){let u=o[a];s[a]=u*u}return{dataId:n.write(s,e.shape,e.dtype),shape:e.shape,dtype:e.dtype}}};var ent=At(wo,(r,t)=>{let e=t;return isNaN(r)?NaN:r>0?1:e.alpha}),iL={kernelName:wo,backendName:"cpu",kernelFunc:ent};function rnt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,end:i,strides:a,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n;tt(o,"stridedSlice");let{finalShapeSparse:f,finalShape:d,isIdentity:h,sliceDim0:g,isSimpleSlice:x,begin:b,end:w,strides:I}=ze.sliceInfo(o.shape,s,i,a,u,l,c,p,m),N;if(h)N=Qt({inputs:{x:o},backend:e,attrs:{shape:d}});else if(g||x){y.assert(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);let E=ze.computeOutShape(b,w,I),A=Bo({inputs:{x:o},backend:e,attrs:{begin:b,size:E}});N=Qt({inputs:{x:A},backend:e,attrs:{shape:d}}),e.disposeIntermediateTensorInfo(A)}else{let E=e.bufferSync(o),A=Cw(f,E,I,b);N=e.makeTensorInfo(d,A.dtype,A.values)}return N}var aL={kernelName:ml,backendName:"cpu",kernelFunc:rnt};function nnt(r){let{inputs:t,backend:e,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:i,rightPad:a,padWidth:u,preserveShortSequences:l}=n,{data:c,dataSplits:p}=t,m=e.data.get(c.dataId).values,f=e.data.get(p.dataId).values,[d,h]=pp(m,f,o,s,i,a,u,l);return[e.makeTensorInfo([d.length],"string",d),e.makeTensorInfo(p.shape,"int32",h)]}var lL={kernelName:du,backendName:"cpu",kernelFunc:nnt};function ont(r){let{inputs:t,backend:e,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let a=e.data.get(s.dataId).values,u=e.data.get(i.dataId).values[0],[l,c,p]=mp(a,u,o),m=c.length;return[e.makeTensorInfo([m,2],"int32",l),e.makeTensorInfo([m],"string",c),e.makeTensorInfo([2],"int32",new Int32Array(p))]}var uL={kernelName:hu,backendName:"cpu",kernelFunc:ont};function snt(r){let{inputs:t,backend:e,attrs:n}=r,{numBuckets:o}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");let i=e.data.get(s.dataId).values,a=fp(i,o);return e.makeTensorInfo(s.shape,"int32",a)}var cL={kernelName:gu,backendName:"cpu",kernelFunc:snt};var int=At(ii,r=>Math.tan(r)),pL={kernelName:ii,backendName:"cpu",kernelFunc:int};var ant=At(ai,r=>Math.tanh(r)),mL={kernelName:ai,backendName:"cpu",kernelFunc:ant};function lnt(r){let{inputs:t,backend:e}=r,{tensor:n,indices:o,updates:s}=t,{sliceRank:i,numUpdates:a,sliceSize:u,strides:l,outputSize:c}=S.calculateShapes(s,o,n.shape),p=!1,m=e.bufferSync(o),f=e.bufferSync(s),d=e.bufferSync(n),h=Si(m,f,n.shape,c,u,a,i,l,d,p);return e.makeTensorInfo(n.shape,h.dtype,h.values)}var fL={kernelName:ll,backendName:"cpu",kernelFunc:lnt};function unt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reps:s}=n;tt(o,"tile");let i=vw(e.bufferSync(o),s);return e.makeTensorInfo(i.shape,i.dtype,i.values)}var dL={kernelName:lo,backendName:"cpu",kernelFunc:unt};function cnt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{k:s,sorted:i}=n;tt(o,"topk");let a=e.data.get(o.dataId).values,[u,l]=Sw(a,o.shape,o.dtype,s,i);return[e.makeTensorInfo(u.shape,u.dtype,u.values),e.makeTensorInfo(l.shape,l.dtype,l.values)]}var hL={kernelName:fl,backendName:"cpu",kernelFunc:cnt};function pnt(r){let{inputs:t,attrs:e,backend:n}=r,{image:o,transforms:s}=t,{interpolation:i,fillMode:a,fillValue:u,outputShape:l}=e,[c,p,m,f]=o.shape,[d,h]=l!=null?l:[p,m],g=[c,d,h,f],x=y.computeStrides(o.shape),b=x[0],w=x[1],I=x[2],N=y.computeStrides(g),E=N[0],A=N[1],D=N[2],F=y.getTypedArrayFromDType(o.dtype,y.sizeFromShape(g));F.fill(u);let P=n.data.get(o.dataId).values,V=n.data.get(s.dataId).values;for(let W=0;W<c;++W){let q=s.shape[0]===1?V:V.subarray(W*8,W*8+8);for(let H=0;H<d;++H)for(let K=0;K<h;++K)for(let X=0;X<f;++X){let Z,et=q[6]*K+q[7]*H+1;if(et===0)continue;let nt=(q[0]*K+q[1]*H+q[2])/et,st=(q[3]*K+q[4]*H+q[5])/et,at=gL(nt,m,a),ot=gL(st,p,a);switch(i){case"nearest":Z=gnt(P,p,m,b,w,I,W,ot,at,X,u);break;case"bilinear":Z=xnt(P,p,m,b,w,I,W,ot,at,X,u);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let it=W*E+H*A+K*D+X;F[it]=Z}return n.makeTensorInfo(g,o.dtype,F)}return{dataId:n.write(F,g,o.dtype),shape:o.shape,dtype:o.dtype}}var xL={kernelName:dl,backendName:"cpu",kernelFunc:pnt};function gL(r,t,e){switch(e){case"reflect":return mnt(r,t);case"wrap":return fnt(r,t);case"nearest":return hnt(r,t);case"constant":default:return dnt(r,t)}}function mnt(r,t){let e=r;if(e<0)if(t<=1)e=0;else{let n=2*t;e<n&&(e=n*Math.trunc(-e/n)+e),e=e<-t?e+n:-e-1}else if(e>t-1)if(t<=1)e=0;else{let n=2*t;e-=n*Math.trunc(e/n),e>=t&&(e=n-e-1)}return y.clamp(0,e,t-1)}function fnt(r,t){let e=r;if(e<0)if(t<=1)e=0;else{let n=t-1;e+=t*(Math.trunc(-e/n)+1)}else if(e>t-1)if(t<=1)e=0;else{let n=t-1;e-=t*Math.trunc(e/n)}return y.clamp(0,e,t-1)}function dnt(r,t){return r}function hnt(r,t){return y.clamp(0,r,t-1)}function sg(r,t,e,n,o,s,i,a,u,l,c){let p=i*n+a*o+u*s+l;return 0<=a&&a<t&&0<=u&&u<e?r[p]:c}function gnt(r,t,e,n,o,s,i,a,u,l,c){let p=Math.round(a),m=Math.round(u);return sg(r,t,e,n,o,s,i,p,m,l,c)}function xnt(r,t,e,n,o,s,i,a,u,l,c){let p=Math.floor(a),m=Math.floor(u),f=p+1,d=m+1,h=(d-u)*sg(r,t,e,n,o,s,i,p,m,l,c)+(u-m)*sg(r,t,e,n,o,s,i,p,d,l,c),g=(d-u)*sg(r,t,e,n,o,s,i,f,m,l,c)+(u-m)*sg(r,t,e,n,o,s,i,f,d,l,c);return(f-a)*h+(a-p)*g}function ynt(r){let{inputs:t,attrs:e,backend:n}=r,{axis:o}=e,{x:s}=t;tt(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:a,outputShape:u,indices:l}=dp(i,o,s.shape,s.dtype);return[n.makeTensorInfo(u,s.dtype,a),n.makeTensorInfo([l.length],"int32",l)]}var yL={kernelName:xu,backendName:"cpu",kernelFunc:ynt};function bnt(r){let{inputs:t,backend:e,attrs:n}=r,{value:o}=t,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o.shape.length,a=o.shape[s],u=new Array(i-1),l=0;for(let f=0;f<i;f++)f!==s&&(u[l++]=o.shape[f]);let c=new Array(i).fill(0),p=o.shape.slice();p[s]=1;let m=new Array(a);for(let f=0;f<m.length;f++){c[s]=f;let d=Bo({inputs:{x:o},backend:e,attrs:{begin:c,size:p}});m[f]=Qt({inputs:{x:d},backend:e,attrs:{shape:u}}),e.disposeIntermediateTensorInfo(d)}return m}var bL={kernelName:Xi,backendName:"cpu",kernelFunc:bnt};function wnt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,segmentIds:s}=t,{numSegments:i}=n;tt(o,"unsortedSegmentSum");let a=o.shape.length,u=s.shape.length,l=[],c=[],p=a-u,m=s;for(let d=0;d<p;++d){let h=Sd({inputs:{input:m},backend:e,attrs:{dim:d+1}});m=h,c.push(h)}for(let d=0;d<i;++d){let h=y.createScalarValue(d,"int32"),g=e.makeTensorInfo([],"int32",h),x=tT({inputs:{a:g,b:m},backend:e}),b=Lo({inputs:{x},backend:e,attrs:{dtype:"float32"}}),w=lp({inputs:{a:b,b:o},backend:e}),I=zl({inputs:{x:w},backend:e,attrs:{axis:0,keepDims:!1}});l.push(I),c.push(g),c.push(x),c.push(b),c.push(w),c.push(I)}let f=RT({inputs:l,backend:e,attrs:{axis:0}});return c.forEach(d=>e.disposeIntermediateTensorInfo(d)),f}var wL={kernelName:yu,backendName:"cpu",kernelFunc:wnt};var Int=[HO,JF,qO,KO,nO,jO,XO,YO,ZO,JO,QO,tP,eP,rP,nP,sP,iP,aP,lP,UO,uP,cP,pP,oO,mP,rO,sO,fP,QF,dP,gP,xP,yP,bP,wP,IP,CP,vP,SP,NP,kP,TP,_P,EP,AP,DP,$P,RP,FP,OP,PP,MP,zP,LO,BP,iO,VP,aO,GP,lO,WP,UP,HP,uO,cO,qP,KP,jP,XP,pO,mO,tO,YP,hP,ZP,JP,QP,zO,fO,dO,tM,hO,eM,rM,nM,oM,sM,iM,aM,gO,lM,uM,cM,pM,fM,dM,hM,xO,gM,xM,wM,yO,bO,IM,CM,vM,wO,SM,TM,_M,Ew,EM,BO,CO,AM,DM,$M,RM,eO,rg,FM,VO,GO,WO,OM,PM,MM,LM,zM,BM,VM,TO,GM,UM,HM,qM,EO,KM,jM,XM,AO,yM,ZM,JM,QM,tL,eL,rL,nL,oL,$O,sL,RO,FO,iL,aL,lL,uL,cL,OO,LP,pL,mL,fL,dL,hL,xL,IO,yL,bL,wL,NM];for(let r of Int)pc(r);var _d={};Kt(_d,{assertNotComplex:()=>Ni,bindCanvasToFramebuffer:()=>Ant,bindColorTextureToFramebuffer:()=>ug,bindTextureToProgramUniformSampler:()=>XT,bindTextureUnit:()=>SL,bindVertexBufferToProgramAttribute:()=>Ow,callAndCheck:()=>ht,canBeRepresented:()=>MT,createFragmentShader:()=>zT,createFramebuffer:()=>qT,createProgram:()=>BT,createStaticIndexBuffer:()=>WT,createStaticVertexBuffer:()=>GT,createTexture:()=>UT,createVertexShader:()=>LT,getBatchDim:()=>Vl,getExtensionOrThrow:()=>Nd,getFramebufferErrorMessage:()=>NL,getMaxTexturesInShader:()=>JT,getNumChannels:()=>_nt,getProgramUniformLocation:()=>jT,getProgramUniformLocationOrThrow:()=>KT,getRowsCols:()=>Gl,getShapeAs3D:()=>Td,getTextureShapeFromLogicalShape:()=>YT,getWebGLDisjointQueryTimerVersion:()=>QT,getWebGLErrorMessage:()=>vL,getWebGLMaxTextureSize:()=>ZT,hasExtension:()=>Zn,isCapableOfRenderingToFloatTexture:()=>t1,isDownloadFloatTextureEnabled:()=>e1,isReshapeFree:()=>Ju,isWebGLFenceEnabled:()=>r1,isWebGLVersionEnabled:()=>Mw,linkProgram:()=>VT,logShaderSourceAndInfoLog:()=>Fw,resetMaxTextureSize:()=>Dnt,resetMaxTexturesInShader:()=>$nt,unbindColorTextureFromFramebuffer:()=>Pw,unbindTextureUnit:()=>Ent,validateFramebuffer:()=>kd,validateProgram:()=>lg,validateTextureSize:()=>HT});var gp={},Aw={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function FT(r,t){gp[r]=t}function Yn(r,t){if(!(r in gp)||t!=null){let n=vnt(r,t);if(n!==null)gp[r]=n;else return console.log("Could not get context for WebGL version",r),null}let e=gp[r];return e==null||e.isContextLost()?(delete gp[r],Yn(r)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),gp[r])}function Cnt(r){if(!L().getBool("IS_SAFARI")&&typeof OffscreenCanvas!="undefined"&&r===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function vnt(r,t){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=t==null?Cnt(r):t;return e.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete gp[r]},!1),L().getBool("SOFTWARE_WEBGL_ENABLED")&&(Aw.failIfMajorPerformanceCaveat=!1),r===1?e.getContext("webgl",Aw)||e.getContext("experimental-webgl",Aw):e.getContext("webgl2",Aw)}var Zu;(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(Zu||(Zu={}));var Jr;(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(Jr||(Jr={}));var zr;(function(r){r[r.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",r[r.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",r[r.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",r[r.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",r[r.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(zr||(zr={}));function xp(r,t){return[t,r]}function IL(r,t){return r*t}function ig(r){let t=y.sizeFromShape(r),e=Math.ceil(t/4);return y.sizeToSquarishShape(e)}function Sa(r,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(r/2))]}function CL(r,t){let[e,n]=Sa(r,t);return e*n*4}function ag(r,t){let e=r,n,o,s,i,a,u,l,c,p,m;return L().getNumber("WEBGL_VERSION")===2?(n=e.R32F,o=e.R16F,s=e.RGBA16F,i=e.RGBA32F,a=e.RED,l=4,c=1,p=e.HALF_FLOAT,m=e.FLOAT,u=e.RGBA8):(n=r.RGBA,o=r.RGBA,s=r.RGBA,i=e.RGBA,a=r.RGBA,l=4,c=4,p=t!=null?t.HALF_FLOAT_OES:null,m=r.FLOAT,u=r.RGBA),{internalFormatFloat:n,internalFormatHalfFloat:o,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:a,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:m}}function ht(r,t){let e=t();return L().getBool("DEBUG")&&Snt(r),e}function Snt(r){let t=r.getError();if(t!==r.NO_ERROR)throw new Error("WebGL Error: "+vL(r,t))}var Nnt=596e-10,knt=65504;function MT(r){return!!(L().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||Nnt<Math.abs(r)&&Math.abs(r)<knt)}function vL(r,t){switch(t){case r.NO_ERROR:return"NO_ERROR";case r.INVALID_ENUM:return"INVALID_ENUM";case r.INVALID_VALUE:return"INVALID_VALUE";case r.INVALID_OPERATION:return"INVALID_OPERATION";case r.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case r.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case r.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function Nd(r,t){return Bl(r,()=>r.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function LT(r,t){let e=Bl(r,()=>r.createShader(r.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(ht(r,()=>r.shaderSource(e,t)),ht(r,()=>r.compileShader(e)),r.getShaderParameter(e,r.COMPILE_STATUS)===!1)throw console.log(r.getShaderInfoLog(e)),new Error("Failed to compile vertex shader.");return e}function zT(r,t){let e=Bl(r,()=>r.createShader(r.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(ht(r,()=>r.shaderSource(e,t)),ht(r,()=>r.compileShader(e)),L().get("ENGINE_COMPILE_ONLY"))return e;if(r.getShaderParameter(e,r.COMPILE_STATUS)===!1)throw Fw(t,r.getShaderInfoLog(e)),new Error("Failed to compile fragment shader.");return e}var Tnt=/ERROR: [0-9]+:([0-9]+):/g;function Fw(r,t){let e=Tnt.exec(t);if(e==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(r);return}let n=+e[1],o=r.split(`
| `),s=o.length.toString().length+2,i=o.map((p,m)=>y.rightPad((m+1).toString(),s)+p),a=0;for(let p=0;p<i.length;p++)a=Math.max(i[p].length,a);let u=i.slice(0,n-1),l=i.slice(n-1,n),c=i.slice(n);console.log(u.join(`
| `)),console.log(t.split(`
| `)[0]),console.log(`%c ${y.rightPad(l[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
| `))}function BT(r){return Bl(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function VT(r,t){if(ht(r,()=>r.linkProgram(t)),!L().get("ENGINE_COMPILE_ONLY")&&r.getProgramParameter(t,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function lg(r,t){if(ht(r,()=>r.validateProgram(t)),r.getProgramParameter(t,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function GT(r,t){let e=Bl(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return ht(r,()=>r.bindBuffer(r.ARRAY_BUFFER,e)),ht(r,()=>r.bufferData(r.ARRAY_BUFFER,t,r.STATIC_DRAW)),e}function WT(r,t){let e=Bl(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return ht(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e)),ht(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,t,r.STATIC_DRAW)),e}function _nt(){return L().getNumber("WEBGL_VERSION")===2?1:4}function UT(r){return Bl(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function HT(r,t){let e=L().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||t<=0){let n=`[${r}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(r>e||t>e){let n=`[${r}x${t}]`,o=`[${e}x${e}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+o+".")}}function qT(r){return Bl(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Ow(r,t,e,n,o,s,i){let a=r.getAttribLocation(t,e);return a===-1?!1:(ht(r,()=>r.bindBuffer(r.ARRAY_BUFFER,n)),ht(r,()=>r.vertexAttribPointer(a,o,r.FLOAT,!1,s,i)),ht(r,()=>r.enableVertexAttribArray(a)),!0)}function SL(r,t,e){kL(r,e),ht(r,()=>r.activeTexture(r.TEXTURE0+e)),ht(r,()=>r.bindTexture(r.TEXTURE_2D,t))}function Ent(r,t){kL(r,t),ht(r,()=>r.activeTexture(r.TEXTURE0+t)),ht(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function KT(r,t,e){return Bl(r,()=>r.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}function jT(r,t,e){return r.getUniformLocation(t,e)}function XT(r,t,e,n){ht(r,()=>SL(r,t,n)),ht(r,()=>r.uniform1i(e,n))}function Ant(r){ht(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,null)),ht(r,()=>r.viewport(0,0,r.canvas.width,r.canvas.height)),ht(r,()=>r.scissor(0,0,r.canvas.width,r.canvas.height))}function ug(r,t,e){ht(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),ht(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t,0))}function Pw(r,t){ht(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),ht(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function kd(r){let t=r.checkFramebufferStatus(r.FRAMEBUFFER);if(t!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+NL(r,t))}function NL(r,t){switch(t){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function Bl(r,t,e){let n=ht(r,()=>t());if(n==null)throw new Error(e);return n}function kL(r,t){let e=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+r.TEXTURE0;if(n<r.TEXTURE0||n>e){let o=`[gl.TEXTURE0, gl.TEXTURE${e}]`;throw new Error(`textureUnit must be in ${o}.`)}}function Vl(r,t=2){return y.sizeFromShape(r.slice(0,r.length-t))}function Gl(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function Td(r){let t=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(t=[Vl(r),...Gl(r)]),t}function YT(r,t=!1){let e=L().getNumber("WEBGL_MAX_TEXTURE_SIZE"),n=L().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");n===1/0&&L().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(n=e/2),t&&(e=e*2,n=n*2,r=r.map((a,u)=>u>=r.length-2?y.nearestLargerEven(r[u]):r[u]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=y.squeezeShape(r).newShape);let o=y.sizeFromShape(r),s=null;r.length<=1&&o<=e?s=[1,o]:r.length===2&&r[0]<=e&&r[1]<=e?s=r:r.length===3&&r[0]*r[1]<=e&&r[2]<=e?s=[r[0]*r[1],r[2]]:r.length===3&&r[0]<=e&&r[1]*r[2]<=e?s=[r[0],r[1]*r[2]]:r.length===4&&r[0]*r[1]*r[2]<=e&&r[3]<=e?s=[r[0]*r[1]*r[2],r[3]]:r.length===4&&r[0]<=e&&r[1]*r[2]*r[3]<=e&&(s=[r[0],r[1]*r[2]*r[3]]);let i=s!=null&&Math.max(...s)>n&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(s==null||i)if(t){let a=Vl(r),u=2,l=2;r.length&&([u,l]=Gl(r)),o=a*(u/2)*(l/2),s=y.sizeToSquarishShape(o).map(c=>c*2)}else s=y.sizeToSquarishShape(o);return s}function Dw(r){return r%2===0}function Ju(r,t){if(r=r.slice(-2),t=t.slice(-2),y.arraysEqual(r,t)||!r.length||!t.length||r[0]===0||r[1]===0||t[0]===0||t[1]===0)return!0;if(r.length!==t.length){let e=r[r.length-1],n=t[t.length-1];if(e===n||Dw(e)&&Dw(n)&&(r[0]===1||t[0]===1))return!0}return r[1]===t[1]&&Dw(r[0])&&Dw(t[0])}var $w,Rw;function ZT(r){if($w==null){let t=Yn(r);$w=t.getParameter(t.MAX_TEXTURE_SIZE)}return $w}function Dnt(){$w=null}function $nt(){Rw=null}function JT(r){if(Rw==null){let t=Yn(r);Rw=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Rw)}function QT(r){if(r===0)return 0;let t,e=Yn(r);return Zn(e,"EXT_disjoint_timer_query_webgl2")&&r===2?t=2:Zn(e,"EXT_disjoint_timer_query")?t=1:t=0,t}function Zn(r,t){return r.getExtension(t)!=null}function Mw(r){try{if(Yn(r)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function t1(r){if(r===0)return!1;let t=Yn(r);if(r===1){if(!Zn(t,"OES_texture_float"))return!1}else if(!Zn(t,"EXT_color_buffer_float"))return!1;return PT(t)}function e1(r){if(r===0)return!1;let t=Yn(r);if(r===1){if(!Zn(t,"OES_texture_float")||!Zn(t,"WEBGL_color_buffer_float"))return!1}else{if(Zn(t,"EXT_color_buffer_float"))return PT(t);let n="EXT_color_buffer_half_float";if(Zn(t,n)){let o=t.getExtension(n);return Rnt(t,o)}return!1}return PT(t)}function PT(r){let t=ag(r),e=r.createTexture();r.bindTexture(r.TEXTURE_2D,e);let n=1,o=1;r.texImage2D(r.TEXTURE_2D,0,t.internalFormatFloat,n,o,0,t.textureFormatFloat,t.textureTypeFloat,null);let s=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,s),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0);let i=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(e),r.deleteFramebuffer(s),i}function Rnt(r,t){let e=ag(r,t),n=r.createTexture();r.bindTexture(r.TEXTURE_2D,n);let o=1,s=1;r.texImage2D(r.TEXTURE_2D,0,e.internalFormatHalfFloat,o,s,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);let i=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,n,0);let a=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(n),r.deleteFramebuffer(i),a}function r1(r){return r!==2?!1:Yn(r).fenceSync!=null}function Ni(r,t){Array.isArray(r)||(r=[r]),r.forEach(e=>{e!=null&&y.assert(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var Et=L();Et.registerFlag("HAS_WEBGL",()=>Et.getNumber("WEBGL_VERSION")>0);Et.registerFlag("WEBGL_VERSION",()=>Mw(2)?2:Mw(1)?1:0);Et.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Et.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Et.get("WEBGL_VERSION")===2);Et.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Et.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Et.registerFlag("WEBGL_PACK",()=>Et.getBool("HAS_WEBGL"));Et.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_CLIP",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_PACK_REDUCE",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_LAZILY_UNPACK",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_CONV_IM2COL",()=>Et.getBool("WEBGL_PACK"));Et.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>ZT(Et.getNumber("WEBGL_VERSION")));Et.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>JT(Et.getNumber("WEBGL_VERSION")));Et.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=Et.getNumber("WEBGL_VERSION");return r===0?0:QT(r)});Et.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Et.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Cu.isMobile());Et.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>t1(Et.getNumber("WEBGL_VERSION")));Et.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Et.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Et.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Et.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>e1(Et.getNumber("WEBGL_VERSION")));Et.registerFlag("WEBGL_FENCE_API_ENABLED",()=>r1(Et.getNumber("WEBGL_VERSION")));Et.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Et.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Et.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,r=>{if(r<0&&r!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${r}.`)});Et.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Cu.isMobile()?1:-1,r=>{if(r<0&&r!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${r}.`)});Et.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Et.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Et.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Et.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);Et.registerFlag("WEBGL_EXP_CONV",()=>!1);Et.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>Et.getBool("IS_TEST"));Et.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);Et.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);Et.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);Et.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function We(){let r,t,e,n,o,s,i,a,u,l;return L().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",t="in",e="out",n="in",o="texture",s="outputColor",i="out vec4 outputColor;",a=L().getBool("WEBGL2_ISNAN_CUSTOM")?`
| bool isnan_custom(float val) {
| uint floatToUint = floatBitsToUint(val);
| return (floatToUint & 0x7fffffffu) > 0x7f800000u;
| }
|
| bvec4 isnan_custom(vec4 val) {
| return bvec4(isnan_custom(val.x),
| isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
| }
|
| #define isnan(value) isnan_custom(value)
| `:"",u="",l=`
| #define round(value) newRound(value)
| int newRound(float value) {
| return int(floor(value + 0.5));
| }
|
| ivec4 newRound(vec4 value) {
| return ivec4(floor(value + vec4(0.5)));
| }
| `):(r="",t="attribute",e="varying",n="varying",o="texture2D",s="gl_FragColor",i="",a=`
| #define isnan(value) isnan_custom(value)
| bool isnan_custom(float val) {
| return (val > 0. || val < 1. || val == 0.) ? false : true;
| }
| bvec4 isnan_custom(vec4 val) {
| return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
| }
| `,u=`
| uniform float INFINITY;
|
| bool isinf(float val) {
| return abs(val) == INFINITY;
| }
| bvec4 isinf(vec4 val) {
| return equal(abs(val), vec4(INFINITY));
| }
| `,l=`
| int round(float value) {
| return int(floor(value + 0.5));
| }
|
| ivec4 round(vec4 value) {
| return ivec4(floor(value + vec4(0.5)));
| }
| `),{version:r,attribute:t,varyingVs:e,varyingFs:n,texture2D:o,output:s,defineOutput:i,defineSpecialNaN:a,defineSpecialInf:u,defineRound:l}}function ki(r,t,e="index"){let n=y.computeStrides(t);return n.map((o,s)=>{let i=`int ${r[s]} = ${e} / ${o}`,a=s===n.length-1?`int ${r[s+1]} = ${e} - ${r[s]} * ${o}`:`index -= ${r[s]} * ${o}`;return`${i}; ${a};`}).join("")}function yp(r,t,e="index"){let n=y.computeStrides(t);return n.map((o,s)=>{let i=`int ${r[s]} = ${e} / outShapeStrides[${s}]`,a=s===n.length-1?`int ${r[s+1]} = ${e} - ${r[s]} * outShapeStrides[${s}]`:`index -= ${r[s]} * outShapeStrides[${s}]`;return`${i}; ${a};`}).join("")}function Fnt(r,t){let e=r.length,n=r.map(s=>`${t}[${s}]`),o=new Array(e-1);o[e-2]=n[e-1];for(let s=e-3;s>=0;--s)o[s]=`(${o[s+1]} * ${n[s+1]})`;return o}function TL(r,t,e="index"){let n=r.map((s,i)=>i),o=Fnt(n,t);return o.map((s,i)=>{let a=`int ${r[i]} = ${e} / ${o[i]}`,u=i===o.length-1?`int ${r[i+1]} = ${e} - ${r[i]} * ${o[i]}`:`index -= ${r[i]} * ${o[i]}`;return`${a}; ${u};`}).join("")}function Ed(r){let t=y.computeStrides(r).map(e=>e.toString());return`
| int getFlatIndex(ivec3 coords) {
| return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
| }
| `}function Ad(){return`
| int getFlatIndex(ivec3 coords) {
| return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
| }
| `}var Lw=`
| const float FLOAT_MAX = 1.70141184e38;
| const float FLOAT_MIN = 1.17549435e-38;
|
| lowp vec4 encode_float(highp float v) {
| if (isnan(v)) {
| return vec4(255, 255, 255, 255);
| }
|
| highp float av = abs(v);
|
| if(av < FLOAT_MIN) {
| return vec4(0.0, 0.0, 0.0, 0.0);
| } else if(v > FLOAT_MAX) {
| return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
| } else if(v < -FLOAT_MAX) {
| return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
| }
|
| highp vec4 c = vec4(0,0,0,0);
|
| highp float e = floor(log2(av));
| highp float m = exp2(fract(log2(av))) - 1.0;
|
| c[2] = floor(128.0 * m);
| m -= c[2] / 128.0;
| c[1] = floor(32768.0 * m);
| m -= c[1] / 32768.0;
| c[0] = floor(8388608.0 * m);
|
| highp float ebias = e + 127.0;
| c[3] = floor(ebias / 2.0);
| ebias -= c[3] * 2.0;
| c[2] += floor(ebias) * 128.0;
|
| c[3] += 128.0 * step(0.0, -v);
|
| return c / 255.0;
| }
| `;var{getBroadcastDims:_L}=S;function EL(r,t,e){let n=[];if(r.forEach(f=>{let d=y.sizeFromShape(f.shapeInfo.logicalShape);if(f.shapeInfo.isUniform?n.push(`uniform float ${f.name}${d>1?`[${d}]`:""};`):(n.push(`uniform sampler2D ${f.name};`),n.push(`uniform int offset${f.name};`)),e.enableShapeUniforms){let{uniformShape:h}=zw(e.packedInputs,f.shapeInfo.logicalShape,f.shapeInfo.texShape);switch(h.length){case 1:n.push(`uniform int ${f.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${f.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${f.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${f.name}Shape;`);break;default:break}n.push(`uniform ivec2 ${f.name}TexShape;`)}}),e.enableShapeUniforms){switch(t.logicalShape.length){case 1:n.push("uniform int outShape;");break;case 2:n.push("uniform ivec2 outShape;"),n.push("uniform int outShapeStrides;");break;case 3:n.push("uniform ivec3 outShape;"),n.push("uniform ivec2 outShapeStrides;");break;case 4:n.push("uniform ivec4 outShape;"),n.push("uniform ivec3 outShapeStrides;");break;default:break}n.push("uniform ivec2 outTexShape;")}e.customUniforms&&e.customUniforms.forEach(f=>{n.push(`uniform ${f.type} ${f.name}${f.arrayIndex?`[${f.arrayIndex}]`:""};`)});let o=n.join(`
| `),s=r.map(f=>Ont(f,t,e.packedInputs,e.enableShapeUniforms)).join(`
| `),i=t.texShape,a=We(),u=Lnt(a),l,c,p=Vnt(a);return t.isPacked?(l=Pnt(t.logicalShape,i,e.enableShapeUniforms),c=Bnt(a)):(l=Mnt(t.logicalShape,i,e.enableShapeUniforms),c=znt(a)),e.packedInputs&&(p+=Hnt),[p,u,c,o,l,s,e.userCode].join(`
| `)}function $d(r,t=!1){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return not(r,t);case 1:return sot(r,t);case 2:return aot(r,t);case 3:return uot(r,t);case 4:return pot(r,t);case 5:return mot(r);case 6:return fot(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function AL(r,t){switch(r.shapeInfo.logicalShape.length){case 0:return rot(r);case 1:return oot(r,t);case 2:return iot(r,t);case 3:return lot(r,t);default:return cot(r,t)}}function Ont(r,t,e=!1,n){let o="";e?o+=AL(r,n):o+=$d(r,n);let s=r.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(e?o+=dot(r,t):o+=hot(r,t)),o}function Pnt(r,t,e){switch(r.length){case 0:return DL();case 1:return qnt(r,t,e);case 2:return tot(r,t,e);case 3:return jnt(r,t,e);default:return Ynt(r,t,e)}}function Mnt(r,t,e){switch(r.length){case 0:return DL();case 1:return Knt(r,t,e);case 2:return eot(r,t,e);case 3:return Xnt(r,t,e);case 4:return Znt(r,t,e);case 5:return Jnt(r,t);case 6:return Qnt(r,t);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function Lnt(r){return`
| float sampleTexture(sampler2D textureSampler, vec2 uv) {
| return ${r.texture2D}(textureSampler, uv).r;
| }
| `}function znt(r){return`
| void setOutput(float val) {
| ${r.output} = vec4(val, 0, 0, 0);
| }
| `}function Bnt(r){return`
| void setOutput(vec4 val) {
| ${r.output} = val;
| }
| `}function Vnt(r){return`${r.version}
| precision highp float;
| precision highp int;
| precision highp sampler2D;
| ${r.varyingFs} vec2 resultUV;
| ${r.defineOutput}
| const vec2 halfCR = vec2(0.5, 0.5);
|
| struct ivec5
| {
| int x;
| int y;
| int z;
| int w;
| int u;
| };
|
| struct ivec6
| {
| int x;
| int y;
| int z;
| int w;
| int u;
| int v;
| };
|
| uniform float NAN;
| ${r.defineSpecialNaN}
| ${r.defineSpecialInf}
| ${r.defineRound}
|
| int imod(int x, int y) {
| return x - y * (x / y);
| }
|
| int idiv(int a, int b, float sign) {
| int res = a / b;
| int mod = imod(a, b);
| if (sign < 0. && mod != 0) {
| res -= 1;
| }
| return res;
| }
|
| //Based on the work of Dave Hoskins
| //https://www.shadertoy.com/view/4djSRW
| #define HASHSCALE1 443.8975
| float random(float seed){
| vec2 p = resultUV * seed;
| vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
| p3 += dot(p3, p3.yzx + 19.19);
| return fract((p3.x + p3.y) * p3.z);
| }
|
| ${Gnt}
| ${Wnt}
| ${Unt}
| `}var Gnt=`
| vec2 uvFromFlat(int texNumR, int texNumC, int index) {
| int texR = index / texNumC;
| int texC = index - texR * texNumC;
| return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
| }
| vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
| int texelIndex = index / 2;
| int texR = texelIndex / texNumC;
| int texC = texelIndex - texR * texNumC;
| return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
| }
| `,Wnt=`
| vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
| int texNumC, int row, int col) {
| int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
| int texR = texelIndex / texNumC;
| int texC = texelIndex - texR * texNumC;
| return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
| }
| `,Unt=`
| vec2 packedUVfrom3D(int texNumR, int texNumC,
| int texelsInBatch, int texelsInLogicalRow, int b,
| int row, int col) {
| int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
| int texR = index / texNumC;
| int texC = index - texR * texNumC;
| return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
| }
| `,Hnt=`
| float getChannel(vec4 frag, vec2 innerDims) {
| vec2 modCoord = mod(innerDims, 2.);
| return modCoord.x == 0. ?
| (modCoord.y == 0. ? frag.r : frag.g) :
| (modCoord.y == 0. ? frag.b : frag.a);
| }
| float getChannel(vec4 frag, int dim) {
| float modCoord = mod(float(dim), 2.);
| return modCoord == 0. ? frag.r : frag.g;
| }
| `;function DL(){return`
| int getOutputCoords() {
| return 0;
| }
| `}function qnt(r,t,e){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?e?`
| int getOutputCoords() {
| return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
| }
| `:`
| int getOutputCoords() {
| return 2 * int(resultUV.x * ${n[1]}.0);
| }
| `:n[1]===1?e?`
| int getOutputCoords() {
| return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
| }
| `:`
| int getOutputCoords() {
| return 2 * int(resultUV.y * ${n[0]}.0);
| }
| `:e?`
| int getOutputCoords() {
| ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(packedTexShape[0], packedTexShape[1]));
| return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
| }
| `:`
| int getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${n[0]}, ${n[1]}));
| return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
| }
| `}function Knt(r,t,e){return t[0]===1?e?`
| int getOutputCoords() {
| return int(resultUV.x * float(outTexShape[1]));
| }
| `:`
| int getOutputCoords() {
| return int(resultUV.x * ${t[1]}.0);
| }
| `:t[1]===1?e?`
| int getOutputCoords() {
| return int(resultUV.y * float(outTexShape[0]));
| }
| `:`
| int getOutputCoords() {
| return int(resultUV.y * ${t[0]}.0);
| }
| `:e?`
| int getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(outTexShape[0], outTexShape[1]));
| return resTexRC.x * outTexShape[1] + resTexRC.y;
| }
| `:`
| int getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| return resTexRC.x * ${t[1]} + resTexRC.y;
| }
| `}function jnt(r,t,e){if(e)return`
| ivec3 getOutputCoords() {
| ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
| int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
| int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(packedTexShape[0], packedTexShape[1]));
| int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
| int b = index / texelsInBatch;
| index -= b * texelsInBatch;
|
| int r = 2 * (index / texelsInLogicalRow);
| int c = imod(index, texelsInLogicalRow) * 2;
|
| return ivec3(b, r, c);
| }
| `;let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(r[2]/2),s=o*Math.ceil(r[1]/2);return`
| ivec3 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${n[0]}, ${n[1]}));
| int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
| int b = index / ${s};
| index -= b * ${s};
|
| int r = 2 * (index / ${o});
| int c = imod(index, ${o}) * 2;
|
| return ivec3(b, r, c);
| }
| `}function Xnt(r,t,e){if(e)return`
| ivec3 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(outTexShape[0], outTexShape[1]));
| int index = resTexRC.x * outTexShape[1] + resTexRC.y;
| ${yp(["r","c","d"],r)}
| return ivec3(r, c, d);
| }
| `;let n=ki(["r","c","d"],r);return`
| ivec3 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
| ${n}
| return ivec3(r, c, d);
| }
| `}function Ynt(r,t,e){if(e)return`
| ivec4 getOutputCoords() {
| ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(packedTexShape[0], packedTexShape[1]));
| int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
| int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
| int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
| int texelsInBatchN = texelsInBatch * outShape[1];
|
| int b2 = index / texelsInBatchN;
| index -= b2 * texelsInBatchN;
|
| int b = index / texelsInBatch;
| index -= b * texelsInBatch;
|
| int r = 2 * (index / texelsInLogicalRow);
| int c = imod(index, texelsInLogicalRow) * 2;
|
| return ivec4(b2, b, r, c);
| }
| `;let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(r[r.length-1]/2),s=o*Math.ceil(r[r.length-2]/2),i=s,a="",u="b, r, c";for(let l=2;l<r.length-1;l++)i*=r[r.length-l-1],a=`
| int b${l} = index / ${i};
| index -= b${l} * ${i};
| `+a,u=`b${l}, `+u;return`
| ivec${r.length} getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${n[0]}, ${n[1]}));
| int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
| ${a}
|
| int b = index / ${s};
| index -= b * ${s};
|
| int r = 2 * (index / ${o});
| int c = imod(index, ${o}) * 2;
|
| return ivec${r.length}(${u});
| }
| `}function Znt(r,t,e){if(e)return`
| ivec4 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(outTexShape[0], outTexShape[1]));
| int index = resTexRC.x * outTexShape[1] + resTexRC.y;
| ${yp(["r","c","d","d2"],r)}
| return ivec4(r, c, d, d2);
| }
| `;let n=ki(["r","c","d","d2"],r);return`
| ivec4 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
| ${n}
| return ivec4(r, c, d, d2);
| }
| `}function Jnt(r,t){let e=ki(["r","c","d","d2","d3"],r);return`
| ivec5 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
| ${t[1]}));
|
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
| ${e}
|
| ivec5 outShape = ivec5(r, c, d, d2, d3);
| return outShape;
| }
| `}function Qnt(r,t){let e=ki(["r","c","d","d2","d3","d4"],r);return`
| ivec6 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
| ${e}
|
| ivec6 result = ivec6(r, c, d, d2, d3, d4);
| return result;
| }
| `}function tot(r,t,e){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(y.arraysEqual(r,t))return e?`
| ivec2 getOutputCoords() {
| ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
| return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
| }
| `:`
| ivec2 getOutputCoords() {
| return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
| }
| `;let o=Math.ceil(r[1]/2);return e?`
| ivec2 getOutputCoords() {
| ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
| int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(packedTexShape[0], packedTexShape[1]));
|
| int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
| int r = 2 * (index / texelsInLogicalRow);
| int c = imod(index, texelsInLogicalRow) * 2;
|
| return ivec2(r, c);
| }
| `:`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${n[0]}, ${n[1]}));
|
| int index = resTexRC.x * ${n[1]} + resTexRC.y;
| int r = 2 * (index / ${o});
| int c = imod(index, ${o}) * 2;
|
| return ivec2(r, c);
| }
| `}function eot(r,t,e){return y.arraysEqual(r,t)?e?`
| ivec2 getOutputCoords() {
| return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
| }
| `:`
| ivec2 getOutputCoords() {
| return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
| }
| `:r[1]===1?e?`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(outTexShape[0], outTexShape[1]));
| int index = resTexRC.x * outTexShape[1] + resTexRC.y;
| return ivec2(index, 0);
| }
| `:`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
| return ivec2(index, 0);
| }
| `:r[0]===1?e?`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(outTexShape[0], outTexShape[1]));
| int index = resTexRC.x * outTexShape[1] + resTexRC.y;
| return ivec2(0, index);
| }
| `:`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
| return ivec2(0, index);
| }
| `:e?`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(outTexShape[0], outTexShape[1]));
| int index = resTexRC.x * outTexShape[1] + resTexRC.y;
| int r = index / outShape[1];
| int c = index - r * outShape[1];
| return ivec2(r, c);
| }
| `:`
| ivec2 getOutputCoords() {
| ivec2 resTexRC = ivec2(resultUV.yx *
| vec2(${t[0]}, ${t[1]}));
| int index = resTexRC.x * ${t[1]} + resTexRC.y;
| int r = index / ${r[1]};
| int c = index - r * ${r[1]};
| return ivec2(r, c);
| }
| `}function bp(r){return`offset${r}`}function rot(r){let t=r.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),n=We();return`
| vec4 ${e}() {
| return ${n.texture2D}(${t}, halfCR);
| }
| `}function not(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`float ${n}() {return ${e};}`;let[o,s]=r.shapeInfo.texShape;if(o===1&&s===1)return`
| float ${n}() {
| return sampleTexture(${e}, halfCR);
| }
| `;let i=bp(e);if(t)return`
| float ${n}() {
| vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], ${i});
| return sampleTexture(${e}, uv);
| }
| `;let[a,u]=r.shapeInfo.texShape;return`
| float ${n}() {
| vec2 uv = uvFromFlat(${a}, ${u}, ${i});
| return sampleTexture(${e}, uv);
| }
| `}function oot(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),o=r.shapeInfo.texShape,s=We();if(t)return`
| vec4 ${n}(int index) {
| ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
| vec2 uv = packedUVfrom1D(
| packedTexShape[0], packedTexShape[1], index);
| return ${s.texture2D}(${e}, uv);
| }
| `;let i=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return`
| vec4 ${n}(int index) {
| vec2 uv = packedUVfrom1D(
| ${i[0]}, ${i[1]}, index);
| return ${s.texture2D}(${e}, uv);
| }
| `}function sot(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
| float ${n}(int index) {
| ${Rd(r)}
| }
| `;let o=r.shapeInfo.texShape,s=o[0],i=o[1];if(i===1&&s===1)return`
| float ${n}(int index) {
| return sampleTexture(${e}, halfCR);
| }
| `;let a=bp(e);return i===1?t?`
| float ${n}(int index) {
| vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / float(${e}TexShape[0]));
| return sampleTexture(${e}, uv);
| }
| `:`
| float ${n}(int index) {
| vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${s}.0);
| return sampleTexture(${e}, uv);
| }
| `:s===1?t?`
| float ${n}(int index) {
| vec2 uv = vec2((float(index + ${a}) + 0.5) / float(${e}TexShape[1]), 0.5);
| return sampleTexture(${e}, uv);
| }
| `:`
| float ${n}(int index) {
| vec2 uv = vec2((float(index + ${a}) + 0.5) / ${i}.0, 0.5);
| return sampleTexture(${e}, uv);
| }
| `:t?`
| float ${n}(int index) {
| vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], index + ${a});
| return sampleTexture(${e}, uv);
| }
| `:`
| float ${n}(int index) {
| vec2 uv = uvFromFlat(${s}, ${i}, index + ${a});
| return sampleTexture(${e}, uv);
| }
| `}function iot(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape,i=s[0],a=s[1],u=We();if(s!=null&&y.arraysEqual(e,s))return t?`
| vec4 ${o}(int row, int col) {
| vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
| return ${u.texture2D}(${n}, uv);
| }
| `:`
| vec4 ${o}(int row, int col) {
| vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${i}.0);
|
| return ${u.texture2D}(${n}, uv);
| }
| `;if(t)return`
| vec4 ${o}(int row, int col) {
| ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
| int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
| vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
| return ${u.texture2D}(${n}, uv);
| }
| `;let l=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],c=Math.ceil(e[1]/2);return`
| vec4 ${o}(int row, int col) {
| vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
| return ${u.texture2D}(${n}, uv);
| }
| `}function aot(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape;if(s!=null&&y.arraysEqual(e,s)){if(t)return`
| float ${o}(int row, int col) {
| vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
| return sampleTexture(${n}, uv);
| }
| `;let m=s[0],f=s[1];return`
| float ${o}(int row, int col) {
| vec2 uv = (vec2(col, row) + halfCR) / vec2(${f}.0, ${m}.0);
| return sampleTexture(${n}, uv);
| }
| `}let{newShape:i,keptDims:a}=y.squeezeShape(e),u=i;if(u.length<e.length){let m=Fd(r,u),f=["row","col"];return`
| ${$d(m,t)}
| float ${o}(int row, int col) {
| return ${o}(${Od(f,a)});
| }
| `}if(r.shapeInfo.isUniform)return`
| float ${o}(int row, int col) {
| int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
| ${Rd(r)}
| }
| `;let l=s[0],c=s[1],p=bp(n);return c===1?t?`
| float ${o}(int row, int col) {
| float index = dot(vec3(row, col, ${p}), vec3(${n}Shape[1], 1, 1));
| vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col) {
| float index = dot(vec3(row, col, ${p}), vec3(${e[1]}, 1, 1));
| vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
| return sampleTexture(${n}, uv);
| }
| `:l===1?t?`
| float ${o}(int row, int col) {
| float index = dot(vec3(row, col, ${p}), vec3(${n}Shape[1], 1, 1));
| vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col) {
| float index = dot(vec3(row, col, ${p}), vec3(${e[1]}, 1, 1));
| vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
| return sampleTexture(${n}, uv);
| }
| `:t?`
| float ${o}(int row, int col) {
| // Explicitly use integer operations as dot() only works on floats.
| int index = row * ${n}Shape[1] + col + ${p};
| vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col) {
| // Explicitly use integer operations as dot() only works on floats.
| int index = row * ${e[1]} + col + ${p};
| vec2 uv = uvFromFlat(${l}, ${c}, index);
| return sampleTexture(${n}, uv);
| }
| `}function lot(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(e[0]===1){let m=e.slice(1),f=[1,2],d=Fd(r,m),h=["b","row","col"];return`
| ${AL(d,t)}
| vec4 ${o}(int b, int row, int col) {
| return ${o}(${Od(h,f)});
| }
| `}let a=We();if(t)return`
| vec4 ${o}(int b, int row, int col) {
| ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
| int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
| int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
| vec2 uv = packedUVfrom3D(
| packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
| return ${a.texture2D}(${n}, uv);
| }
| `;let u=i[0],l=i[1],c=Math.ceil(e[2]/2),p=c*Math.ceil(e[1]/2);return`
| vec4 ${o}(int b, int row, int col) {
| vec2 uv = packedUVfrom3D(
| ${u}, ${l}, ${p}, ${c}, b, row, col);
| return ${a.texture2D}(${n}, uv);
| }
| `}function uot(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e[1]*e[2],i=e[2],{newShape:a,keptDims:u}=y.squeezeShape(e),l=a;if(l.length<e.length){let h=Fd(r,l),g=["row","col","depth"];return`
| ${$d(h,t)}
| float ${o}(int row, int col, int depth) {
| return ${o}(${Od(g,u)});
| }
| `}if(r.shapeInfo.isUniform)return`
| float ${o}(int row, int col, int depth) {
| int index = round(dot(vec3(row, col, depth),
| vec3(${s}, ${i}, 1)));
| ${Rd(r)}
| }
| `;let c=r.shapeInfo.texShape,p=c[0],m=c[1],f=r.shapeInfo.flatOffset;if(m===s&&f==null)return t?`
| float ${o}(int row, int col, int depth) {
| int stride1 = ${n}Shape[2];
| float texR = float(row);
| float texC = dot(vec2(col, depth), vec2(stride1, 1));
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${n}TexShape[1], ${n}TexShape[0]);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col, int depth) {
| float texR = float(row);
| float texC = dot(vec2(col, depth), vec2(${i}, 1));
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${m}.0, ${p}.0);
| return sampleTexture(${n}, uv);
| }
| `;if(m===i&&f==null)return t?`
| float ${o}(int row, int col, int depth) {
| float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
| float texC = float(depth);
| vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col, int depth) {
| float texR = dot(vec2(row, col), vec2(${e[1]}, 1));
| float texC = float(depth);
| vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${m}.0, ${p}.0);
| return sampleTexture(${n}, uv);
| }
| `;let d=bp(n);return t?`
| float ${o}(int row, int col, int depth) {
| // Explicitly use integer operations as dot() only works on floats.
| int stride0 = ${n}Shape[1] * ${n}Shape[2];
| int stride1 = ${n}Shape[2];
| int index = row * stride0 + col * stride1 + depth + ${d};
| vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col, int depth) {
| // Explicitly use integer operations as dot() only works on floats.
| int index = row * ${s} + col * ${i} + depth + ${d};
| vec2 uv = uvFromFlat(${p}, ${m}, index);
| return sampleTexture(${n}, uv);
| }
| `}function cot(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),o=We();if(t)return`
| vec4 ${n}(int b2, int b, int row, int col) {
| int valuesPerRow = int(ceil(float(${e}Shape[3]) / 2.0));
| int texelsInBatch = valuesPerRow * int(ceil(float(${e}Shape[2]) / 2.0));
| int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
| texelsInBatch *= ${e}Shape[1];
| index = b2 * texelsInBatch + index;
| ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
| int texR = index / packedTexShape[1];
| int texC = index - texR * packedTexShape[1];
| vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${o.texture2D}(${e}, uv);
| }
| `;let s=r.shapeInfo.logicalShape,i=s.length,a=r.shapeInfo.texShape,u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=u[0],c=u[1],p=Math.ceil(s[i-1]/2),m=p*Math.ceil(s[i-2]/2),f="int b, int row, int col",d=`b * ${m} + (row / 2) * ${p} + (col / 2)`;for(let h=2;h<i-1;h++)f=`int b${h}, `+f,m*=s[i-h-1],d=`b${h} * ${m} + `+d;return`
| vec4 ${n}(${f}) {
| int index = ${d};
| int texR = index / ${c};
| int texC = index - texR * ${c};
| vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});
| return ${o.texture2D}(${e}, uv);
| }
| `}function pot(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e[3],i=e[2]*s,a=e[1]*i,{newShape:u,keptDims:l}=y.squeezeShape(e);if(u.length<e.length){let b=Fd(r,u),w=["row","col","depth","depth2"];return`
| ${$d(b,t)}
| float ${o}(int row, int col, int depth, int depth2) {
| return ${o}(${Od(w,l)});
| }
| `}if(r.shapeInfo.isUniform)return`
| float ${o}(int row, int col, int depth, int depth2) {
| int index = round(dot(vec4(row, col, depth, depth2),
| vec4(${a}, ${i}, ${s}, 1)));
| ${Rd(r)}
| }
| `;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1],d=`int stride2 = ${n}Shape[3];`,h=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(f===a&&c==null)return t?`
| float ${o}(int row, int col, int depth, int depth2) {
| ${d}
| ${h}
| float texR = float(row);
| float texC =
| dot(vec3(col, depth, depth2),
| vec3(stride1, stride2, 1));
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${n}TexShape[1], ${n}TexShape[0]);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col, int depth, int depth2) {
| float texR = float(row);
| float texC =
| dot(vec3(col, depth, depth2),
| vec3(${i}, ${s}, 1));
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${f}.0, ${m}.0);
| return sampleTexture(${n}, uv);
| }
| `;if(f===s&&c==null)return t?`
| float ${o}(int row, int col, int depth, int depth2) {
| float texR = dot(vec3(row, col, depth),
| vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
| float texC = float(depth2);
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${n}TexShape[1], ${n}TexShape[0]);
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col, int depth, int depth2) {
| float texR = dot(vec3(row, col, depth),
| vec3(${e[1]*e[2]}, ${e[2]}, 1));
| float texC = float(depth2);
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${f}.0, ${m}.0);
| return sampleTexture(${n}, uv);
| }
| `;let x=bp(n);return t?`
| float ${o}(int row, int col, int depth, int depth2) {
| // Explicitly use integer operations as dot() only works on floats.
| ${d}
| ${h}
| ${g}
| int index = row * stride0 + col * stride1 +
| depth * stride2 + depth2;
| vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${x});
| return sampleTexture(${n}, uv);
| }
| `:`
| float ${o}(int row, int col, int depth, int depth2) {
| // Explicitly use integer operations as dot() only works on floats.
| int index = row * ${a} + col * ${i} +
| depth * ${s} + depth2;
| vec2 uv = uvFromFlat(${m}, ${f}, index + ${x});
| return sampleTexture(${n}, uv);
| }
| `}function mot(r){let t=r.shapeInfo.logicalShape,e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),o=t[4],s=t[3]*o,i=t[2]*s,a=t[1]*i,{newShape:u,keptDims:l}=y.squeezeShape(t);if(u.length<t.length){let h=Fd(r,u),g=["row","col","depth","depth2","depth3"];return`
| ${$d(h)}
| float ${n}(int row, int col, int depth, int depth2, int depth3) {
| return ${n}(${Od(g,l)});
| }
| `}if(r.shapeInfo.isUniform)return`
| float ${n}(int row, int col, int depth, int depth2, int depth3) {
| float index = dot(
| vec4(row, col, depth, depth2),
| vec4(${a}, ${i}, ${s}, ${o})) +
| depth3;
| ${Rd(r)}
| }
| `;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1];if(f===a&&c==null)return`
| float ${n}(int row, int col, int depth, int depth2, int depth3) {
| int texR = row;
| float texC = dot(vec4(col, depth, depth2, depth3),
| vec4(${i}, ${s}, ${o}, 1));
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${f}.0, ${m}.0);
| return sampleTexture(${e}, uv);
| }
| `;if(f===o&&c==null)return`
| float ${n}(int row, int col, int depth, int depth2, int depth3) {
| float texR = dot(
| vec4(row, col, depth, depth2),
| vec4(${t[1]*t[2]*t[3]},
| ${t[2]*t[3]}, ${t[3]}, 1));
| int texC = depth3;
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${f}.0, ${m}.0);
| return sampleTexture(${e}, uv);
| }
| `;let d=bp(e);return`
| float ${n}(int row, int col, int depth, int depth2, int depth3) {
| // Explicitly use integer operations as dot() only works on floats.
| int index = row * ${a} + col * ${i} + depth * ${s} +
| depth2 * ${o} + depth3 + ${d};
| vec2 uv = uvFromFlat(${m}, ${f}, index);
| return sampleTexture(${e}, uv);
| }
| `}function fot(r){let t=r.shapeInfo.logicalShape,e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),{newShape:o,keptDims:s}=y.squeezeShape(t);if(o.length<t.length){let g=Fd(r,o),x=["row","col","depth","depth2","depth3","depth4"];return`
| ${$d(g)}
| float ${n}(int row, int col, int depth,
| int depth2, int depth3, int depth4) {
| return ${n}(${Od(x,s)});
| }
| `}let i=t[5],a=t[4]*i,u=t[3]*a,l=t[2]*u,c=t[1]*l;if(r.shapeInfo.isUniform)return`
| float ${n}(int row, int col, int depth,
| int depth2, int depth3, int depth4) {
| int index = round(dot(
| vec4(row, col, depth, depth2),
| vec4(${c}, ${l}, ${u}, ${a})) +
| dot(
| vec2(depth3, depth4),
| vec2(${i}, 1)));
| ${Rd(r)}
| }
| `;let p=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===c&&p==null)return`
| float ${n}(int row, int col, int depth,
| int depth2, int depth3, int depth4) {
| int texR = row;
| float texC = dot(vec4(col, depth, depth2, depth3),
| vec4(${l}, ${u}, ${a}, ${i})) +
| float(depth4);
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${d}.0, ${f}.0);
| return sampleTexture(${e}, uv);
| }
| `;if(d===i&&p==null)return`
| float ${n}(int row, int col, int depth,
| int depth2, int depth3, int depth4) {
| float texR = dot(vec4(row, col, depth, depth2),
| vec4(${t[1]*t[2]*t[3]*t[4]},
| ${t[2]*t[3]*t[4]},
| ${t[3]*t[4]},
| ${t[4]})) + float(depth3);
| int texC = depth4;
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${d}.0, ${f}.0);
| return sampleTexture(${e}, uv);
| }
| `;let h=bp(e);return`
| float ${n}(int row, int col, int depth,
| int depth2, int depth3, int depth4) {
| // Explicitly use integer operations as dot() only works on floats.
| int index = row * ${c} + col * ${l} + depth * ${u} +
| depth2 * ${a} + depth3 * ${i} + depth4 + ${h};
| vec2 uv = uvFromFlat(${f}, ${d}, index);
| return sampleTexture(${e}, uv);
| }
| `}function Rd(r){let t=r.name,e=y.sizeFromShape(r.shapeInfo.logicalShape);return e<2?`return ${t};`:`
| for (int i = 0; i < ${e}; i++) {
| if (i == index) {
| return ${t}[i];
| }
| }
| `}function dot(r,t){let e=r.name,n=e.charAt(0).toUpperCase()+e.slice(1),o="get"+n+"AtOutCoords",s=r.shapeInfo.logicalShape.length,i=t.logicalShape.length,a=_L(r.shapeInfo.logicalShape,t.logicalShape),u=zt(i),l=i-s,c,p=["x","y","z","w","u","v"];s===0?c="":i<2&&a.length>=1?c="coords = 0;":c=a.map(b=>`coords.${p[b+l]} = 0;`).join(`
| `);let m="";i<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((b,w)=>`coords.${p[w+l]}`).join(", ");let f="return outputValue;",h=y.sizeFromShape(r.shapeInfo.logicalShape)===1,x=y.sizeFromShape(t.logicalShape)===1;if(s===1&&!h&&!x)f=`
| return vec4(outputValue.xy, outputValue.xy);
| `;else if(h&&!x)i===1?f=`
| return vec4(outputValue.x, outputValue.x, 0., 0.);
| `:f=`
| return vec4(outputValue.x);
| `;else if(a.length){let b=s-2,w=s-1;a.indexOf(b)>-1&&a.indexOf(w)>-1?f="return vec4(outputValue.x);":a.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(w)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
| vec4 ${o}() {
| ${u} coords = getOutputCoords();
| ${c}
| vec4 outputValue = get${n}(${m});
| ${f}
| }
| `}function hot(r,t){let e=r.name,n=e.charAt(0).toUpperCase()+e.slice(1),o="get"+n+"AtOutCoords",s=t.texShape,i=r.shapeInfo.texShape,a=r.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!r.shapeInfo.isUniform&&a===u&&r.shapeInfo.flatOffset==null&&y.arraysEqual(i,s))return`
| float ${o}() {
| return sampleTexture(${e}, resultUV);
| }
| `;let l=zt(u),c=_L(r.shapeInfo.logicalShape,t.logicalShape),p=u-a,m,f=["x","y","z","w","u","v"];a===0?m="":u<2&&c.length>=1?m="coords = 0;":m=c.map(h=>`coords.${f[h+p]} = 0;`).join(`
| `);let d="";return u<2&&a>0?d="coords":d=r.shapeInfo.logicalShape.map((h,g)=>`coords.${f[g+p]}`).join(", "),`
| float ${o}() {
| ${l} coords = getOutputCoords();
| ${m}
| return get${n}(${d});
| }
| `}function zt(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error(`GPU for rank ${r} is not yet supported`)}function zw(r,t,e){let{newShape:n,keptDims:o}=y.squeezeShape(t),s=t.length,i=r&&s===3&&t[0]===1,a=i?t.slice(1):n,u=!r&&s>1&&!y.arraysEqual(t,e)&&n.length<s||i;return{useSqueezeShape:u,uniformShape:u?a:t,keptDims:o}}function Fd(r,t){let e=JSON.parse(JSON.stringify(r));return e.shapeInfo.logicalShape=t,e}function Od(r,t){return t.map(e=>r[e]).join(", ")}function RL(r,t,e,n){let o=e.map((c,p)=>{let m={logicalShape:c.shape,texShape:c.isUniform?null:c.texData.texShape,isUniform:c.isUniform,isPacked:c.isUniform?!1:c.texData.isPacked,flatOffset:null};return c.texData!=null&&c.texData.slice!=null&&c.texData.slice.flatOffset>0&&(m.flatOffset=c.texData.slice.flatOffset),{name:t.variableNames[p],shapeInfo:m}}),s=o.map(c=>c.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},a=EL(o,i,t),u=zT(r.gl,a),l=r.createProgram(u);return L().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:a,webGLProgram:l,inShapeInfos:s,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(r.buildVao(l),Object.assign({program:t,fragmentShader:u,source:a,webGLProgram:l,inShapeInfos:s,outShapeInfo:i},n1(r,t,l)))}function n1(r,t,e){let n=[],o=[],s,i,a,u=null,l=null;l=r.getUniformLocation(e,"NAN",!1),L().getNumber("WEBGL_VERSION")===1&&(u=r.getUniformLocation(e,"INFINITY",!1));let c=!1;for(let p of t.variableNames){let m={name:p,uniform:r.getUniformLocation(e,p,c),offset:r.getUniformLocation(e,`offset${p}`,c)};t.enableShapeUniforms&&(m.shape=r.getUniformLocation(e,`${p}Shape`,c),m.texShape=r.getUniformLocation(e,`${p}TexShape`,c)),n.push(m)}if(t.enableShapeUniforms&&(s=r.getUniformLocation(e,"outShape",c),a=r.getUniformLocation(e,"outShapeStrides",c),i=r.getUniformLocation(e,"outTexShape",c)),t.customUniforms)for(let p of t.customUniforms)o.push(r.getUniformLocation(e,p.name,c));return{variablesLocations:n,customUniformLocations:o,infLoc:u,nanLoc:l,outShapeLocation:s,outShapeStridesLocation:a,outTexShapeLocation:i}}function $L(r,t){if(r.length!==t.length)throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${t.length} inputs`);r.forEach((e,n)=>{let o=e.logicalShape,s=t[n],i=s.shape;if(!y.arraysEqual(o,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${i} must match`);if(e.isUniform&&s.isUniform)return;let a=e.texShape,u=s.isUniform?null:s.texData.texShape;if(!y.arraysEqual(a,u))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${u} must match`)})}function FL(r,t,e,n,o){t.program.enableShapeUniforms||($L(t.inShapeInfos,e),$L([t.outShapeInfo],[n]));let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?r.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):r.setOutputMatrixTexture(s.texture,i[0],i[1]),r.setProgram(t.webGLProgram),r.bindVertexArray(t.webGLProgram.vao),L().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&r.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&r.gl.uniform1f(t.nanLoc,NaN);for(let u=0;u<e.length;++u){let l=e[u],{uniform:c,offset:p,shape:m,texShape:f}=t.variablesLocations[u];if(m){let{uniformShape:d}=zw(t.program.packedInputs,l.shape,l.texData.texShape);switch(d.length){case 1:r.gl.uniform1iv(m,new Int32Array(d));break;case 2:r.gl.uniform2iv(m,new Int32Array(d));break;case 3:r.gl.uniform3iv(m,new Int32Array(d));break;case 4:r.gl.uniform4iv(m,new Int32Array(d));break;default:break}}if(f&&r.gl.uniform2i(f,l.texData.texShape[0],l.texData.texShape[1]),c!=null){if(l.isUniform){if(y.sizeFromShape(l.shape)<2)r.gl.uniform1f(c,l.uniformValues[0]);else{let d=l.uniformValues;d instanceof Float32Array||(d=new Float32Array(d)),r.gl.uniform1fv(c,d)}continue}l.texData.slice!=null&&p!=null&&r.gl.uniform1i(p,l.texData.slice.flatOffset),r.setInputMatrixTexture(l.texData.texture.texture,c,u)}}let a=t.outShapeLocation;if(a)switch(n.shape.length){case 1:r.gl.uniform1iv(a,new Int32Array(n.shape));break;case 2:r.gl.uniform2iv(a,new Int32Array(n.shape));break;case 3:r.gl.uniform3iv(a,new Int32Array(n.shape));break;case 4:r.gl.uniform4iv(a,new Int32Array(n.shape));break;default:break}if(t.outShapeStridesLocation){let u=y.computeStrides(n.shape);switch(n.shape.length){case 2:r.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(u));break;case 3:r.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(u));break;case 4:r.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(u));break;default:break}}if(t.outTexShapeLocation&&r.gl.uniform2i(t.outTexShapeLocation,n.texData.texShape[0],n.texData.texShape[1]),t.program.customUniforms&&o)for(let u=0;u<t.program.customUniforms.length;++u){let l=t.program.customUniforms[u],c=t.customUniformLocations[u],p=o[u];if(l.type==="float")r.gl.uniform1fv(c,p);else if(l.type==="vec2")r.gl.uniform2fv(c,p);else if(l.type==="vec3")r.gl.uniform3fv(c,p);else if(l.type==="vec4")r.gl.uniform4fv(c,p);else if(l.type==="int")r.gl.uniform1iv(c,p);else if(l.type==="ivec2")r.gl.uniform2iv(c,p);else if(l.type==="ivec3")r.gl.uniform3iv(c,p);else if(l.type==="ivec4")r.gl.uniform4iv(c,p);else throw Error(`uniform type ${l.type} is not supported yet.`)}r.executeProgram()}function OL(r,t,e){let n="";t.concat(e).forEach(i=>{let a=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(r.enableShapeUniforms&&!i.isUniform){let u=i.texData.texShape,{useSqueezeShape:l,uniformShape:c,keptDims:p}=zw(r.packedInputs,i.shape,u),m="",f="",d="";if(c.length===1&&r.packedInputs){let N=[Math.ceil(u[0]/2),Math.ceil(u[1]/2)];m=`${N[0]>1}_${N[1]>1}`}else if(c.length===2&&!r.packedInputs)f=`${c[0]>1}_${c[1]>1}`;else if(c.length>2&&!r.packedInputs){let N=y.computeStrides(c);d=`${N[0]===u[1]}_${N[N.length-1]===u[1]}`}let h=i.shape.length,g=c.length===2&&y.arraysEqual(i.shape,u),x=y.sizeFromShape(i.shape)===1,b=S.getBroadcastDims(i.shape,e.shape),w=!r.packedInputs&&h===e.shape.length&&y.arraysEqual(u,e.texData.texShape),I=r.packedInputs||c.length>2?"":`${u[0]>1}_${u[1]>1}`;n+=`${h}_${w}_${l?p:""}_${c.length}_${x}_${b}_${g}_${m}_${f}_${d}_${I}_${a}`}else{let u=i.isUniform?"uniform":i.texData.texShape;n+=`${i.shape}_${u}_${a}`}});let o=r.userCode,s=r.constructor.name;return s+="_"+n+"_"+o+`${L().getNumber("WEBGL_VERSION")}`,s}function de(r){return L().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&r<=4}var Bw=class{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Zu.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let e=We();this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length),this.userCode=`
| ivec3 outCoordsFromFlatIndex(int index) {
| ${this.enableShapeUniforms?yp(["r","c","d"],t):ki(["r","c","d"],t)}
| return ivec3(r, c, d);
| }
|
| void main() {
| ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
| int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
| vec4 result = vec4(0.);
|
| for (int i=0; i<4; i++) {
| int flatIndex = index + i;
| ivec3 rc = outCoordsFromFlatIndex(flatIndex);
| result[i] = getA(rc.x, rc.y, rc.z);
| }
|
| ${e.output} = result;
| }
| `}};var Vw=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Zu.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let e=We();this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length),this.userCode=`
| ivec3 outCoordsFromFlatIndex(int index) {
| ${this.enableShapeUniforms?yp(["r","c","d"],t):ki(["r","c","d"],t)}
| return ivec3(r, c, d);
| }
|
| void main() {
| ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
| int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
| vec4 result = vec4(0.);
|
| for (int i=0; i<4; i++) {
| int flatIndex = index + i;
| ivec3 rc = outCoordsFromFlatIndex(flatIndex);
| result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
| }
|
| ${e.output} = result;
| }
| `}};var Gw=class{constructor(t){this.variableNames=["A"],this.outTexUsage=Jr.DOWNLOAD;let e=We();this.outputShape=t,this.userCode=`
| ${Lw}
|
| void main() {
| float x = getAAtOutCoords();
| ${e.output} = encode_float(x);
| }
| `}};var Ww=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Jr.DOWNLOAD;let e=We();this.outputShape=t,this.userCode=`
| ${Lw}
|
| void main() {
| ivec3 coords = getOutputCoords();
| float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
| ${e.output} = encode_float(x);
| }
| `}};var yot={R:0,G:1,B:2,A:3},cg=class{constructor(t,e=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let o=We();this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length);let s="result";e&&(s="floor(result * 255. + 0.5)");let i="";for(let a=0;a<n.length;a++){let u=n[a];i+=`
| if(offset == ${a}) {
| result = values[${yot[u]}];
| }`}this.userCode=`
| ${this.enableShapeUniforms?Ad():Ed(t)}
|
| void main() {
| ivec3 coords = getOutputCoords();
| int flatIndex = getFlatIndex(coords);
| float result = 0.;
| int offset = imod(flatIndex, ${n.length});
|
| flatIndex = idiv(flatIndex, ${n.length}, 1.);
|
| int r = flatIndex / texShape[1];
| if (r < texShape[0]) {
| int c = imod(flatIndex, texShape[1]);
| vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
| vec4 values = ${o.texture2D}(A, uv);
| ${i}
| }
| ${o.output} = vec4(${s}, 0., 0., 0.);
| }
| `}};var Uw=class{constructor(t,e=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=We();this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length);let o="",s="result";e&&(s="floor(result * 255. + 0.5)");for(let i=0;i<=1;i++)for(let a=0;a<=1;a++){let u=i*2+a;o+=`
| localCoords = coords;
| if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${t[2]}`}) {
| localCoords[2] += ${a};
| if (localCoords[1] + ${i} < ${this.enableShapeUniforms?"outShape[1]":`${t[1]}`}) {
| localCoords[1] += ${i};
|
| flatIndex = getFlatIndex(localCoords);
| offset = imod(flatIndex, 4);
|
| flatIndex = idiv(flatIndex, 4, 1.);
|
| int r = flatIndex / texShape[1];
| int c = imod(flatIndex, texShape[1]);
| vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
| values = ${n.texture2D}(A, uv);
|
| if (offset == 0) {
| result[${u}] = values[0];
| } else if (offset == 1) {
| result[${u}] = values[1];
| } else if (offset == 2) {
| result[${u}] = values[2];
| } else {
| result[${u}] = values[3];
| }
| }
| }
| `}this.userCode=`
| ${this.enableShapeUniforms?Ad():Ed(t)}
|
| void main() {
| ivec3 coords = getOutputCoords();
|
| vec4 result = vec4(0.);
| int flatIndex, r, c, offset;
| ivec3 localCoords;
| vec2 uv;
| vec4 values;
|
| ${o}
|
| ${n.output} = ${s};
| }
| `}};var w1={};Kt(w1,{bindVertexProgramAttributeStreams:()=>m1,createBufferFromOutputTexture:()=>h1,createFloat16MatrixTexture:()=>l1,createFloat16PackedMatrixTexture:()=>p1,createFloat32MatrixTexture:()=>a1,createIndexBuffer:()=>i1,createPackedMatrixTexture:()=>c1,createUnsignedBytesMatrixTexture:()=>u1,createVertexBuffer:()=>s1,createVertexShader:()=>o1,downloadByteEncodedFloatMatrixFromOutputTexture:()=>x1,downloadFloat32MatrixFromBuffer:()=>g1,downloadMatrixFromPackedOutputTexture:()=>b1,downloadPackedMatrixFromBuffer:()=>y1,getInternalFormatForFloat16MatrixTexture:()=>qw,getInternalFormatForFloat16PackedMatrixTexture:()=>Xw,getInternalFormatForFloat32MatrixTexture:()=>Hw,getInternalFormatForPackedMatrixTexture:()=>jw,getInternalFormatForUnsignedBytesMatrixTexture:()=>Kw,uploadDenseMatrixToTexture:()=>f1,uploadPixelDataToTexture:()=>d1});function o1(r){let t=We(),e=`${t.version}
| precision highp float;
| ${t.attribute} vec3 clipSpacePos;
| ${t.attribute} vec2 uv;
| ${t.varyingVs} vec2 resultUV;
|
| void main() {
| gl_Position = vec4(clipSpacePos, 1);
| resultUV = uv;
| }`;return LT(r,e)}function s1(r){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return GT(r,t)}function i1(r){let t=new Uint16Array([0,1,2,2,1,3]);return WT(r,t)}function pg(r,t,e,n,o,s){HT(t,e);let i=UT(r),a=r.TEXTURE_2D;return ht(r,()=>r.bindTexture(a,i)),ht(r,()=>r.texParameteri(a,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),ht(r,()=>r.texParameteri(a,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),ht(r,()=>r.texParameteri(a,r.TEXTURE_MIN_FILTER,r.NEAREST)),ht(r,()=>r.texParameteri(a,r.TEXTURE_MAG_FILTER,r.NEAREST)),L().getNumber("WEBGL_VERSION")===1?ht(r,()=>r.texImage2D(a,0,n,t,e,0,o,s,null)):ht(r,()=>r.texStorage2D(a,1,n,t,e)),ht(r,()=>r.bindTexture(r.TEXTURE_2D,null)),{texture:i,texShape:[e,t]}}function Hw(r){return r.internalFormatFloat}function a1(r,t,e,n){let[o,s]=xp(t,e);return pg(r,o,s,Hw(n),n.textureFormatFloat,r.FLOAT)}function qw(r){return r.internalFormatHalfFloat}function l1(r,t,e,n){let[o,s]=xp(t,e);return pg(r,o,s,qw(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function Kw(r){return r.downloadTextureFormat}function u1(r,t,e,n){let[o,s]=xp(t,e);return pg(r,o,s,Kw(n),r.RGBA,r.UNSIGNED_BYTE)}function jw(r){return r.internalFormatPackedFloat}function c1(r,t,e,n){let[o,s]=Sa(t,e);return pg(r,o,s,jw(n),r.RGBA,r.FLOAT)}function Xw(r){return r.internalFormatPackedHalfFloat}function p1(r,t,e,n){let[o,s]=Sa(t,e);return pg(r,o,s,Xw(n),r.RGBA,n.textureTypeHalfFloat)}function m1(r,t,e){return ht(r,()=>r.bindBuffer(r.ARRAY_BUFFER,e)),Ow(r,t,"clipSpacePos",e,3,20,0)&&Ow(r,t,"uv",e,2,20,12)}function f1(r,t,e,n,o,s){ht(r,()=>r.bindTexture(r.TEXTURE_2D,t));let i,a,u;o instanceof Uint8Array?(i=new Uint8Array(e*n*4),a=r.UNSIGNED_BYTE,u=r.RGBA):(i=new Float32Array(e*n*4),a=r.FLOAT,u=s.internalFormatPackedFloat),i.set(o),L().getNumber("WEBGL_VERSION")===2?ht(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,e,n,r.RGBA,a,i)):ht(r,()=>r.texImage2D(r.TEXTURE_2D,0,u,e,n,0,r.RGBA,a,i)),ht(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function d1(r,t,e){ht(r,()=>r.bindTexture(r.TEXTURE_2D,t)),e.data instanceof Uint8Array?L().getNumber("WEBGL_VERSION")===2?ht(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,e.width,e.height,r.RGBA,r.UNSIGNED_BYTE,e.data)):ht(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e.width,e.height,0,r.RGBA,r.UNSIGNED_BYTE,e.data)):L().getNumber("WEBGL_VERSION")===2?ht(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,e)):ht(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e)),ht(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function h1(r,t,e,n){let o=r.createBuffer();ht(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,o));let a=4*4*t*e;return ht(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,a,r.STREAM_READ)),ht(r,()=>r.readPixels(0,0,e,t,r.RGBA,r.FLOAT,0)),ht(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),o}function g1(r,t,e){let n=r,o=new Float32Array(e);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}function x1(r,t,e,n){let[o,s]=xp(t,e),i=4,a=new Uint8Array(IL(t*e,i));return ht(r,()=>r.readPixels(0,0,o,s,n.downloadTextureFormat,r.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function y1(r,t,e,n,o,s,i,a){let u=r,l=new Float32Array(CL(s,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function b1(r,t,e){let n=new Float32Array(t*e*4);return ht(r,()=>r.readPixels(0,0,e,t,r.RGBA,r.FLOAT,n)),n}var wp=class{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let e=L().getNumber("WEBGL_VERSION");if(t!=null?(this.gl=t,FT(e,t)):this.gl=Yn(e),t=this.gl,L().getNumber("WEBGL_VERSION")===2){let s=t;this.createVertexArray=()=>ht(s,()=>s.createVertexArray()),this.bindVertexArray=i=>ht(s,()=>s.bindVertexArray(i)),this.deleteVertexArray=i=>ht(s,()=>s.deleteVertexArray(i)),this.getVertexArray=()=>ht(s,()=>s.getParameter(s.VERTEX_ARRAY_BINDING))}else if(t!=null){let s=t.getExtension("OES_vertex_array_object");if(s==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>ht(t,()=>s.createVertexArrayOES()),this.bindVertexArray=i=>ht(t,()=>s.bindVertexArrayOES(i)),this.deleteVertexArray=i=>ht(t,()=>s.deleteVertexArrayOES(i)),this.getVertexArray=()=>ht(t,()=>t.getParameter(s.VERTEX_ARRAY_BINDING_OES))}let n="WEBGL_color_buffer_float",o="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),L().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",i="OES_texture_half_float";if(this.textureFloatExtension=Nd(this.gl,s),Zn(this.gl,i))this.textureHalfFloatExtension=Nd(this.gl,i);else if(L().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Zn(this.gl,o))this.colorBufferHalfFloatExtension=Nd(this.gl,o);else if(L().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Zn(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Zn(this.gl,o))this.colorBufferHalfFloatExtension=this.gl.getExtension(o);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=s1(this.gl),this.indexBuffer=i1(this.gl),this.framebuffer=qT(this.gl),this.textureConfig=ag(this.gl,this.textureHalfFloatExtension)}get debug(){return L().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let t=this.gl;ht(t,()=>t.finish()),ht(t,()=>t.bindFramebuffer(t.FRAMEBUFFER,null)),ht(t,()=>t.deleteFramebuffer(this.framebuffer)),ht(t,()=>t.bindBuffer(t.ARRAY_BUFFER,null)),ht(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),ht(t,()=>t.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(t,e){return this.throwIfDisposed(),a1(this.gl,t,e,this.textureConfig)}createFloat16MatrixTexture(t,e){return this.throwIfDisposed(),l1(this.gl,t,e,this.textureConfig)}createUnsignedBytesMatrixTexture(t,e){return this.throwIfDisposed(),u1(this.gl,t,e,this.textureConfig)}uploadPixelDataToTexture(t,e){this.throwIfDisposed(),d1(this.gl,t,e)}uploadDenseMatrixToTexture(t,e,n,o){this.throwIfDisposed(),f1(this.gl,t,e,n,o,this.textureConfig)}createFloat16PackedMatrixTexture(t,e){return this.throwIfDisposed(),p1(this.gl,t,e,this.textureConfig)}createPackedMatrixTexture(t,e){return this.throwIfDisposed(),c1(this.gl,t,e,this.textureConfig)}deleteMatrixTexture(t){this.throwIfDisposed(),this.outputTexture===t&&(Pw(this.gl,this.framebuffer),this.outputTexture=null),ht(this.gl,()=>this.gl.deleteTexture(t))}downloadByteEncodedFloatMatrixFromOutputTexture(t,e,n){return this.downloadMatrixDriver(t,()=>x1(this.gl,e,n,this.textureConfig))}downloadPackedMatrixFromBuffer(t,e,n,o,s,i){return y1(this.gl,t,e,n,o,s,i,this.textureConfig)}downloadFloat32MatrixFromBuffer(t,e){return g1(this.gl,t,e)}createBufferFromTexture(t,e,n){this.bindTextureToFrameBuffer(t);let o=h1(this.gl,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),o}createAndWaitForFence(){let t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,n;if(L().getBool("WEBGL_FENCE_API_ENABLED")){let o=t,s=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=()=>{let i=o.clientWaitSync(s,0,0);return i===o.ALREADY_SIGNALED||i===o.CONDITION_SATISFIED},e=s}else L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(e,L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:e,isFencePassed:n}}downloadMatrixFromPackedTexture(t,e,n){return this.downloadMatrixDriver(t,()=>b1(this.gl,e,n))}createProgram(t){this.throwIfDisposed();let e=this.gl;this.vertexShader==null&&(this.vertexShader=o1(e));let n=BT(e);ht(e,()=>e.attachShader(n,this.vertexShader)),ht(e,()=>e.attachShader(n,t)),VT(e,n);let o=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&lg(e,o),o}buildVao(t){this.setProgram(t),this.bindVertexArray(t.vao);let e=this.gl;ht(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),m1(e,t,this.vertexBuffer)}deleteProgram(t){this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&(ht(this.gl,()=>this.gl.deleteProgram(t)),this.deleteVertexArray(t.vao))}setProgram(t){this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&lg(this.gl,this.program),ht(this.gl,()=>this.gl.useProgram(t))}getUniformLocation(t,e,n=!0){return this.throwIfDisposed(),n?KT(this.gl,t,e):jT(this.gl,t,e)}getAttributeLocation(t,e){return this.throwIfDisposed(),ht(this.gl,()=>this.gl.getAttribLocation(t,e))}getUniformLocationNoThrow(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)}setInputMatrixTexture(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),XT(this.gl,t,e,n)}setOutputMatrixTexture(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)}setOutputPackedMatrixTexture(t,e,n){this.throwIfDisposed();let[o,s]=Sa(e,n);this.setOutputMatrixTextureDriver(t,o,s)}setOutputMatrixWriteRegion(t,e,n,o){this.setOutputMatrixWriteRegionDriver(n,t,o,e)}setOutputPackedMatrixWriteRegion(t,e,n,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&lg(this.gl,this.program),kd(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let t=this.gl;if(this.debug){let e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}ht(t,()=>t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),ht(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Nd(this.gl,L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,o=this.getQueryTimerExtensionWebGL2(),s=n.createQuery();return n.beginQuery(o.TIME_ELAPSED_EXT,s),s}let t=this.getQueryTimerExtensionWebGL1(),e=t.createQueryEXT();return t.beginQueryEXT(t.TIME_ELAPSED_EXT,e),e}endQuery(){if(L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT);return}let t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(t){return await y.repeatedTry(()=>this.disposed||this.isQueryAvailable(t,L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(t,L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(t,e){if(e===0)return null;if(e===2){let n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(t,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(t,e){if(e===0)return!0;if(e===2){let n=this.gl,o=this.getQueryTimerExtensionWebGL2(),s=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),s&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),o=n.getQueryObjectEXT(t,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),o&&!this.disjoint}}pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){let t=bot(this.itemsToPoll.map(e=>e.isDoneFn));for(let e=0;e<=t;++e){let{resolveFn:n}=this.itemsToPoll[e];n()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}addItemToPoll(t,e){if(this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in L().platform&&(n=L().platform.setTimeoutCustom.bind(L().platform)),y.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,n)}bindTextureToFrameBuffer(t){this.throwIfDisposed(),ug(this.gl,t,this.framebuffer),this.debug&&kd(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(ug(this.gl,this.outputTexture,this.framebuffer),this.debug&&kd(this.gl)):Pw(this.gl,this.framebuffer)}downloadMatrixDriver(t,e){this.bindTextureToFrameBuffer(t);let n=e();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(t,e,n){this.throwIfDisposed();let o=this.gl;ug(o,t,this.framebuffer),this.debug&&kd(o),this.outputTexture=t,ht(o,()=>o.viewport(0,0,e,n)),ht(o,()=>o.scissor(0,0,e,n))}setOutputMatrixWriteRegionDriver(t,e,n,o){this.throwIfDisposed(),ht(this.gl,()=>this.gl.scissor(t,e,n,o))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function bot(r){let t=0;for(;t<r.length&&r[t]();++t);return t-1}var{addImpl:PL,bincountImpl:Yw,bincountReduceImpl:ML,bitwiseAndImpl:LL,castImpl:zL,ceilImpl:BL,concatImpl:VL,equalImpl:GL,expImpl:WL,expm1Impl:UL,floorImpl:HL,gatherNdImpl:qL,gatherV2Impl:KL,greaterImpl:jL,greaterEqualImpl:XL,lessImpl:YL,lessEqualImpl:ZL,linSpaceImpl:JL,logImpl:QL,maxImpl:tz,maximumImpl:ez,minimumImpl:rz,multiplyImpl:nz,negImpl:oz,notEqualImpl:sz,prodImpl:iz,raggedGatherImpl:az,raggedRangeImpl:lz,raggedTensorToTensorImpl:uz,rangeImpl:cz,rsqrtImpl:pz,scatterImpl:mz,sigmoidImpl:fz,simpleAbsImpl:Zw,sliceImpl:dz,sparseFillEmptyRowsImpl:hz,sparseReshapeImpl:gz,sparseSegmentReductionImpl:Jw,sqrtImpl:xz,staticRegexReplaceImpl:yz,stridedSliceImpl:bz,stringNGramsImpl:wz,stringSplitImpl:Iz,stringToHashBucketFastImpl:Cz,subImpl:vz,tileImpl:Sz,topKImpl:Nz,transposeImpl:Ip,uniqueImpl:kz}=Nw;function I1(r,t){return["x","y","z","w","u","v"].slice(0,t).map(e=>`${r}.${e}`)}function er(r,t){return t===1?[r]:I1(r,t)}function Tz(r,t){if(r===1)return"rc";let e="";for(let n=0;n<r;n++)e+=t[n],n<r-1&&(e+=",");return e}var Qw=class{constructor(t){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.enableShapeUniforms=de(this.outputShape.length),this.rank===0)this.userCode=`
| void main() {
| setOutput(vec4(getA(), 0., 0., 0.));
| }
| `;else{let e=er("rc",this.rank),n=zt(this.rank),o=this.getOutOfBoundsCondition(e),s=this.getSetup(e),i=this.getOutput(e);this.userCode=`
| void main() {
| ${n} rc = getOutputCoords();
|
| if(${o}) {
| setOutput(vec4(0));
| } else {
| ${s}
|
| setOutput(vec4(${i}));
| }
| }
| `}}getSourceCoordsArr(t){let e=[];for(let n=0;n<=1;n++)for(let o=0;o<=1;o++){let s=`${n===0?"r":"rp1"}, ${o===0?"c":"cp1"}`;for(let i=2;i<this.rank;i++)s=`${t[t.length-1-i]},`+s;e.push(s)}return e}getOutOfBoundsCondition(t){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let e="";for(let n=this.rank-2;n<this.rank;n++)e+=`${t[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(e+="||");return e}getSetup(t){if(this.rank===1)return"";let e=t.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],o=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
| int r = ${e[0]};
| int c = ${e[1]};
| int rp1 = r + 1;
| int cp1 = c + 1;
|
| bool cEdge = cp1 >= ${n};
| bool rEdge = rp1 >= ${o};
| `}getOutput(t){let e=this.getSourceCoordsArr(t);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${e[0]}),
| cEdge ? 0. : getA(${e[1]}),
| rEdge ? 0. : getA(${e[2]}),
| rEdge || cEdge ? 0. : getA(${e[3]})`}};var Pd=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length);let n="";for(let o=0;o<4;o++){let s="thisRC = rc;";o%2===1&&(s+="thisRC.z += 1;"),o>1&&(s+="thisRC.y += 1;"),n+=`
| ${s}
| ${o>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
| int flatIndex = getFlatIndex(thisRC);
|
| ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
| vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
| result[${o}] =
| getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
| ${o>0?"}":""}
| `}this.userCode=`
| ${wot(e,this.enableShapeUniforms)}
| ${this.enableShapeUniforms?Ad():Ed(t)}
|
| void main() {
| ivec3 rc = getOutputCoords();
|
| vec4 result = vec4(0.);
|
| ivec3 thisRC;
| int rows = ${this.enableShapeUniforms?"outShape[1]":t[1]};
| int cols = ${this.enableShapeUniforms?"outShape[2]":t[2]};
|
| ${n}
|
| setOutput(result);
| }
| `}};function wot(r,t){return`
| ivec3 inputCoordsFromReshapedOutCoords(int index) {
| ${t?TL(["r","c","d"],"inputShape"):ki(["r","c","d"],r)}
| return ivec3(r, c, d);
| }
| `}var tI=class{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(t,e,n){let o=Ez(e,n),s=Az(t,o,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let i=_z(t,o,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();let u=this.freeTextures[s].pop();return this.usedTextures[s].push(u),u}let a;return o===zr.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===zr.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===zr.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===zr.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===zr.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[s].push(a),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),a}releaseTexture(t,e,n,o){if(this.freeTextures==null)return;let s=Ez(n,o),i=Az(e,s,o);i in this.freeTextures||(this.freeTextures[i]=[]);let a=_z(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,o),u=L().get("WEBGL_DELETE_TEXTURE_THRESHOLD");u!==-1&&this._numBytesAllocated>u?(this.gpgpu.deleteMatrixTexture(t.texture),this._numBytesAllocated-=a):(this.freeTextures[i].push(t),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;let l=this.usedTextures[i],c=l&&l.indexOf(t);if(c==null||c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[c]=l[l.length-1],l.pop(),this.log()}log(){if(!this.logEnabled)return;let t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${t})`);let e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(let t in this.usedTextures)this.usedTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function Iot(r,t){let e=r;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===r.RGBA)return 16;if(t===e.RGBA16F)return 8;if(t===e.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function _z(r,t,e,n,o){let s=Cot(t,n),i;if(o){let[u,l]=Sa(r[0],r[1]);i=u*l}else{let[u,l]=xp(r[0],r[1]);i=u*l}let a=Iot(e,s);return i*a}function Cot(r,t){switch(r){case zr.PACKED_2X2_FLOAT32:return jw(t);case zr.PACKED_2X2_FLOAT16:return Xw(t);case zr.UNPACKED_FLOAT32:return Hw(t);case zr.UNPACKED_FLOAT16:return qw(t);case zr.PACKED_4X1_UNSIGNED_BYTE:return Kw(t);default:throw new Error(`Unknown physical texture type ${r}`)}}function vot(r){return L().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?zr.PACKED_2X2_FLOAT32:zr.UNPACKED_FLOAT32:r?zr.PACKED_2X2_FLOAT16:zr.UNPACKED_FLOAT16}function Ez(r,t){if(r===Jr.UPLOAD)return zr.PACKED_2X2_FLOAT32;if(r===Jr.RENDER||r==null)return vot(t);if(r===Jr.DOWNLOAD||r===Jr.PIXELS)return zr.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function Az(r,t,e){return`${r[0]}_${r[1]}_${t}_${e}`}var Br=class{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length),this.userCode=`
| float unaryOperation(float x) {
| ${e}
| }
|
| void main() {
| float x = getAAtOutCoords();
| float y = unaryOperation(x);
|
| setOutput(y);
| }
| `}},yr="if (isnan(x)) return x;",Dz="return x;",C1="return abs(x);";var $z="return (x >= 0.0) ? x : (exp(x) - 1.0);",Rz=yr+`
| return (x < 0.0) ? 0.0 : x;
| `,Fz=yr+`
| return (x < 0.0) ? 0.0 : min(6.0, x);
| `,Na="return x;",Oz="return 1.0 / (1.0 + exp(-1.0 * x));";var Mz="return x;",Lz=`
| vec4 result;
|
| result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
| result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
| result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
| result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
|
| return result;
| `,zz=`
| vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
| bvec4 isNaN = isnan(x);
|
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `,Bz=`
| vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
| bvec4 isNaN = isnan(x);
|
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `,Vz="return 1.0 / (1.0 + exp(-1.0 * x));",Fn=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length),this.userCode=`
| vec4 unaryOperation(vec4 x) {
| ${e}
| }
|
| void main() {
| vec4 x = getAAtOutCoords();
| vec4 y = unaryOperation(x);
|
| setOutput(y);
| }
| `}};var eI=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length);let e=t.length,n=er("rc",e),o=zt(e),s=Tz(e,n),i=n.slice(-2),a=e<=1?"rc":`vec2(${i.join(",")})`;this.userCode=`
| void main() {
| ${o} rc = getOutputCoords();
| vec4 packedInput = getA(${s});
|
| setOutput(getChannel(packedInput, ${a}));
| }
| `}};var Not=jr.whereImpl,kot=1e-7,Tot=1e-4,rI={};function _ot(r){return r in rI||(rI[r]={}),rI[r]}var Eot=L().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Aot=600;function Dot(){return L().global.screen==null?1024:L().global.screen.height*L().global.screen.width*window.devicePixelRatio*Aot/1024/1024}var Qu=class extends Uo{nextDataId(){return Qu.nextDataId++}constructor(t){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!L().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let e;if(t!=null){if(t instanceof wp)e=t;else{let n=Yn(L().getNumber("WEBGL_VERSION"),t);e=new wp(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Yn(L().getNumber("WEBGL_VERSION"));e=new wp(n),this.binaryCache=_ot(L().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=e,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new tI(this.gpgpu),this.numMBBeforeWarning=Dot(),this.texData=new Da(this,Wn())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(t,e,n,o,s,i){let a=this.makeTensorInfo(e,n),u=this.texData.get(a.dataId);u.isPacked=!1,u.texture={texture:t,texShape:[o,s]},u.texShape=[o,s];let l=Td(e),c=new cg(l,!1,i),p=this.runWebGLProgram(c,[a],n,[[o,s]]);return p.shape=e,u.texture=null,this.disposeIntermediateTensorInfo(a),p.dataId}write(t,e,n){if((L().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||L().getBool("DEBUG"))&&this.checkNumericalProblems(t),n==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let o={id:this.nextDataId()};return this.texData.set(o,{shape:e,dtype:n,values:t,usage:Jr.UPLOAD,refCount:1}),o}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){let e=this.texData.get(t);e.refCount++}decRef(t){if(this.texData.has(t)){let e=this.texData.get(t);e.refCount--}}move(t,e,n,o,s){if(L().getBool("DEBUG")&&this.checkNumericalProblems(e),o==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:o,values:e,usage:Jr.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){let e=this.texData.get(t),{values:n,dtype:o,complexTensorInfos:s,slice:i,shape:a,isPacked:u}=e;if(i!=null){let m;u?m=new Fn(a,Na):m=new Br(a,Na);let f=this.runWebGLProgram(m,[{dataId:t,shape:a,dtype:o}],o),d=this.readSync(f.dataId);return this.disposeIntermediateTensorInfo(f),d}if(n!=null)return this.convertAndCacheOnCPU(t);if(o==="string")return n;let l=this.activeTimers!=null,c;l&&(c=y.now());let p;if(o==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=S.mergeRealAndImagArrays(m,f)}else p=this.getValuesFromTexture(t);return l&&(this.downloadWaitMs+=y.now()-c),this.convertAndCacheOnCPU(t,p)}async read(t){if(this.pendingRead.has(t)){let d=this.pendingRead.get(t);return new Promise(h=>d.push(h))}let e=this.texData.get(t),{values:n,shape:o,slice:s,dtype:i,complexTensorInfos:a,isPacked:u}=e;if(s!=null){let d;u?d=new Fn(o,Na):d=new Br(o,Na);let h=this.runWebGLProgram(d,[{dataId:t,shape:o,dtype:i}],i),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(n!=null)return this.convertAndCacheOnCPU(t);if(L().getBool("DEBUG")&&!L().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&L().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(i!=="complex64"&&L().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(t);let d=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(d.texture.texture,...ig(o))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(i==="complex64"){let d=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),h=d[0],g=d[1];p=S.mergeRealAndImagArrays(h,g)}else if(l==null)p=this.getValuesFromTexture(t);else{let d=y.sizeFromShape(o);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,d)}if(c!=null&&this.disposeIntermediateTensorInfo(c),l!=null){let d=this.gpgpu.gl;ht(d,()=>d.deleteBuffer(l))}let m=this.convertAndCacheOnCPU(t,p),f=this.pendingRead.get(t);return this.pendingRead.delete(t),f.forEach(d=>d(m)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&Wn().removeDataId(t,this),this.pendingDeletes--),m}readToGPU(t,e={}){let n=this.texData.get(t),{values:o,shape:s,slice:i,dtype:a,isPacked:u,texture:l}=n;if(a==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let f;u?f=new Fn(s,Na):f=new Br(s,Na);let d=this.runWebGLProgram(f,[{dataId:t,shape:s,dtype:a}],a),h=this.readToGPU(d,e);return this.disposeIntermediateTensorInfo(d),h}if(l==null)throw o!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let c=this.decode(t,e.customTexShape),p=Wn().makeTensorFromTensorInfo(c),m=this.texData.get(c.dataId);return Object.assign({tensorRef:p},m.texture)}bufferSync(t){let e=this.readSync(t.dataId);if(t.dtype==="string")try{let n=e.map(o=>y.decodeString(o));return wt(t.shape,t.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(t.shape,t.dtype,e)}checkNumericalProblems(t){if(t!=null)for(let e=0;e<t.length;e++){let n=t[e];if(!MT(n))throw L().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(t){let{shape:e,dtype:n,isPacked:o}=this.texData.get(t),s=y.sizeFromShape(e);if(L().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let m=this.decode(t),f=this.texData.get(m.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(f.texture.texture,...ig(e)).subarray(0,s);return this.disposeIntermediateTensorInfo(m),d}let i=L().getBool("WEBGL_PACK")&&o===!0,a=i?Td(e):e,u=i?new Ww(a):new Gw(a),l=this.runWebGLProgram(u,[{shape:a,dtype:n,dataId:t}],"float32"),c=this.texData.get(l.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture.texture,c.texShape[0],c.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(l),p}timerAvailable(){return L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(t){let e=this.activeTimers,n=[],o=!1;this.programTimersStack==null?(this.programTimersStack=n,o=!0):this.activeTimers.push(n),this.activeTimers=n,t();let s=y.flatten(this.activeTimers.map(u=>u.query)).filter(u=>u!=null),i=y.flatten(this.activeTimers.map(u=>u.name)).filter(u=>u!=null);this.activeTimers=e,o&&(this.programTimersStack=null);let a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let u=await Promise.all(s);a.kernelMs=y.sum(u),a.getExtraProfileInfo=()=>u.map((l,c)=>({name:i[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:y.now(),endMs:null}}endTimer(t){return L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=y.now(),t)}async getQueryTime(t){if(L().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);let e=t;return e.endMs-e.startMs}disposeData(t,e=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(e?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!e&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);let{complexTensorInfos:n}=this.texData.get(t);return n!=null&&(this.disposeData(n.real.dataId,e),this.disposeData(n.imag.dataId,e)),this.texData.delete(t),!0}releaseGPUData(t){let{texture:e,dtype:n,texShape:o,usage:s,isPacked:i,slice:a}=this.texData.get(t),u=a&&a.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),e!=null&&(this.numBytesInGPU-=this.computeBytes(o,n),this.textureManager.releaseTexture(e,o,s,i)));let c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture.texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,e=Eot){return L().getBool("WEBGL_CPU_FORWARD")&&t.every(n=>this.texData.get(n.dataId).texture==null&&y.sizeFromShape(n.shape)<e)}getGPGPUContext(){return this.gpgpu}where(t){S.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let e=t.dataSync();return Not(t.shape,e)}packedUnaryOp(t,e,n){let o=new Fn(t.shape,e),s=this.compileAndRun(o,[t],n);return Wn().makeTensorFromTensorInfo(s)}abs(t){if(this.shouldExecuteOnCPU([t])&&t.dtype!=="complex64"){let o=Zw(this.texData.get(t.dataId).values);return this.makeOutput(t.shape,t.dtype,o)}if(L().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,C1,t.dtype);let e=new Br(t.shape,C1),n=this.compileAndRun(e,[t]);return Wn().makeTensorFromTensorInfo(n)}makeTensorInfo(t,e,n){let o;if(e==="string"&&n!=null&&n.length>0&&y.isString(n[0])){let s=n.map(i=>y.encodeString(i));o=this.write(s,t,e)}else o=this.write(n,t,e);return this.texData.get(o).usage=null,{dataId:o,shape:t,dtype:e}}makeOutput(t,e,n){return Wn().makeTensorFromTensorInfo(this.makeTensorInfo(t,e,n),this)}unpackTensor(t){let e=new eI(t.shape);return this.runWebGLProgram(e,[t],t.dtype)}packTensor(t){let e=new Qw(t.shape),n=!0;return this.runWebGLProgram(e,[t],t.dtype,null,n)}packedReshape(t,e){let n=[Vl(t.shape),...Gl(t.shape)],o={dtype:t.dtype,shape:n,dataId:t.dataId},s=[Vl(e),...Gl(e)],i=new Pd(s,n),a=!0,u=[n],l=this.runWebGLProgram(i,[o],t.dtype,u,a);return{dataId:l.dataId,shape:e,dtype:l.dtype}}decode(t,e){let n=this.texData.get(t),{isPacked:o,shape:s,dtype:i}=n;if(e!=null){let m=y.sizeFromShape(s),f=e[0]*e[1]*4;y.assert(m<=f,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let a=Td(s),u;o?u=new Vw(a):u=new Bw(a);let l=!0,c=[e!=null?e:ig(a)],p=this.runWebGLProgram(u,[{shape:a,dtype:i,dataId:t}],i,c,l,e);return{dtype:i,shape:s,dataId:p.dataId}}runWebGLProgram(t,e,n,o,s=!1,i){let a=this.makeTensorInfo(t.outputShape,n),u=this.texData.get(a.dataId);if(t.packedOutput&&(u.isPacked=!0),t.outPackingScheme===Zu.DENSE){let x=i!=null?i:ig(t.outputShape);u.texShape=x.map(b=>b*2)}if(t.outTexUsage!=null&&(u.usage=t.outTexUsage),y.sizeFromShape(a.shape)===0)return u.values=y.getTypedArrayFromDType(a.dtype,0),a;let l=[],c=e.map(x=>{if(x.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let b=this.texData.get(x.dataId);if(b.texture==null){if(!t.packedInputs&&y.sizeFromShape(x.shape)<=L().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:x.shape,texData:null,isUniform:!0,uniformValues:b.values};t.packedInputs&&(b.isPacked=!0,b.shape=x.shape)}if(this.uploadToGPU(x.dataId),!!b.isPacked!=!!t.packedInputs)x=b.isPacked?this.unpackTensor(x):this.packTensor(x),l.push(x),b=this.texData.get(x.dataId);else if(b.isPacked&&!Ju(b.shape,x.shape)){let w=x,I=x.shape;x.shape=b.shape,x=this.packedReshape(x,I),l.push(x),b=this.texData.get(x.dataId),w.shape=I}return{shape:x.shape,texData:b,isUniform:!1}});this.uploadToGPU(a.dataId);let p={shape:a.shape,texData:u,isUniform:!1},m=OL(t,c,p),f=this.getAndSaveBinary(m,()=>RL(this.gpgpu,t,c,p)),d=this.activeTimers!=null,h;d&&(h=this.startTimer()),L().get("ENGINE_COMPILE_ONLY")||FL(this.gpgpu,f,c,p,o),l.forEach(x=>this.disposeIntermediateTensorInfo(x)),d&&(h=this.endTimer(h),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(h)}));let g=L().get("WEBGL_FLUSH_THRESHOLD");if(g>0){let x=y.now();x-this.lastGlFlushTime>g&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=x)}if(!L().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&s===!1){let x=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),x}return a}compileAndRun(t,e,n,o,s=!1){return n=n||e[0].dtype,this.runWebGLProgram(t,e,n,o,s)}getAndSaveBinary(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(L().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=B(()=>{if(!L().get("WEBGL_RENDER_FLOAT32_ENABLED")){let t=L().getBool("DEBUG");L().set("DEBUG",!1);let e=this.abs(ft(1e-8)).dataSync()[0];if(L().set("DEBUG",t),e>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?kot:Tot}uploadToGPU(t){let e=this.texData.get(t),{shape:n,dtype:o,values:s,texture:i,usage:a,isPacked:u}=e;if(i!=null)return;let l=this.activeTimers!=null,c;l&&(c=y.now());let p=e.texShape;if(p==null&&(p=YT(n,u),e.texShape=p),s!=null){let m=Td(n),f,d=p[1],h=p[0],g=s instanceof Uint8Array||s instanceof Uint8ClampedArray;(u||!g)&&([d,h]=Sa(p[0],p[1])),u?f=new Uw(m,g):f=new cg(m,g);let x=g?[h,d]:p,b=this.makeTensorInfo(x,o),w=this.texData.get(b.dataId);g?w.usage=Jr.PIXELS:w.usage=Jr.UPLOAD,w.texShape=x,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),d,h,s);let I=[[h,d]],N=!0,E=this.runWebGLProgram(f,[b],o,I,N),A=this.texData.get(E.dataId);e.texShape=A.texShape,e.isPacked=A.isPacked,e.usage=A.usage,L().get("ENGINE_COMPILE_ONLY")?this.disposeData(E.dataId):(e.texture=A.texture,e.values=null,this.texData.delete(E.dataId)),this.disposeIntermediateTensorInfo(b),l&&(this.uploadWaitMs+=y.now()-c)}else{let m=this.acquireTexture(p,a,o,u);e.texture=m}}convertAndCacheOnCPU(t,e){let n=this.texData.get(t),{dtype:o}=n;return e!=null&&(n.values=$ot(e,o)),n.values}acquireTexture(t,e,n,o){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(t,e,o)}computeBytes(t,e){return t[0]*t[1]*y.bytesPerElement(e)}checkCompileCompletion(){for(let[,t]of Object.entries(this.binaryCache))this.checkCompletion_(t)}async checkCompileCompletionAsync(){let t=[];if(this.gpgpu.parallelCompilationExtension){for(let[,e]of Object.entries(this.binaryCache))t.push(this.checkCompletionAsync_(e));return Promise.all(t)}else{for(let[,e]of Object.entries(this.binaryCache)){let n=new Promise(o=>{try{this.checkCompletion_(e),o(!0)}catch(s){throw s}});t.push(n)}return Promise.all(t)}}async checkCompletionAsync_(t){return this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(t):(await kh(),this.checkCompletionAsync_(t))}checkCompletion_(t){if(this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)),this.gpgpu.gl.getShaderParameter(t.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(Fw(t.source,this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let t of Object.values(this.binaryCache)){this.gpgpu.buildVao(t.webGLProgram);let{variablesLocations:e,customUniformLocations:n,infLoc:o,nanLoc:s,outShapeLocation:i,outShapeStridesLocation:a,outTexShapeLocation:u}=n1(this.gpgpu,t.program,t.webGLProgram);t.variablesLocations=e,t.customUniformLocations=n,t.infLoc=o,t.nanLoc=s,t.outShapeLocation=i,t.outShapeStridesLocation=a,t.outTexShapeLocation=u}}createTensorFromGPUData(t,e,n){t.channels=t.channels||"RGBA";let{texture:o,height:s,width:i,channels:a}=t,u=Wn().backend;if(!u.gpgpu.gl.isTexture(o))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");let l=u.writeTexture(o,e,n,s,i,a);return Wn().makeTensorFromDataId(l,e,n,u)}};Qu.nextDataId=0;function $ot(r,t){if(t==="float32"||t==="complex64")return r;if(t==="int32"||t==="bool"){let e=t==="int32"?new Int32Array(r.length):new Uint8Array(r.length);for(let n=0;n<e.length;++n)e[n]=Math.round(r[n]);return e}else throw new Error(`Unknown dtype ${t}`)}var Gz="4.7.0";function Wz(){L().set("WEBGL_FORCE_F16_TEXTURES",!0)}Cu.isBrowser()&&im("webgl",()=>new Qu,2);var JDe={forceHalfFloat:Wz};var Md=`
| if (isnan(a)) return a;
| if (isnan(b)) return b;
| `;var On=class{constructor(t,e,n){this.variableNames=["A","B"],this.outputShape=S.assertAndGetBroadcastShape(e,n),this.enableShapeUniforms=de(this.outputShape.length),this.userCode=`
| float binaryOperation(float a, float b) {
| ${t}
| }
|
| void main() {
| float a = getAAtOutCoords();
| float b = getBAtOutCoords();
| setOutput(binaryOperation(a, b));
| }
| `}};var Qn=`
| result.r = isNaN.r ? NAN : result.r;
| result.g = isNaN.g ? NAN : result.g;
| result.b = isNaN.b ? NAN : result.b;
| result.a = isNaN.a ? NAN : result.a;
| `;var Jn=class{constructor(t,e,n,o=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=S.assertAndGetBroadcastShape(e,n);let s=this.outputShape.length;this.enableShapeUniforms=de(s);let i="";if(o)if(s===0||y.sizeFromShape(this.outputShape)===1)i=`
| result.y = 0.;
| result.z = 0.;
| result.w = 0.;
| `;else if(i=`
| ${zt(s)} coords = getOutputCoords();
| `,s===1)this.enableShapeUniforms?i+=`
| result.y = (coords + 1) >= outShape ? 0. : result.y;
| result.z = 0.;
| result.w = 0.;
| `:i+=`
| result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
| result.z = 0.;
| result.w = 0.;
| `;else{let u=er("coords",s);this.enableShapeUniforms?i+=`
| bool nextRowOutOfBounds =
| (${u[s-2]} + 1) >= outShape[${s} - 2];
| bool nextColOutOfBounds =
| (${u[s-1]} + 1) >= outShape[${s} - 1];
| result.y = nextColOutOfBounds ? 0. : result.y;
| result.z = nextRowOutOfBounds ? 0. : result.z;
| result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
| `:i+=`
| bool nextRowOutOfBounds =
| (${u[s-2]} + 1) >= ${this.outputShape[s-2]};
| bool nextColOutOfBounds =
| (${u[s-1]} + 1) >= ${this.outputShape[s-1]};
| result.y = nextColOutOfBounds ? 0. : result.y;
| result.z = nextRowOutOfBounds ? 0. : result.z;
| result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
| `}this.userCode=`
| vec4 binaryOperation(vec4 a, vec4 b) {
| ${t}
| }
|
| void main() {
| vec4 a = getAAtOutCoords();
| vec4 b = getBAtOutCoords();
|
| vec4 result = binaryOperation(a, b);
| ${i}
|
| setOutput(result);
| }
| `}};function rr(r){let{inputs:t,backend:e}=r,{x:n}=t;return e.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var Uz={kernelName:bo,backendName:"webgl",kernelFunc:rr};function Pn(r){let{inputs:t,backend:e}=r,{real:n,imag:o}=t,s=e.makeTensorInfo(n.shape,"complex64"),i=e.texData.get(s.dataId),a=rr({inputs:{x:n},backend:e}),u=rr({inputs:{x:o},backend:e});return i.complexTensorInfos={real:a,imag:u},s}var Hz={kernelName:zp,backendName:"webgl",kernelFunc:Pn};var v1="return (a < 0.) ? b * a : a;",S1=`
| vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
| return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
| `;function Rot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{alpha:s}=n,i=e.makeTensorInfo([],"float32",y.createScalarValue(s,"float32")),a=L().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Jn(S1,o.shape,i.shape):new On(v1,o.shape,i.shape),u=e.runWebGLProgram(a,[o,i],"float32");return e.disposeIntermediateTensorInfo(i),u}var qz={kernelName:vs,backendName:"webgl",kernelFunc:Rot};var N1="return (a < 0.) ? b * a : a;",k1=`
| vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
| return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
| `;function Fot(r){let{inputs:t,backend:e}=r,{x:n,alpha:o}=t,s=L().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Jn(k1,n.shape,o.shape):new On(N1,n.shape,o.shape);return e.runWebGLProgram(s,[n,o],"float32")}var Kz={kernelName:zs,backendName:"webgl",kernelFunc:Fot};var Vo="if (isnan(x)) return x;";function It({opSnippet:r,packedOpSnippet:t,cpuKernelImpl:e,dtype:n}){return({inputs:o,backend:s})=>{let{x:i}=o,a=s,u=n||i.dtype;if(a.shouldExecuteOnCPU([i])&&e!=null){let p=a.texData.get(i.dataId),m=e(p.values,u);return a.makeTensorInfo(i.shape,u,m)}let l=L().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,c;return l?c=new Fn(i.shape,t):c=new Br(i.shape,r),a.runWebGLProgram(c,[i],u)}}function ue({opSnippet:r,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:n=!1,cpuKernelImpl:o,dtype:s}){return({inputs:i,backend:a})=>{let{a:u,b:l}=i,c=a;if(n&&u.dtype==="complex64"){let d=c.texData.get(u.dataId),h=c.texData.get(l.dataId),[g,x]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(w=>{let[I,N]=w,E={dataId:I.dataId,dtype:I.dtype,shape:u.shape},A={dataId:N.dataId,dtype:N.dtype,shape:l.shape},D=new On(r,u.shape,l.shape);return c.runWebGLProgram(D,[E,A],ur(I.dtype,N.dtype))}),b=Pn({inputs:{real:g,imag:x},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(x),b}let p=s||ur(u.dtype,l.dtype);if((u.dtype==="string"||l.dtype==="string"||c.shouldExecuteOnCPU([u,l]))&&o!=null){let d=c.texData.get(u.dataId).values,h=c.texData.get(l.dataId).values,g=u.dtype==="string"?S.fromUint8ToStringArray(d):d,x=u.dtype==="string"?S.fromUint8ToStringArray(h):h,[b,w]=o(u.shape,l.shape,g,x,p),I=c.makeTensorInfo(w,p),N=c.texData.get(I.dataId);return N.values=b,I}let m=L().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,f;return m?f=new Jn(t,u.shape,l.shape,e):f=new On(r,u.shape,l.shape),c.runWebGLProgram(f,[u,l],p)}}function Wl(r,t=!1){if(r==="linear")return t?Mz:Dz;if(r==="relu")return t?zz:Rz;if(r==="elu")return t?Lz:$z;if(r==="relu6")return t?Bz:Fz;if(r==="prelu")return t?k1:N1;if(r==="leakyrelu")return t?S1:v1;if(r==="sigmoid")return t?Vz:Oz;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var Ld=class{constructor(t,e,n,o=!1,s=!1,i=!1,a=null,u=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=de(this.outputShape.length);let c=o?t[1]:t[2],p=Math.ceil(c/2),m=o?"i * 2, rc.y":"rc.y, i * 2",f=s?"rc.z, i * 2":"i * 2, rc.z",d=o?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],g="",x="";a&&(u?g=`vec4 activation(vec4 a) {
| vec4 b = getPreluActivationWeightsAtOutCoords();
| ${a}
| }`:l?g=`vec4 activation(vec4 a) {
| vec4 b = getLeakyreluAlphaAtOutCoords();
| ${a}
| }`:g=`vec4 activation(vec4 x) {
| ${a}
| }`,x="result = activation(result);");let b=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let w="rc.x",I="rc.x";t[0]<e[0]?w=`imod(rc.x, ${t[0]})`:e[0]<t[0]&&(I=`imod(rc.x, ${e[0]})`),this.userCode=`
| ${g}
| // Don't use uniform for sharedDimensionPacked for performance.
| const float sharedDimension = ${p}.0;
|
| vec4 dot2x2ARowBCol(ivec3 rc) {
| vec4 result = vec4(0);
| int batchA = ${w};
| int batchB = ${I};
| for (int i = 0; i < ${p}; i++) {
| vec4 a = getMatrixA(batchA, ${m});
| vec4 b = getMatrixB(batchB, ${f});
|
| // These swizzled products need to be separately added.
| // See: https://github.com/tensorflow/tfjs/issues/1735
| result += (${d[0]} * ${h[0]});
| result += (${d[1]} * ${h[1]});
| }
| return result;
| }
|
| void main() {
| ivec3 rc = getOutputCoords();
| vec4 result = dot2x2ARowBCol(rc);
|
| ${b}
|
| ${x}
|
| setOutput(result);
| }
| `}};var T1={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},mg=class{constructor(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=S.assertAndGetBroadcastShape(e,n),this.userCode=`
| float binaryOpComplex(
| float areal, float aimag, float breal, float bimag) {
| ${t}
| }
|
| void main() {
| float areal = getARealAtOutCoords();
| float aimag = getAImagAtOutCoords();
| float breal = getBRealAtOutCoords();
| float bimag = getBImagAtOutCoords();
| setOutput(binaryOpComplex(areal, aimag, breal, bimag));
| }
| `}};var jz="return a * b;";function fg(r){let{inputs:t,backend:e}=r,{a:n,b:o}=t,s=S.upcastType(n.dtype,o.dtype);if(n.dtype==="complex64"){let a=e.texData.get(n.dataId),u=e.texData.get(o.dataId),l=new mg(T1.REAL,n.shape,o.shape),c=new mg(T1.IMAG,n.shape,o.shape),p=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:n.shape},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:u.complexTensorInfos.real.dataId,dtype:u.complexTensorInfos.real.dtype,shape:o.shape},{dataId:u.complexTensorInfos.imag.dataId,dtype:u.complexTensorInfos.imag.dtype,shape:o.shape}],m=e.runWebGLProgram(l,p,"float32"),f=e.runWebGLProgram(c,p,"float32"),d=Pn({inputs:{real:m,imag:f},backend:e});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),d}if(e.shouldExecuteOnCPU([n,o])){let a=e.texData.get(n.dataId),u=e.texData.get(o.dataId),[l,c]=nz(n.shape,o.shape,a.values,u.values,s),p=e.makeTensorInfo(c,s),m=e.texData.get(p.dataId);return m.values=l,p}let i;return L().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Jn(jz,n.shape,o.shape):i=new On(jz,n.shape,o.shape),e.runWebGLProgram(i,[n,o],s)}var Xz={kernelName:Os,backendName:"webgl",kernelFunc:fg};function Yz(r,t,e){let n=[Vl(r.shape),...Gl(r.shape)],o={dtype:r.dtype,shape:n,dataId:r.dataId},s=[Vl(t),...Gl(t)],i=new Pd(s,n),a=!0,u=[n],l=e.runWebGLProgram(i,[o],r.dtype,u,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function rt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{shape:s}=n,i=e,a=y.sizeFromShape(o.shape),u=y.inferFromImplicitShape(s,a),l=y.sizeFromShape(u);y.assert(a===l,()=>`The new shape (${u}) has ${l} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);let c=i.texData.get(o.dataId);return c.isPacked&&!Ju(o.shape,u)&&!(c.texture!==null&&Ju(c.shape,u))?Yz(o,u,i):(i.incRef(o.dataId),{dataId:o.dataId,shape:u,dtype:o.dtype})}var Zz={kernelName:Ui,backendName:"webgl",kernelFunc:rt};var dg=class{constructor(t,e){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:i}=t;this.outputShape=[o,i];let a=Math.floor(n/4)*4,u=n%4,l="sumValue += dot(values, ones);";if(e!=null){let p=1/e;l=`sumValue += dot(values * ${y.isInt(p)?p.toPrecision(2):p}, ones);`}let c="";s%n>0&&(c=`
| if (inIdx < 0 || inIdx >= ${s}) {
| return 0.0;
| }
| `),this.userCode=`
| const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
| float getValue(int batch, int inIdx) {
| ${c}
| return getX(batch, inIdx);
| }
|
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int outIdx = coords[1];
| int inOffset = outIdx * ${n};
|
| float sumValue = 0.0;
|
| for (int i = 0; i < ${a}; i += 4) {
| int inIdx = inOffset + i;
| vec4 values = vec4(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| getValue(batch, inIdx + 2),
| getValue(batch, inIdx + 3)
| );
|
| ${l}
| }
|
| int inIdx = inOffset + ${a};
| if (${u===1}) {
| vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
| ${l}
| } else if (${u===2}) {
| vec4 values = vec4(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1), 0.0, 0.0);
|
| ${l}
| } else if (${u===3}) {
| vec4 values = vec4(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| getValue(batch, inIdx + 2), 0.0);
|
| ${l}
| }
| setOutput(sumValue);
| }
| `}};var nI=class{constructor(t,e){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:i}=t;this.outputShape=[o,i];let a="0.0",u="";e==="prod"?a="1.0":e==="min"?(a="1.0 / 1e-20",u="min"):e==="max"&&(a="-1.0 / 1e-20",u="max");let l=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="sum"?l="sumValue":e==="prod"?l="prodValue":e==="all"?l="allValue":e==="any"&&(l="anyValue");let c=Math.floor(n/4)*4,p=n%4,m=`
| if (${e==="sum"}) {
| sumValue += dot(values, ones);
| } else if (${e==="prod"}) {
| vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
| prodValue *= tmp[0] * tmp[1];
| } else {
| minMaxValue = ${u}(values, minMaxValue);
| if (${e==="min"} || ${e==="max"}) {
| minMaxValue = ${u}(values, minMaxValue);
| bvec4 isNaN = isnan(values);
| if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
| minMaxValue = vec4(NAN);
| }
| }
| }
| `,f="vec4";e==="all"?(a="1.0",m=`
| bool reducedAllValue = all(values);
| float floatedReducedAllValue = float(reducedAllValue);
| allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
| `,f="bvec4"):e==="any"&&(a="0.0",m=`
| bool reducedAnyValue = any(values);
| float floatedReducedAnyValue = float(reducedAnyValue);
| anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
| `,f="bvec4");let d="";s%n>0&&(d=`
| if (inIdx < 0 || inIdx >= ${s}) {
| return initializationValue;
| }
| `),this.userCode=`
| const float initializationValue = ${a};
| const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
| float getValue(int batch, int inIdx) {
| ${d}
| return getX(batch, inIdx);
| }
|
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int outIdx = coords[1];
| int inOffset = outIdx * ${n};
|
| vec4 minMaxValue = vec4(${a});
| float prodValue = 1.0;
| float sumValue = 0.0;
| float allValue = 1.0;
| float anyValue = 0.0;
|
| for (int i = 0; i < ${c}; i += 4) {
| int inIdx = inOffset + i;
| ${f} values = ${f}(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| getValue(batch, inIdx + 2),
| getValue(batch, inIdx + 3)
| );
|
| ${m}
| }
|
| int inIdx = inOffset + ${c};
| if (${p===1}) {
| ${f} values = ${f}(
| getValue(batch, inIdx),
| initializationValue,
| initializationValue,
| initializationValue
| );
|
| ${m}
| } else if (${p===2}) {
| ${f} values = ${f}(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| initializationValue,
| initializationValue
| );
|
| ${m}
| } else if (${p===3}) {
| ${f} values = ${f}(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| getValue(batch, inIdx + 2),
| initializationValue
| );
|
| ${m}
| }
| setOutput(${l});
| }
| `}};function Pot(r){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let e=t.length?t[t.length-1].outSize:r[1],n=S.computeOptimalWindowSize(e);t.push({inSize:e,windowSize:n,outSize:Math.ceil(e/n)})}return t}function to(r,t,e,n){let o=Pot(r.shape),s=r;for(let i=0;i<o.length;i++){let{inSize:a,windowSize:u,outSize:l}=o[i],c,p;e==="mean"?c=i===0?new dg({windowSize:u,inSize:a,batchSize:r.shape[0],outSize:l},a):new dg({windowSize:u,inSize:a,batchSize:r.shape[0],outSize:l}):c=new nI({windowSize:u,inSize:a,batchSize:r.shape[0],outSize:l},e),p=s,s=n.runWebGLProgram(c,[s],t),p.dataId!==r.dataId&&n.disposeIntermediateTensorInfo(p)}return s}var oI=class{constructor(t,e){this.variableNames=["A"];let n=new Array(t.length);for(let i=0;i<n.length;i++)n[i]=t[e[i]];this.outputShape=n,this.rank=n.length;let o=zt(this.rank),s=Mot(e);this.userCode=`
| void main() {
| ${o} resRC = getOutputCoords();
| setOutput(getA(${s}));
| }
| `}};function Mot(r){let t=r.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let o=0;o<r.length;o++)n[r[o]]=e[o];return n.join()}var sI=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(t.length);for(let c=0;c<n.length;c++)n[c]=t[e[c]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let o=zt(this.rank),s=I1("rc",this.rank),i=new Array(this.rank);for(let c=0;c<e.length;c++)i[e[c]]=s[c];let a=`vec2(${i.slice(-2).join()})`,u=`++${s[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${i.join()}), ${a})`;this.userCode=`
| void main() {
| ${o} rc = getOutputCoords();
| vec4 result = vec4(0.);
| result[0] = ${l};
| if(${u}) {
| result[1] = ${l};
| }
| --${s[this.rank-1]};
| if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
| result[2] = ${l};
| if(${u}) {
| result[3] = ${l};
| }
| }
| setOutput(result);
| }
| `}};function tc(r,t,e){let n=L().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new sI(r.shape,t):new oI(r.shape,t);return e.runWebGLProgram(n,[r],r.dtype)}function Jz(r,t,e,n){let o=t,s=r.shape.length,i=y.parseAxisParam(o,r.shape),a=i,u=S.getAxesPermutation(a,s),l=u!=null,c=r;l&&(c=tc(r,u,n),a=S.getInnerMostAxes(a.length,s)),S.assertAxesAreInnerMostDims("sum",a,s);let[p,m]=S.computeOutAndReduceShapes(c.shape,a),f=p;e&&(f=S.expandShapeToKeepDim(p,i));let d=y.sizeFromShape(m),g=y.sizeFromShape(r.shape)/d,x=rt({inputs:{x:c},attrs:{shape:[g,d]},backend:n}),b=xc(r.dtype),w=to(x,b,"sum",n),I=rt({inputs:{x:w},attrs:{shape:f},backend:n});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(w),l&&n.disposeIntermediateTensorInfo(c),I}function Cp(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;return Jz(o,s,i,e)}var Qz={kernelName:ri,backendName:"webgl",kernelFunc:Cp};function Pe(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{perm:s}=n,i=e,a=o.shape.length,u=new Array(a);for(let c=0;c<u.length;c++)u[c]=o.shape[s[c]];let l;if(i.shouldExecuteOnCPU([o])){let p=i.texData.get(o.dataId).values,m=Ip(p,o.shape,o.dtype,s,u);l=i.makeTensorInfo(u,o.dtype);let f=i.texData.get(l.dataId);f.values=m}else l=tc(o,s,i);return l}var t3={kernelName:uo,backendName:"webgl",kernelFunc:Pe};var _1=1e3;function vp({a:r,b:t,transposeA:e,transposeB:n,backend:o,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:a=0,activation:u=null}){let l=r.shape.length,c=t.shape.length,p=e?r.shape[l-2]:r.shape[l-1],m=n?t.shape[c-1]:t.shape[c-2],f=e?r.shape[l-1]:r.shape[l-2],d=n?t.shape[c-2]:t.shape[c-1],h=r.shape.slice(0,-2),g=t.shape.slice(0,-2),x=y.sizeFromShape(h),b=y.sizeFromShape(g),I=Hr.assertAndGetBroadcastShape(r.shape.slice(0,-2),t.shape.slice(0,-2)).concat([f,d]);y.assert(p===m,()=>`Error in matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${r.shape} and ${t.shape} and transposeA=${e} and transposeB=${n} must match.`);let N=e?[x,p,f]:[x,f,p],E=n?[b,d,m]:[b,m,d],A=rt({inputs:{x:r},backend:o,attrs:{shape:N}}),D=rt({inputs:{x:t},backend:o,attrs:{shape:E}}),F=[A,D],P=Math.max(x,b),V=e?A.shape[1]:A.shape[2],G=s!=null,W=i!=null,q=u==="leakyrelu",H=u!=null?Wl(u,!0):null,K=G||W||q||H!=null,X;if((f===1||d===1)&&V>_1&&K===!1){let et=A,nt=D;e&&(et=Pe({inputs:{x:A},backend:o,attrs:{perm:[0,2,1]}}),F.push(et)),n&&(nt=Pe({inputs:{x:D},backend:o,attrs:{perm:[0,2,1]}}),F.push(nt));let st=d!==1,at=d===1,ot=et;st&&(ot=rt({inputs:{x:et},backend:o,attrs:{shape:[P,V,1]}}),F.push(ot));let it=d===1?2:1,mt=nt;at&&(mt=rt({inputs:{x:nt},backend:o,attrs:{shape:[P,1,V]}}),F.push(mt));let gt=fg({inputs:{a:ot,b:mt},backend:o});X=Cp({inputs:{x:gt},backend:o,attrs:{axis:it,keepDims:!0}}),F.push(gt)}else{let et=ur(r.dtype,t.dtype),nt=new Ld(N,E,[P,f,d],e,n,G,H,W,q),st=[A,D];if(s!=null&&st.push(s),W&&st.push(i),q){let at=o.makeTensorInfo([],"float32",y.createScalarValue(a,"float32"));st.push(at),F.push(at)}X=o.runWebGLProgram(nt,st,et)}let Z=rt({inputs:{x:X},backend:o,attrs:{shape:I}});F.push(X);for(let et of F)o.disposeIntermediateTensorInfo(et);return Z}function Lot(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=n;return vp({a:o,b:s,transposeA:u,transposeB:l,backend:e,bias:i,preluActivationWeights:a,leakyreluAlpha:p,activation:c})}var e3={kernelName:Zi,backendName:"webgl",kernelFunc:Lot};var r3="return abs(x);";function zot(r){let{inputs:t,backend:e}=r,{x:n}=t;if(e.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=e.texData.get(n.dataId),i=Zw(s.values);return e.makeTensorInfo(n.shape,n.dtype,i)}let o;return L().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Fn(n.shape,r3):o=new Br(n.shape,r3),e.runWebGLProgram(o,[n],n.dtype)}var n3={kernelName:$i,backendName:"webgl",kernelFunc:zot};var Bot=yr+`
| if (abs(x) > 1.) {
| return NAN;
| }
| return acos(x);
| `,Vot=It({opSnippet:Bot}),o3={kernelName:qo,backendName:"webgl",kernelFunc:Vot};var Got=yr+`
| if (x < 1.0) return NAN;
| return log(x + sqrt(x * x - 1.0));`,Wot=It({opSnippet:Got}),s3={kernelName:Ko,backendName:"webgl",kernelFunc:Wot};var i3="return a + b;",Uot=ue({opSnippet:i3,packedOpSnippet:i3,supportsComplex:!0,cpuKernelImpl:PL}),a3={kernelName:ao,backendName:"webgl",kernelFunc:Uot};var iI=class{constructor(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((s,i)=>`T${i}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let o=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
| void main() {
| ${n.join(`
| `)}
|
| float result = ${o};
| setOutput(result);
| }
| `}};var aI=class{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((s,i)=>`T${i}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let o=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
| void main() {
| ${n.join(`
| `)}
|
| vec4 result = ${o};
| setOutput(result);
| }
| `}};function lI(r){let{inputs:t,backend:e}=r,n=t;if(n.length===1)return rr({inputs:{x:n[0]},backend:e});if(n.length>L().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(n.length/2),l=lI({inputs:n.slice(0,u),backend:e}),c=lI({inputs:n.slice(u),backend:e});return lI({inputs:[l,c],backend:e})}let o=n.map(u=>u.dtype).reduce((u,l)=>ur(u,l)),s=n.map(u=>u.shape),a=L().getBool("WEBGL_PACK")?new aI(n[0].shape,s):new iI(n[0].shape,s);return e.runWebGLProgram(a,n,o)}var l3={kernelName:jo,backendName:"webgl",kernelFunc:lI};function Hot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=y.parseAxisParam(s,o.shape),l=u,c=S.getAxesPermutation(l,a),p=o;c!=null&&(p=Pe({inputs:{x:o},backend:e,attrs:{perm:c}}),l=S.getInnerMostAxes(l.length,a)),S.assertAxesAreInnerMostDims("all",l,a);let[m,f]=S.computeOutAndReduceShapes(p.shape,l),d=y.sizeFromShape(f),h=rt({inputs:{x:p},backend:e,attrs:{shape:[-1,d]}}),g=to(h,h.dtype,"all",e),x;if(i){let b=S.expandShapeToKeepDim(m,u);x=rt({inputs:{x:g},backend:e,attrs:{shape:b}})}else x=rt({inputs:{x:g},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),c!=null&&e.disposeIntermediateTensorInfo(p),x}var u3={kernelName:Ra,backendName:"webgl",kernelFunc:Hot};function qot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=y.parseAxisParam(s,o.shape),l=u,c=S.getAxesPermutation(l,a),p=o;c!=null&&(p=Pe({inputs:{x:o},backend:e,attrs:{perm:c}}),l=S.getInnerMostAxes(l.length,a)),S.assertAxesAreInnerMostDims("any",l,a);let[m,f]=S.computeOutAndReduceShapes(p.shape,l),d=y.sizeFromShape(f),h=rt({inputs:{x:p},backend:e,attrs:{shape:[-1,d]}}),g=to(h,h.dtype,"any",e),x;if(i){let b=S.expandShapeToKeepDim(m,u);x=rt({inputs:{x:g},backend:e,attrs:{shape:b}})}else x=rt({inputs:{x:g},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),c!=null&&e.disposeIntermediateTensorInfo(p),x}var c3={kernelName:Fa,backendName:"webgl",kernelFunc:qot};var uI=class{constructor(t,e,n){this.variableNames=["A"];let{windowSize:o,batchSize:s,outSize:i}=t;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,i];let a=e==="max"?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int outIdx = coords[1];
| int inOffset = outIdx * ${o};
|
| int bestIndex = inOffset;
| float bestValue = getA(batch, bestIndex);
|
| for (int i = 0; i < ${o}; i++) {
| int inIdx = ${u};
| float candidate = getA(batch, inIdx);
| if (candidate ${a} bestValue) {
| bestValue = candidate;
| bestIndex = inIdx;
| }
| }
| setOutput(float(bestIndex));
| }
| `}};var cI=class{constructor(t,e,n,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,y.assert(t.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=t[t.length-1],i=Math.ceil(s/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),o||this.variableNames.push("bestIndicesA");let a=this.outputShape,u=a.length,l=zt(u),c=er("coords",u),p,m;if(i===1){m=u+1;let D=zt(m);p=`
| ${D} sourceLocR = ${D}(${c.join()}, 0);
| ++${c[u-1]};
| ${D} sourceLocG = ${D}(${c.join()}, 0);
| ++${c[u-2]};
| ${D} sourceLocA = ${D}(${c.join()}, 0);
| --${c[u-1]};
| ${D} sourceLocB = ${D}(${c.join()}, 0);
| --${c[u-2]};`}else m=u,p=`
| ${l} sourceLocR = coords;
| ++${c[u-1]};
| ${l} sourceLocG = coords;
| ++${c[u-2]};
| ${l} sourceLocA = coords;
| --${c[u-1]};
| ${l} sourceLocB = coords;
| --${c[u-2]};`;let f=["x","y","z","w","u","v"].slice(0,m),d="."+f[m-1],h=f.map(D=>"int "+D),g=er("sourceLocR",m-1).concat("inIdx.r"),x=er("sourceLocG",m-1).concat("inIdx.g"),b=er("sourceLocB",m-1).concat("inIdx.b"),w=er("sourceLocA",m-1).concat("inIdx.a"),I=n==="max"?"greaterThan":"lessThan",N=o?"":`
| inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
| getBestIndicesAChannel(${x.join()}),
| getBestIndicesAChannel(${b.join()}),
| getBestIndicesAChannel(${w.join()})));`,E=`vec4(
| getAChannel(${g.join()}),
| hasNextCol ? getAChannel(${x.join()}) : 0.,
| hasNextRow ? getAChannel(${b.join()}) : 0.,
| hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,A=o?"":`
| float getBestIndicesAChannel(${h.join()}) {
| return getChannel(getBestIndicesA(${f.join()}),
| vec2(${f.slice(-2).join()}));
| }`;this.userCode=`
| float getAChannel(${h.join()}) {
| return getChannel(getA(${f.join()}),
| vec2(${f.slice(-2).join()}));
| }
| ${A}
| void main() {
| ${l} coords = getOutputCoords();
| bool hasNextCol = ${c[u-1]} < ${a[u-1]-1};
| bool hasNextRow = ${c[u-2]} < ${a[u-2]-1};
| ${p}
| ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
| sourceLocB${d}, sourceLocA${d}) * ${e};
| ivec4 inIdx = srcIdx;
| vec4 bestIndex = vec4(inIdx);
| vec4 bestValue = ${E};
|
| for (int i = 0; i < ${e}; i++) {
| inIdx = srcIdx;
| ${N}
| vec4 candidate = ${E};
| bvec4 nan = isnan(candidate);
| bvec4 replace = bvec4(
| vec4(${I}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
| bestValue = vec4(replace.x ? candidate.x : bestValue.x,
| replace.y ? candidate.y : bestValue.y,
| replace.z ? candidate.z : bestValue.z,
| replace.w ? candidate.w : bestValue.w);
| bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
| srcIdx++;
| }
| setOutput(bestIndex);
| }
| `}};function p3(r,t,e,n=null){let o=t.shape[0],s=t.shape[1];n!=null&&(o=n.shape[0],s=n.shape[1]);let i=S.computeOptimalWindowSize(s),a={windowSize:i,inSize:s,batchSize:o,outSize:Math.ceil(s/i)},u=new uI(a,e,n==null),l=[t];n!=null&&l.push(n);let c=r.runWebGLProgram(u,l,"int32");if(c.shape[1]===1)return c;let p=p3(r,t,e,c);return r.disposeIntermediateTensorInfo(c),p}function m3(r,t,e,n=null){let o=n!=null?n.shape:t.shape,s=o[o.length-1],i=S.computeOptimalWindowSize(s),a=new cI(o,i,e,n==null),u=n==null?[t]:[t,n],l=r.runWebGLProgram(a,u,"int32");if(l.shape.length===t.shape.length){let c=m3(r,t,e,l);return r.disposeIntermediateTensorInfo(l),c}return l}function pI(r,t,e,n){let o=[e];if(S.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),o,t.shape.length),!L().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=r.texData.get(t.dataId),a=i!==null&&i.isPacked,u=t;a&&(u=r.unpackTensor(t),s.push(u));let[l,c]=S.computeOutAndReduceShapes(u.shape,o),p=y.sizeFromShape(c),m=rt({inputs:{x:u},backend:r,attrs:{shape:[-1,p]}});s.push(m);let f=p3(r,m,n);s.push(f);let d=rt({inputs:{x:f},backend:r,attrs:{shape:l}});return s.forEach(h=>r.disposeIntermediateTensorInfo(h)),d}return m3(r,t,n)}function Kot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s}=n,i=y.parseAxisParam(s,o.shape),a=S.getAxesPermutation(i,o.shape.length),u=o,l=[];a!=null&&(u=Pe({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(u),i=S.getInnerMostAxes(i.length,u.shape.length)),S.assertAxesAreInnerMostDims("argMax",[i[0]],u.shape.length);let c=pI(e,u,i[0],"max");return l.forEach(p=>e.disposeIntermediateTensorInfo(p)),c}var f3={kernelName:Ri,backendName:"webgl",kernelFunc:Kot};function jot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s}=n,i=y.parseAxisParam(s,o.shape),a=S.getAxesPermutation(i,o.shape.length),u=o,l=[];a!=null&&(u=Pe({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(u),i=S.getInnerMostAxes(i.length,u.shape.length)),S.assertAxesAreInnerMostDims("argMin",[i[0]],u.shape.length);let c=pI(e,u,i[0],"min");return l.forEach(p=>e.disposeIntermediateTensorInfo(p)),c}var d3={kernelName:Fi,backendName:"webgl",kernelFunc:jot};var Xot=yr+`
| if (abs(x) > 1.) {
| return NAN;
| }
| return asin(x);
| `,Yot=It({opSnippet:Xot}),h3={kernelName:Xo,backendName:"webgl",kernelFunc:Yot};var Zot=yr+"return log(x + sqrt(x * x + 1.0));",Jot=It({opSnippet:Zot}),g3={kernelName:Yo,backendName:"webgl",kernelFunc:Jot};var Qot=yr+`
| return atan(x);
| `,tst=It({opSnippet:Qot}),x3={kernelName:Zo,backendName:"webgl",kernelFunc:tst};var est=Md+`
| return atan(a, b);
| `,rst=`
| vec4 result = atan(a, b);
| bvec4 isNaNA = isnan(a);
| bvec4 isNaNB = isnan(b);
| bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
| `+Qn+`
| return result;
| `,nst=ue({opSnippet:est,packedOpSnippet:rst}),y3={kernelName:Qo,backendName:"webgl",kernelFunc:nst};var ost=yr+`
| if ((x < -1.0) || (x > 1.0)) return NAN;
| return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,sst=It({opSnippet:ost}),b3={kernelName:Jo,backendName:"webgl",kernelFunc:sst};var Ti=class{constructor(t,e,n,o=!1,s=!1){if(this.variableNames=["x"],e==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let i=t.filterWidth,a=t.strideHeight,u=t.strideWidth,l=t.dilationHeight,c=t.dilationWidth,p=t.effectiveFilterHeight,m=t.effectiveFilterWidth,f=t.padInfo.top,d=t.padInfo.left;this.outputShape=t.outShape;let h=e==="avg",g=`((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`,x=`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`,b="0.0";if(h||(b="-1.0 / 1e-20"),n){let D=">=";this.userCode=`
| const ivec2 strides = ivec2(${a}, ${u});
| const ivec2 pads = ivec2(${f}, ${d});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords[0];
| int d = coords[3];
|
| ivec2 xRCCorner = coords.yz * strides - pads;
| int xRCorner = xRCCorner.x;
| int xCCorner = xRCCorner.y;
|
| // max/min x(?, ?, d) to get y(yR, yC, d).
| // ? = to be determined
| float minMaxValue = 0.0;
| float minMaxValueFound = 0.0;
| int minMaxPosition = 0;
| float avgValue = 0.0;
|
| for (int wR = 0; wR < ${p};
| wR += ${l}) {
| int xR = xRCorner + wR;
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int wC = 0; wC < ${m};
| wC += ${c}) {
| int xC = xCCorner + wC;
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| float value = getX(batch, xR, xC, d);
|
| // If a min / max value has already been found, use it. If not,
| // use the current value.
| float currMinMaxValue = mix(
| value, minMaxValue, minMaxValueFound);
| if (value ${D} currMinMaxValue) {
| minMaxValue = value;
| minMaxValueFound = 1.0;
| minMaxPosition = ${o?s?g:x:`wR * ${m} + wC`};
| }
| }
| }
| setOutput(float(minMaxPosition));
| }
| `;return}let w="max",I=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(I="avgValue / max(count, 1.0)");let N=Math.floor(i/4)*4,E=i%4,A=`
| if (${h}) {
| avgValue += dot(values, ones);
| } else {
| minMaxValue = ${w}(values, minMaxValue);
| }
| `;this.userCode=`
| const ivec2 strides = ivec2(${a}, ${u});
| const ivec2 pads = ivec2(${f}, ${d});
| const float initializationValue = ${b};
| const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
| float count = 0.0;
|
| float getValue(int batch, int xR, int xC, int d) {
| if (xC < 0 || xC >= ${t.inWidth}) {
| return initializationValue;
| }
| count += 1.0;
| return getX(batch, xR, xC, d);
| }
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords[0];
| int d = coords[3];
|
| ivec2 xRCCorner = coords.yz * strides - pads;
| int xRCorner = xRCCorner.x;
| int xCCorner = xRCCorner.y;
|
| // max/min x(?, ?, d) to get y(yR, yC, d).
| // ? = to be determined
| vec4 minMaxValue = vec4(${b});
| float avgValue = 0.0;
| count = 0.0;
|
| for (int wR = 0; wR < ${p};
| wR += ${l}) {
| int xR = xRCorner + wR;
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int wC = 0; wC < ${N}; wC += 4) {
| int xC = xCCorner + wC * ${c};
|
| vec4 values = vec4(
| getValue(batch, xR, xC, d),
| getValue(batch, xR, xC + ${c}, d),
| getValue(batch, xR, xC + 2 * ${c}, d),
| getValue(batch, xR, xC + 3 * ${c}, d)
| );
|
| ${A}
| }
|
| int xC = xCCorner + ${N};
| if (${E===1}) {
| vec4 values = vec4(
| getValue(batch, xR, xC, d),
| initializationValue,
| initializationValue,
| initializationValue
| );
|
| ${A}
| } else if (${E===2}) {
| vec4 values = vec4(
| getValue(batch, xR, xC, d),
| getValue(batch, xR, xC + ${c}, d),
| initializationValue,
| initializationValue
| );
|
| ${A}
| } else if (${E===3}) {
| vec4 values = vec4(
| getValue(batch, xR, xC, d),
| getValue(batch, xR, xC + ${c}, d),
| getValue(batch, xR, xC + 2 * ${c}, d),
| initializationValue
| );
|
| ${A}
| }
| }
| setOutput(${I});
| }
| `}},ec=class{constructor(t,e,n,o=!1,s=!1){if(this.variableNames=["x"],e==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let i=t.filterWidth,a=t.strideDepth,u=t.strideHeight,l=t.strideWidth,c=t.dilationDepth,p=t.dilationHeight,m=t.dilationWidth,f=t.effectiveFilterDepth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,g=t.padInfo.front,x=t.padInfo.top,b=t.padInfo.left;this.outputShape=t.outShape;let w=e==="avg",I="0.0";if(w||(I="-1.0 / 1e-20"),n){let P=">=";this.userCode=`
| const ivec3 strides =
| ivec3(${a}, ${u}, ${l});
| const ivec3 pads = ivec3(${g}, ${x}, ${b});
|
| void main() {
| ivec5 coords = getOutputCoords();
| int batch = coords.x;
| int ch = coords.u;
|
| ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
| int xDCorner = xCorner.x;
| int xRCorner = xCorner.y;
| int xCCorner = xCorner.z;
|
| // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
| // ? = to be determined
| float minMaxValue = 0.0;
| float minMaxValueFound = 0.0;
| int minMaxPosition = 0;
|
| for (int wD = 0; wD < ${f};
| wD += ${c}) {
| int xD = xDCorner + wD;
|
| if (xD < 0 || xD >= ${t.inDepth}) {
| continue;
| }
|
| for (int wR = 0; wR < ${d};
| wR += ${p}) {
| int xR = xRCorner + wR;
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int wC = 0; wC < ${h};
| wC += ${m}) {
| int xC = xCCorner + wC;
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| float value = getX(batch, xD, xR, xC, ch);
|
| // If a min / max value has already been found, use it. If not,
| // use the current value.
| float currMinMaxValue = mix(
| value, minMaxValue, minMaxValueFound);
| if (value ${P} currMinMaxValue) {
| minMaxValue = value;
| minMaxValueFound = 1.0;
| minMaxPosition = ${o?s?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${d} * ${h} +
| wR * ${h} + wC`};
| }
| }
| }
| }
| setOutput(float(minMaxPosition));
| }
| `;return}let N="max",E=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(E="avgValue / max(count, 1.0)");let A=Math.floor(i/4)*4,D=i%4,F=`
| if (${w}) {
| avgValue += dot(values, ones);
| } else {
| minMaxValue = ${N}(values, minMaxValue);
| }
| `;this.userCode=`
| const ivec3 strides =
| ivec3(${a}, ${u}, ${l});
| const ivec3 pads = ivec3(${g}, ${x}, ${b});
| const float initializationValue = ${I};
| const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
| float count = 0.0;
|
| float getValue(int batch, int xD, int xR, int xC, int ch) {
| if (xC < 0 || xC >= ${t.inWidth}) {
| return initializationValue;
| }
| count += 1.0;
| return getX(batch, xD, xR, xC, ch);
| }
|
| void main() {
| ivec5 coords = getOutputCoords();
| int batch = coords.x;
| int ch = coords.u;
|
| ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
| int xDCorner = xCorner.x;
| int xRCorner = xCorner.y;
| int xCCorner = xCorner.z;
|
| // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
| // ? = to be determined
| vec4 minMaxValue = vec4(${I});
| float avgValue = 0.0;
| count = 0.0;
|
| for (int wD = 0; wD < ${f};
| wD += ${c}) {
| int xD = xDCorner + wD;
|
| if (xD < 0 || xD >= ${t.inDepth}) {
| continue;
| }
|
| for (int wR = 0; wR < ${d};
| wR += ${p}) {
| int xR = xRCorner + wR;
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int wC = 0; wC < ${A}; wC += 4) {
| int xC = xCCorner + wC * ${m};
|
| vec4 values = vec4(
| getValue(batch, xD, xR, xC, ch),
| getValue(batch, xD, xR, xC + ${m}, ch),
| getValue(batch, xD, xR, xC + 2 * ${m}, ch),
| getValue(batch, xD, xR, xC + 3 * ${m}, ch)
| );
|
| ${F}
| }
|
| int xC = xCCorner + ${A};
| if (${D===1}) {
| vec4 values = vec4(
| getValue(batch, xD, xR, xC, ch),
| initializationValue,
| initializationValue,
| initializationValue
| );
|
| ${F}
| } else if (${D===2}) {
| vec4 values = vec4(
| getValue(batch, xD, xR, xC, ch),
| getValue(batch, xD, xR, xC + ${m}, ch),
| initializationValue,
| initializationValue
| );
|
| ${F}
| } else if (${D===3}) {
| vec4 values = vec4(
| getValue(batch, xD, xR, xC, ch),
| getValue(batch, xD, xR, xC + ${m}, ch),
| getValue(batch, xD, xR, xC + 2 * ${m}, ch),
| initializationValue
| );
|
| ${F}
| }
| }
| }
| setOutput(${E});
| }
| `}};function ist(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;Ni(o,"avgPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=n,l=1;y.assert(S.eitherStridesOrDilationsAreOne(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=S.computePool2DInfo(o.shape,s,i,l,a,u);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return rr({inputs:{x:o},backend:e});let p=new Ti(c,"avg",!1);return e.runWebGLProgram(p,[o],"float32")}var w3={kernelName:ts,backendName:"webgl",kernelFunc:ist};function ast(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u,dataFormat:l}=n,c=[1,1,1],p=S.computePool3DInfo(o.shape,s,i,c,a,u,l),m=new ec(p,"avg",!1);return e.runWebGLProgram(m,[o],"float32")}var I3={kernelName:Oi,backendName:"webgl",kernelFunc:ast};var mI=class{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterHeight,n=t.filterWidth,o=t.strideHeight,s=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=u-1-t.padInfo.top,p=l-1-t.padInfo.left,m=1/(e*n);this.userCode=`
| const ivec2 pads = ivec2(${c}, ${p});
| const float avgMultiplier = float(${m});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
|
| ivec2 dyRCCorner = coords.yz - pads;
| int dyRCorner = dyRCCorner.x;
| int dyCCorner = dyRCCorner.y;
|
| // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
| for (int wR = 0; wR < ${u};
| wR += ${i}) {
| float dyR = float(dyRCorner + wR) / ${o}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| for (int wC = 0; wC < ${l};
| wC+= ${a}) {
| float dyC = float(dyCCorner + wC) / ${s}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| float dyValue = getDy(b, idyR, idyC, d);
|
| dotProd += dyValue * avgMultiplier;
| }
| }
| setOutput(dotProd);
| }
| `}},fI=class{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterDepth,n=t.filterHeight,o=t.filterWidth,s=t.strideDepth,i=t.strideHeight,a=t.strideWidth,u=t.dilationDepth,l=t.dilationHeight,c=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=p-1-t.padInfo.front,h=m-1-t.padInfo.top,g=f-1-t.padInfo.left,x=1/(e*n*o);this.userCode=`
| const ivec3 pads = ivec3(${d}, ${h}, ${g});
| const float avgMultiplier = float(${x});
|
| void main() {
| ivec5 coords = getOutputCoords();
| int batch = coords.x;
| int ch = coords.u;
|
| ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
| int dyDCorner = dyCorner.x;
| int dyRCorner = dyCorner.y;
| int dyCCorner = dyCorner.z;
|
| // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
| // dx(xD, xR, xC, ch).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
|
| for (int wD = 0; wD < ${p};
| wD += ${u}) {
| float dyD = float(dyDCorner + wD) / ${s}.0;
|
| if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
| continue;
| }
| int idyD = int(dyD);
|
| for (int wR = 0; wR < ${m};
| wR += ${l}) {
| float dyR = float(dyRCorner + wR) / ${i}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
| fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| for (int wC = 0; wC < ${f};
| wC += ${c}) {
| float dyC = float(dyCCorner + wC) / ${a}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
| dotProd += dyValue * avgMultiplier;
| }
| }
| }
| setOutput(dotProd);
| }
| `}};function lst(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s,{filterSize:a,strides:u,pad:l,dimRoundingMode:c}=n,p=[1,1,1],m=S.computePool3DInfo(i.shape,a,u,p,l,c),f=new fI(m);return e.runWebGLProgram(f,[o],i.dtype)}var C3={kernelName:Jl,backendName:"webgl",kernelFunc:lst};function ust(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s;Ni([o,s],"avgPoolGrad");let{filterSize:a,strides:u,pad:l}=n,c=S.computePool2DInfo(i.shape,a,u,1,l),p=new mI(c);return e.runWebGLProgram(p,[o],i.dtype)}var v3={kernelName:Zl,backendName:"webgl",kernelFunc:ust};function cst(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s}=t,{transposeA:i,transposeB:a}=n;return vp({a:o,b:s,transposeA:i,transposeB:a,backend:e})}var S3={kernelName:es,backendName:"webgl",kernelFunc:cst};var dI=class{constructor(t,e,n,o,s,i){this.outputShape=[],this.variableNames=["x","mean","variance"],S.assertAndGetBroadcastShape(t,e),S.assertAndGetBroadcastShape(t,n);let a="0.0";o!=null&&(S.assertAndGetBroadcastShape(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let u="1.0";s!=null&&(S.assertAndGetBroadcastShape(t,s),this.variableNames.push("scale"),u="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
| void main() {
| float x = getXAtOutCoords();
| float mean = getMeanAtOutCoords();
| float variance = getVarianceAtOutCoords();
| float offset = ${a};
| float scale = ${u};
| float inv = scale * inversesqrt(variance + float(${i}));
| setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
| }
| `}};var hI=class{constructor(t,e,n,o,s,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],S.assertAndGetBroadcastShape(t,e),S.assertAndGetBroadcastShape(t,n);let a="vec4(0.0)";o!=null&&(S.assertAndGetBroadcastShape(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let u="vec4(1.0)";s!=null&&(S.assertAndGetBroadcastShape(t,s),this.variableNames.push("scale"),u="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
| void main() {
| vec4 offset = ${a};
| vec4 scale = ${u};
|
| vec4 x = getXAtOutCoords();
| vec4 mean = getMeanAtOutCoords();
| vec4 variance = getVarianceAtOutCoords();
|
| vec4 inv = scale * inversesqrt(variance + vec4(${i}));
|
| setOutput((x - mean) * inv + offset);
| }
| `}};var pst=({inputs:r,backend:t,attrs:e})=>{let{x:n,mean:o,variance:s,offset:i,scale:a}=r;y.assert(o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:u}=e;u==null&&(u=.001);let l=[n,o,s],c=null;i!=null&&(c=i.shape,l.push(i));let p=null;a!=null&&(p=a.shape,l.push(a));let m=L().getBool("WEBGL_PACK_NORMALIZATION")?new hI(n.shape,o.shape,s.shape,c,p,u):new dI(n.shape,o.shape,s.shape,c,p,u);return t.runWebGLProgram(m,l,l[0].dtype)},N3={kernelName:ys,backendName:"webgl",kernelFunc:pst};var gI=class{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;let e=zt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=mst(this.rank),o,s=t.map((i,a)=>`sourceLoc.${E1[a]} = start[${a}] + coords.${E1[a]};`);o=`
| ${e} sourceLoc;
| ${e} coords = getOutputCoords();
| ${s.join(`
| `)}
| `,this.userCode=`
| void main() {
| ${o}
| setOutput(getSource(${n}));
| }
| `}},E1=["x","y","z","w","u","v"];function mst(r){if(r===1)return"sourceLoc";if(r<=6)return E1.slice(0,r).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var xI=class{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let e=zt(this.rank),n=er("coords",this.rank),o=er("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${o.slice(-2).join()})`,i=`getChannel(getSource(${o.join()}), ${s})`,a=`
| result.x = ${i};
| if (++${n[this.rank-1]} < ${t[this.rank-1]}) {
| ++${o[this.rank-1]};
| result.y = ${i};
| --${o[this.rank-1]};
| }
| `,u=this.rank===1?"":`
| --${n[this.rank-1]};
| if (++${n[this.rank-2]} < ${t[this.rank-2]}) {
| ++${o[this.rank-2]};
| result.z = ${i};
| if (++${n[this.rank-1]} < ${t[this.rank-1]}) {
| ++${o[this.rank-1]};
| result.w = ${i};
| }
| }
| `,l=this.rank<=4?`sourceLoc = coords +
| ${e}(${t.map((c,p)=>`start[${p}]`).join()});`:t.map((c,p)=>`${o[p]} = ${n[p]} + start[${p}];`).join(`
| `);this.userCode=`
| void main() {
| ${e} coords = getOutputCoords();
| ${e} sourceLoc;
| ${l}
| vec4 result = vec4(0.);
| ${a}
| ${u}
| setOutput(result);
| }
| `}};function fst(r,t,e,n){let o=n.texData.get(r.dataId),s=n.makeTensorInfo(e,r.dtype),i=n.texData.get(s.dataId);Object.assign(i,o),i.refCount=1,i.shape=e,i.dtype=r.dtype;let a=ze.computeFlatOffset(t,y.computeStrides(r.shape));o.slice&&(a+=o.slice.flatOffset),i.slice={flatOffset:a,origDataId:o.slice&&o.slice.origDataId||r.dataId};let u=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,u+1),s}function _i(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,size:i}=n,[a,u]=ze.parseSliceParams(o,s,i);if(ze.assertParamsValid(o,a,u),y.sizeFromShape(u)===0)return e.makeTensorInfo(u,o.dtype,[]);if(e.shouldExecuteOnCPU([o])||o.dtype==="string"){let p=e.texData.get(o.dataId),m=dz(p.values,a,u,o.shape,o.dtype);return e.makeTensorInfo(u,o.dtype,m)}let{isPacked:l}=e.texData.get(o.dataId),c=ze.isSliceContinous(o.shape,a,u);if(l||!c){let p=L().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xI(u):new gI(u),m=[a];return e.runWebGLProgram(p,[o],o.dtype,m)}return e.uploadToGPU(o.dataId),fst(o,a,u,e)}var k3={kernelName:qi,backendName:"webgl",kernelFunc:_i};var dst=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,crops:i}=n;y.assert(o.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let a=s.reduce((b,w)=>b*w),u=S.getReshaped(o.shape,s,a),l=S.getPermuted(u.length,s.length),c=S.getReshapedPermuted(o.shape,s,a),p=S.getSliceBeginCoords(i,s.length),m=S.getSliceSize(c,i,s.length),f=[],d=rt({inputs:{x:o},backend:e,attrs:{shape:u}}),h=Pe({inputs:{x:d},backend:e,attrs:{perm:l}}),g=rt({inputs:{x:h},backend:e,attrs:{shape:c}}),x=_i({inputs:{x:g},backend:e,attrs:{begin:p,size:m}});return f.push(d),f.push(h),f.push(g),f.forEach(b=>e.disposeIntermediateTensorInfo(b)),x},T3={kernelName:Pi,backendName:"webgl",kernelFunc:dst};function hst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,weights:s}=t,{size:i}=n,a=e.readSync(o.dataId),u=e.readSync(s.dataId),l=Yw(a,u,s.dtype,s.shape,i);return e.makeTensorInfo([i],s.dtype,l)}var _3={kernelName:Oa,backendName:"webgl",kernelFunc:hst};var gst=`
| int r = int(a.r) & int(b.r);
| int g = int(a.g) & int(b.g);
| int rb = int(a.b) & int(b.b);
| int ra = int(a.a) & int(b.a);
| return vec4(r, g, rb, ra);
| `,xst=`
| return float(int(a.r) & int(b.r));
| `;function yst(r){let{inputs:t,backend:e}=r,{a:n,b:o}=t,s=L().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=L().getNumber("WEBGL_VERSION");if(e.shouldExecuteOnCPU([n,o])||i===1){let u=e.texData.get(n.dataId).values,l=e.texData.get(o.dataId).values,[c,p]=LL(n.shape,o.shape,u,l,n.dtype),m=e.makeTensorInfo(p,n.dtype),f=e.texData.get(m.dataId);return f.values=c,m}let a;return s?a=new Jn(gst,n.shape,o.shape,!1):a=new On(xst,n.shape,o.shape),e.runWebGLProgram(a,[n,o],n.dtype)}var E3={kernelName:Pa,backendName:"webgl",kernelFunc:yst};function bst(r){let{inputs:t,backend:e}=r,{s0:n,s1:o}=t,s=e.readSync(n.dataId),i=e.readSync(o.dataId),a=S.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}var A3={kernelName:Ql,backendName:"webgl",kernelFunc:bst};var wst="return float(a != b);",A1=ue({opSnippet:wst,cpuKernelImpl:sz,dtype:"bool"}),D3={kernelName:el,backendName:"webgl",kernelFunc:A1};function Ul(r){let{inputs:t,backend:e}=r,{input:n}=t,o=e.texData.get(n.dataId);return rr({inputs:{x:o.complexTensorInfos.real},backend:e})}var $3={kernelName:Yp,backendName:"webgl",kernelFunc:Ul};var Ist="return float(int(x));";function R3(r,t){let e=new Br(r.shape,Ist),n=t.runWebGLProgram(e,[r],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function D1(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return rr({inputs:{x:o},backend:e});let i=Te(o.shape),a=D1({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),u=Pn({inputs:{real:a,imag:i},backend:e});return i.dispose(),e.disposeIntermediateTensorInfo(a),u}if(o.dtype==="complex64"){let i=Ul({inputs:{input:o},backend:e}),a=D1({inputs:{x:i},backend:e,attrs:{dtype:s}});return e.disposeIntermediateTensorInfo(i),a}if(!y.hasEncodingLoss(o.dtype,s)){let i=rr({inputs:{x:o},backend:e});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(e.shouldExecuteOnCPU([o])){let i=e.texData.get(o.dataId).values,[a,u,l]=zL(i,o.shape,o.dtype,s);return e.makeTensorInfo(a,u,l)}if(s==="int32")return R3(o,e);if(s==="bool"){let i=e.makeTensorInfo([],"bool",y.getTypedArrayFromDType("bool",1)),u=A1({inputs:{a:o,b:i},backend:e});return e.disposeIntermediateTensorInfo(i),u}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}var F3={kernelName:xo,backendName:"webgl",kernelFunc:D1};var O3="return ceil(x);",Cst=It({opSnippet:O3,packedOpSnippet:O3,cpuKernelImpl:BL}),P3={kernelName:rs,backendName:"webgl",kernelFunc:Cst};var yI=class{constructor(t){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=`
|
| void main() {
| float value = getAAtOutCoords();
| if (isnan(value)) {
| setOutput(value);
| return;
| }
|
| setOutput(clamp(value, minVal, maxVal));
| }
| `}};var bI=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=`
| void main() {
| vec4 value = getAAtOutCoords();
|
| if (any(isnan(value))) {
| setOutput(value);
| return;
| }
|
| setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
| }
| `}};function vst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{clipValueMin:s,clipValueMax:i}=n,a;L().getBool("WEBGL_PACK_CLIP")?a=new bI(o.shape):a=new yI(o.shape);let u=[[s],[i]];return e.runWebGLProgram(a,[o],o.dtype,u)}var M3={kernelName:yo,backendName:"webgl",kernelFunc:vst};var wI=class{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=`
| void main() {
| float re = abs(getRealAtOutCoords());
| float im = abs(getImagAtOutCoords());
| float mx = max(re, im);
|
| // sadly the length function in glsl is not underflow-safe
| // (at least not on Intel GPUs). So the safe solution is
| // to ensure underflow-safety in all cases.
| setOutput(
| mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
| );
| }
| `}};function L3(r,t){return{dataId:t.dataId,dtype:t.dtype,shape:r.shape}}function Sst(r){let{inputs:t,backend:e}=r,{x:n}=t,o=e.texData.get(n.dataId),s=new wI(n.shape),i=[L3(n,o.complexTensorInfos.real),L3(n,o.complexTensorInfos.imag)];return e.runWebGLProgram(s,i,i[0].dtype)}var z3={kernelName:tu,backendName:"webgl",kernelFunc:Sst};var II=class{constructor(t){this.outputShape=[],this.outputShape=S.computeOutShape(t,1),this.variableNames=t.map((i,a)=>`T${a}`);let e=new Array(t.length-1);e[0]=t[0][1];for(let i=1;i<e.length;i++)e[i]=e[i-1]+t[i][1];let n=[`if (yC < ${e[0]}) setOutput(getT0(yR, yC));`];for(let i=1;i<e.length;i++){let a=e[i-1];n.push(`else if (yC < ${e[i]}) setOutput(getT${i}(yR, yC-${a}));`)}let o=e.length,s=e[e.length-1];n.push(`else setOutput(getT${o}(yR, yC-${s}));`),this.userCode=`
| void main() {
| ivec2 coords = getOutputCoords();
| int yR = coords.x;
| int yC = coords.y;
|
| ${n.join(`
| `)}
| }
| `}};var vI=class{constructor(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=S.computeOutShape(t,e);let n=this.outputShape,o=n.length,s=zt(o),i=er("coords",o),a=["x","y","z","w","u","v"].slice(0,o);this.variableNames=t.map((h,g)=>`T${g}`);let u=new Array(t.length-1);u[0]=t[0][e];for(let h=1;h<u.length;h++)u[h]=u[h-1]+t[h][e];let l=a[e],c=a.slice(-2),p=a.join(),m=`if (${l} < ${u[0]}) {
| return getChannel(
| getT0(${p}), vec2(${c.join()}));
| }`;for(let h=1;h<u.length;h++){let g=u[h-1];m+=`
| if (${l} < ${u[h]} && ${l} >= ${u[h-1]}) {
| return getChannel(
| getT${h}(${CI(a,l,g)}),
| vec2(${CI(c,l,g)}));
| }`}let f=u.length,d=u[u.length-1];m+=`
| return getChannel(
| getT${f}(${CI(a,l,d)}),
| vec2(${CI(c,l,d)}));`,this.userCode=`
| float getValue(${a.map(h=>"int "+h)}) {
| ${m}
| }
|
| void main() {
| ${s} coords = getOutputCoords();
| vec4 result = vec4(getValue(${i}), 0., 0., 0.);
|
| ${i[o-1]} = ${i[o-1]} + 1;
| if (${i[o-1]} < ${n[o-1]}) {
| result.g = getValue(${i});
| }
|
| ${i[o-2]} = ${i[o-2]} + 1;
| if (${i[o-2]} < ${n[o-2]}) {
| result.a = getValue(${i});
| }
|
| ${i[o-1]} = ${i[o-1]} - 1;
| if (${i[o-2]} < ${n[o-2]} &&
| ${i[o-1]} < ${n[o-1]}) {
| result.b = getValue(${i});
| }
| setOutput(result);
| }
| `}};function CI(r,t,e){let n=r.indexOf(t);return r.map((s,i)=>i===n?`${s} - ${e}`:s).join()}function Sp(r){let{inputs:t,backend:e}=r,{input:n}=t,o=e.texData.get(n.dataId);return rr({inputs:{x:o.complexTensorInfos.imag},backend:e})}var B3={kernelName:qp,backendName:"webgl",kernelFunc:Sp};function zd(r,t,e){let n=r[0].dtype;if(n==="complex64"){let f=r.map(b=>Ul({inputs:{input:b},backend:e})),d=r.map(b=>Sp({inputs:{input:b},backend:e})),h=zd(f,t,e),g=zd(d,t,e),x=Pn({inputs:{real:h,imag:g},backend:e});return f.forEach(b=>e.disposeIntermediateTensorInfo(b)),d.forEach(b=>e.disposeIntermediateTensorInfo(b)),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),x}let o=e.shouldExecuteOnCPU(r);if(n==="string"&&(o=!0),o){let f=r.map(I=>{let E=[-1,y.sizeFromShape(I.shape.slice(t))];return rt({inputs:{x:I},backend:e,attrs:{shape:E}})}),d=f.map(I=>({vals:e.readSync(I.dataId),shape:I.shape})),h=S.computeOutShape(f.map(I=>I.shape),1),g=f[0].shape[0]===1,x=VL(d,h,n,g),b=S.computeOutShape(r.map(I=>I.shape),t),w=e.makeTensorInfo(b,n,x);return f.forEach(I=>e.disposeIntermediateTensorInfo(I)),w}let s=r.filter(f=>y.sizeFromShape(f.shape)>0),i=L().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let f=i?new Br(r[0].shape,Na):new Fn(r[0].shape,Na);return e.runWebGLProgram(f,r,n)}let a=L().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>a){let f=[];for(let h=0;h<s.length;h+=a){let g=s.slice(h,h+a);f.push(zd(g,t,e))}let d=zd(f,t,e);for(let h of f)e.disposeIntermediateTensorInfo(h);return d}if(i){let f=new vI(s.map(d=>d.shape),t);return e.runWebGLProgram(f,s,n)}let{tensors2D:u,outShape:l}=Nst(s,t,e),c=new II(u.map(f=>f.shape)),p=e.runWebGLProgram(c,u,n);u.forEach(f=>e.disposeIntermediateTensorInfo(f));let m=rt({inputs:{x:p},attrs:{shape:l},backend:e});return e.disposeIntermediateTensorInfo(p),m}function Nst(r,t,e){let n=S.computeOutShape(r.map(s=>s.shape),t);return{tensors2D:r.map(s=>rt({inputs:{x:s},attrs:{shape:[-1,y.sizeFromShape(s.shape.slice(t))]},backend:e})),outShape:n}}function $1(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n,s=y.parseAxisParam(o,t[0].shape)[0],i=t.map(l=>l.shape);S.assertParamsConsistent(i,s);let a=S.computeOutShape(t.map(l=>l.shape),s);if(y.sizeFromShape(a)===0)return e.makeTensorInfo(a,t[0].dtype,[]);let u=t.filter(l=>y.sizeFromShape(l.shape)>0);return u.length===1?rr({inputs:{x:u[0]},backend:e}):zd(u,s,e)}var V3={kernelName:Mi,backendName:"webgl",kernelFunc:$1};var Bd=class{constructor(t,e=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;let i=t.padInfo.top,a=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,m=t.filterHeight,f=t.filterWidth,d=Math.floor(t.inChannels/4)*4,h=t.inChannels%4,g=t.dataFormat==="channelsLast",x=g?1:2,b=g?2:3,w=g?3:1,I="",N="";n&&(o?I=`float activation(float a) {
| float b = getPreluActivationWeightsAtOutCoords();
| ${n}
| }`:s?I=`float activation(float a) {
| float b = getLeakyreluAlphaAtOutCoords();
| ${n}
| }`:I=`
| float activation(float x) {
| ${n}
| }
| `,N="result = activation(result);");let E=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
| ${I}
|
| const ivec2 strides = ivec2(${u}, ${l});
| const ivec2 pads = ivec2(${i}, ${a});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords[0];
| int d2 = coords[${w}];
|
| ivec2 xRCCorner =
| ivec2(coords[${x}], coords[${b}]) * strides - pads;
| int xRCorner = xRCCorner.x;
| int xCCorner = xRCCorner.y;
|
| // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
| for (int wR = 0; wR < ${m}; wR++) {
| int xR = xRCorner + wR * ${c};
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int wC = 0; wC < ${f}; wC++) {
| int xC = xCCorner + wC * ${p};
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| for (int d1 = 0; d1 < ${d}; d1 += 4) {
| vec4 wValues = vec4(
| getW(wR, wC, d1, d2),
| getW(wR, wC, d1 + 1, d2),
| getW(wR, wC, d1 + 2, d2),
| getW(wR, wC, d1 + 3, d2)
| );
|
| if (${g}) {
| vec4 xValues = vec4(
| getX(batch, xR, xC, d1),
| getX(batch, xR, xC, d1 + 1),
| getX(batch, xR, xC, d1 + 2),
| getX(batch, xR, xC, d1 + 3)
| );
| dotProd += dot(xValues, wValues);
| } else {
| vec4 xValues = vec4(
| getX(batch, d1, xR, xC),
| getX(batch, d1 + 1, xR, xC),
| getX(batch, d1 + 2, xR, xC),
| getX(batch, d1 + 3, xR, xC)
| );
| dotProd += dot(xValues, wValues);
| }
| }
|
| if (${h===1}) {
|
| if (${g}) {
| dotProd +=
| getX(batch, xR, xC, ${d}) *
| getW(wR, wC, ${d}, d2);
| } else {
| dotProd +=
| getX(batch, ${d}, xR, xC) *
| getW(wR, wC, ${d}, d2);
| }
|
| } else if (${h===2}) {
| vec2 wValues = vec2(
| getW(wR, wC, ${d}, d2),
| getW(wR, wC, ${d} + 1, d2)
| );
|
| if (${g}) {
| vec2 xValues = vec2(
| getX(batch, xR, xC, ${d}),
| getX(batch, xR, xC, ${d} + 1)
| );
| dotProd += dot(xValues, wValues);
| } else {
| vec2 xValues = vec2(
| getX(batch, ${d}, xR, xC),
| getX(batch, ${d} + 1, xR, xC)
| );
| dotProd += dot(xValues, wValues);
| }
|
| } else if (${h===3}) {
| vec3 wValues = vec3(
| getW(wR, wC, ${d}, d2),
| getW(wR, wC, ${d} + 1, d2),
| getW(wR, wC, ${d} + 2, d2)
| );
|
| if (${g}) {
| vec3 xValues = vec3(
| getX(batch, xR, xC, ${d}),
| getX(batch, xR, xC, ${d} + 1),
| getX(batch, xR, xC, ${d} + 2)
| );
| dotProd += dot(xValues, wValues);
| } else {
| vec3 xValues = vec3(
| getX(batch, ${d}, xR, xC),
| getX(batch, ${d} + 1, xR, xC),
| getX(batch, ${d} + 2, xR, xC)
| );
| dotProd += dot(xValues, wValues);
| }
|
| }
| }
| }
|
| float result = dotProd;
| ${E}
| ${N}
| setOutput(result);
| }
| `}},SI=class{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let e=t.padInfo.front,n=t.padInfo.top,o=t.padInfo.left,s=t.strideDepth,i=t.strideHeight,a=t.strideWidth,u=t.dilationDepth,l=t.dilationHeight,c=t.dilationWidth,p=t.filterDepth,m=t.filterHeight,f=t.filterWidth,d=Math.floor(t.inChannels/4)*4,h=t.inChannels%4;this.userCode=`
| const ivec3 strides = ivec3(${s}, ${i}, ${a});
| const ivec3 pads = ivec3(${e}, ${n}, ${o});
|
| void main() {
| ivec5 coords = getOutputCoords();
| int batch = coords.x;
| int d2 = coords.u;
|
| ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
| int xFCorner = xFRCCorner.x;
| int xRCorner = xFRCCorner.y;
| int xCCorner = xFRCCorner.z;
|
| // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
| // y(yF, yR, yC, d2). ? = to be determined. : = across all
| // values in that axis.
| float dotProd = 0.0;
| for (int wF = 0; wF < ${p}; wF++) {
| int xF = xFCorner + wF * ${u};
|
| if (xF < 0 || xF >= ${t.inDepth}) {
| continue;
| }
|
| for (int wR = 0; wR < ${m}; wR++) {
| int xR = xRCorner + wR * ${l};
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int wC = 0; wC < ${f}; wC++) {
| int xC = xCCorner + wC * ${c};
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| for (int d1 = 0; d1 < ${d}; d1 += 4) {
| vec4 xValues = vec4(
| getX(batch, xF, xR, xC, d1),
| getX(batch, xF, xR, xC, d1 + 1),
| getX(batch, xF, xR, xC, d1 + 2),
| getX(batch, xF, xR, xC, d1 + 3)
| );
| vec4 wValues = vec4(
| getW(wF, wR, wC, d1, d2),
| getW(wF, wR, wC, d1 + 1, d2),
| getW(wF, wR, wC, d1 + 2, d2),
| getW(wF, wR, wC, d1 + 3, d2)
| );
|
| dotProd += dot(xValues, wValues);
| }
|
| if (${h===1}) {
| dotProd +=
| getX(batch, xF, xR, xC, ${d}) *
| getW(wF, wR, wC, ${d}, d2);
| } else if (${h===2}) {
| vec2 xValues = vec2(
| getX(batch, xF, xR, xC, ${d}),
| getX(batch, xF, xR, xC, ${d} + 1)
| );
| vec2 wValues = vec2(
| getW(wF, wR, wC, ${d}, d2),
| getW(wF, wR, wC, ${d} + 1, d2)
| );
| dotProd += dot(xValues, wValues);
| } else if (${h===3}) {
| vec3 xValues = vec3(
| getX(batch, xF, xR, xC, ${d}),
| getX(batch, xF, xR, xC, ${d} + 1),
| getX(batch, xF, xR, xC, ${d} + 2)
| );
| vec3 wValues = vec3(
| getW(wF, wR, wC, ${d}, d2),
| getW(wF, wR, wC, ${d} + 1, d2),
| getW(wF, wR, wC, ${d} + 2, d2)
| );
| dotProd += dot(xValues, wValues);
| }
| }
| }
| }
| setOutput(dotProd);
| }
| `}};var Vd=class{constructor(t,e=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=t.outShape,this.enableShapeUniforms=de(this.outputShape.length);let i=t.padInfo.left,a=t.strideWidth,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,p=c,m=`
| int xR; int xC; int xCOffset;
| vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<c;g++)m+=`
| vec4 xTexelC${g*2};
| int xTexelC${g*2}Ready;
| vec4 xTexelC${g*2+1};
| int xTexelC${g*2+1}Ready;
| vec4 xC${g};`;m+=`
| for (int r = 0; r < ${l}; r++) {
| for (int d1 = 0; d1 < ${t.inChannels}; d1 += 2) {
| `;for(let g=0;g<c;g++)m+=`
| xTexelC${g*2} = vec4(0.0);
| xTexelC${g*2}Ready = 0;
| xTexelC${g*2+1} = vec4(0.0);
| xTexelC${g*2+1}Ready = 0;
| xC${g} = vec4(0.0);`;m+=`
| xR = xRCorner + r * dilations[0];
| if (xR >=0 && xR < inDims[0]) {
| `;for(let g=0;g<(p+1)/2;g++){let x=g*2;if(m+=`
| xC = xCCorner + ${x*u};
| `,a===1){if(x<c&&(i%2===1?(m+=`
| xCOffset = xC + 1;
| if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
| xTexelC${x} = getX(batch, xR, xCOffset, d1);
|
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${x}.zw = vec2(0.0);
| }
| xTexelC${x}Ready = 1;
| }
| `,u===1&&x>0?m+=`
| xC${x} = vec4(xTexelC${x-2}.zw, xTexelC${x}.xy);
| `:m+=`
| xCOffset = xC + 1 - 2;
|
| if (xCOffset >= 0 && xCOffset < inDims[1]) {
| previous = getX(batch, xR, xCOffset, d1);
|
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| previous.zw = vec2(0.0);
| }
|
| xC${x} = vec4(previous.zw, xTexelC${x}.xy);
| } else {
| xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);
| }
| `):m+=`
| if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
| xTexelC${x} = getX(batch, xR, xC, d1);
| if (xC + 1 >= inDims[1]) {
| xTexelC${x}.zw = vec2(0.0);
| }
| xTexelC${x}Ready = 1;
| }
|
| xC${x} = xTexelC${x};
| `,x+1<c)){let b=i%2===0?y.nearestLargerEven(u):u;u%2===0&&i%2===1||u%2!==0&&i%2!==1?(m+=`
| xCOffset = xC + imod(pads[1], 2) + ${b};
|
| if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
| xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
|
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${x+1}.zw = vec2(0.0);
| }
| xTexelC${x+1}Ready = 1;
| }
| `,u>1?m+=`
| xCOffset -= 2;
| if (xCOffset >= 0 && xCOffset < inDims[1]) {
| previous = getX(batch, xR, xCOffset, d1);
| xC${x+1} = vec4(previous.zw, xTexelC${x+1}.xy);
| } else {
| xC${x+1} = vec4(0.0, 0.0, xTexelC${x+1}.xy);
| }
| `:m+=`
| xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.xy);
| `):b===1?m+=`
| xC${x+1} = xTexelC${x};
| `:m+=`
| xCOffset = xC + ${b};
|
| if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
| xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${x+1}.zw = vec2(0.0);
| }
| xTexelC${x+1}Ready = 1;
| }
|
| xC${x+1} = xTexelC${x+1};
| `}}else x<c&&(i%2===1?(m+=`
| xCOffset = xC + 1 - strides[1];
| if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
| xTexelC${x} = getX(batch, xR, xCOffset, d1);
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${x}.zw = vec2(0.0);
| }
| xTexelC${x}Ready = 1;
| }
|
| if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x+1}Ready == 0) {
| xTexelC${x+1} = getX(batch, xR, xC + 1, d1);
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xC + 2 >= inDims[1]) {
| xTexelC${x+1}.zw = vec2(0.0);
| }
| xTexelC${x+1}Ready = 1;
| }
|
| xC${x} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
| `,x+1<c&&(m+=`
| final = vec4(0.0);
| xCOffset = xC + 1 + strides[1];
| if(xCOffset >= 0 && xCOffset < inDims[1]) {
| final = getX(batch, xR, xCOffset, d1);
| }
| xC${x+1} = vec4(xTexelC${x+1}.xy, final.xy);
| `)):(m+=`
| if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
| xTexelC${x} = getX(batch, xR, xC, d1);
| if (xC + 1 >= inDims[1]) {
| xTexelC${x}.zw = vec2(0.0);
| }
| xTexelC${x}Ready = 1;
| }
|
| xCOffset = xC + strides[1];
| if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
| xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${x+1}.zw = vec2(0.);
| }
| xTexelC${x+1}Ready = 1;
| }
|
| xC${x} = vec4(
| xTexelC${x}.xy, xTexelC${x+1}.xy);
| `,x+1<c&&(m+=`
| xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
| `)));x<c&&(m+=`
| wTexel = getW(r, ${x}, d1, d2);
| dotProd += xC${x}.xxzz * vec4(wTexel.xy, wTexel.xy);
| if(d1 + 1 < ${t.inChannels}) {
| dotProd += xC${x}.yyww * vec4(wTexel.zw, wTexel.zw);
| }
| `,x+1<c&&(m+=`
| wTexel = getW(r, ${x+1}, d1, d2);
| dotProd += xC${x+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
| if(d1 + 1 < ${t.inChannels}) {
| dotProd += xC${x+1}.yyww * vec4(wTexel.zw, wTexel.zw);
| }
| `))}m+=`
| }
| `,m+=`
| }
| `,m+=`
| }
| `;let f="",d="";n&&(o?f=`vec4 activation(vec4 a) {
| vec4 b = getPreluActivationWeightsAtOutCoords();
| ${n}
| }`:s?f=`vec4 activation(vec4 a) {
| vec4 b = getLeakyreluAlphaAtOutCoords();
| ${n}
| }`:f=`vec4 activation(vec4 x) {
| ${n}
| }`,d="result = activation(result);");let h=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
| ${f}
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords.x;
| ivec2 xRCCorner = coords.yz * strides - pads;
| int d2 = coords.w;
| int xRCorner = xRCCorner.x;
| int xCCorner = xRCCorner.y;
|
| //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
| vec4 dotProd = vec4(0.000000000000001);
|
| ${m}
|
| vec4 result = dotProd - vec4(0.000000000000001);
| ${h}
| ${d}
| setOutput(result);
| }
| `}};var NI=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=t,this.enableShapeUniforms=de(this.outputShape.length);let{dataFormat:n}=e,o=We(),s=n==="channelsLast",i=s?1:2,a=s?2:3,u=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${t[2]} && pos < ${t[1]}) {`,l="";for(let c=0;c<=1;c++)for(let p=0;p<=1;p++)l+=`
| blockIndex = rc.z + ${p};
| pos = rc.y + ${c};
|
| ${u}
| offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
| d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
| if(d0 < inputShape[${i}] && d0 >= 0) {
| // Use custom imod instead mod. On Intel GPU, mod may generate
| // unexpected value.
| // https://github.com/tensorflow/tfjs/issues/5447
| offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
| d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
| inChannels);
|
| if(d1 < inputShape[${a}] && d1 >= 0) {
|
| ch = imod(pos, inChannels);
|
| if (${s}) {
| innerDims = vec2(d1, ch);
| result[${c*2+p}] = getChannel(
| getA(rc.x, d0, int(innerDims.x),
| int(innerDims.y)), innerDims);
| } else {
| innerDims = vec2(d0, d1);
| result[${c*2+p}] = getChannel(
| getA(rc.x, ch, int(innerDims.x),
| int(innerDims.y)), innerDims);
| }
| }
| }
| }
| `;this.userCode=`
| void main() {
| ivec3 rc = getOutputCoords();
|
| vec4 result = vec4(0);
|
| int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
| vec2 innerDims;
|
| ${l}
|
| ${o.output} = result;
| }
| `}};function kI(r,t){let e=r.length;return e>=3?t?[...r.slice(0,-3),r[e-3]*r[e-2],r[e-1]]:[...r.slice(0,-3),r[e-3],r[e-2]*r[e-1]]:!t&&e===1&&r[0]>1?[r[0],1]:null}function TI({x:r,filter:t,convInfo:e,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:a=null}){let u=r.shape,l=n.texData.get(r.dataId),c=e.inChannels,p=u[0]*u[1]*u[2],m=e.outChannels,f=e.dataFormat==="channelsLast",d=!1,h=!1,g,x=[];if(s!=null){let I=kI(s.shape,f);I!=null&&(s=rt({inputs:{x:s},backend:n,attrs:{shape:I}}),x.push(s))}if(o!=null){let I=kI(o.shape,f);I!=null&&(o=rt({inputs:{x:o},backend:n,attrs:{shape:I}}),x.push(o))}if(!((p===1||m===1)&&c>_1)&&l.isPacked&&f&&l.texture!=null&&u[2]%2!==0&&y.arraysEqual(l.shape.slice(-3),u.slice(-3))){let I=u[0]*u[1]*(u[2]+1),N={dataId:r.dataId,shape:[1,I,e.inChannels],dtype:r.dtype},E=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,y.assert(Ju(l.shape,N.shape),()=>`packed reshape ${l.shape} to ${N.shape} isn't free`);let A=rt({inputs:{x:t},backend:n,attrs:{shape:[1,e.inChannels,e.outChannels]}});x.push(A);let D=vp({a:N,b:A,backend:n,transposeA:d,transposeB:h,bias:o,activation:a,preluActivationWeights:s,leakyreluAlpha:i}),F=n.texData.get(D.dataId);y.assert(F.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=E,F.shape=e.outShape,g=rr({inputs:{x:D},backend:n}),g.shape=e.outShape,x.push(D)}else{let I=e.outHeight*e.outWidth,N=rt({inputs:{x:r},backend:n,attrs:{shape:f?[e.batchSize,I,e.inChannels]:[e.batchSize,e.inChannels,I]}}),E=rt({inputs:{x:t},backend:n,attrs:{shape:[1,e.inChannels,e.outChannels]}}),A=vp({a:f?N:E,b:f?E:N,transposeA:!f,transposeB:h,backend:n,bias:o,activation:a,preluActivationWeights:s,leakyreluAlpha:i});g=rt({inputs:{x:A},backend:n,attrs:{shape:e.outShape}}),x.push(N),x.push(E),x.push(A)}for(let I of x)n.disposeIntermediateTensorInfo(I);return g}function _I({x:r,filter:t,convInfo:e,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:a=null}){let{filterWidth:u,filterHeight:l,inChannels:c,outWidth:p,outHeight:m,dataFormat:f}=e,d=f==="channelsLast",h=u*l*c,g=m*p,x=[e.batchSize,h,g],b=!0,w=!1,I=[];if(s!=null){let Z=kI(s.shape,d);Z!=null&&(s=rt({inputs:{x:s},backend:n,attrs:{shape:Z}}),I.push(s))}if(o!=null){let Z=kI(o.shape,d);Z!=null&&(o=rt({inputs:{x:o},backend:n,attrs:{shape:Z}}),I.push(o))}let N=rt({inputs:{x:t},backend:n,attrs:{shape:[1,h,y.sizeFromShape(t.shape)/h]}});I.push(N);let E=new NI(x,e),A=[r.shape,[e.padInfo.top,e.padInfo.left],[e.strideHeight,e.strideWidth],[e.dilationHeight,e.dilationWidth],[e.inChannels],[e.filterWidth*e.inChannels],[e.outWidth]],D=n.runWebGLProgram(E,[r],"float32",A),F=rt({inputs:{x:D},backend:n,attrs:{shape:x}});I.push(D),I.push(F);let P=o!=null,V=s!=null,G=a==="leakyrelu",W=a?Wl(a,!0):null,q=new Ld(d?F.shape:N.shape,d?N.shape:F.shape,d?[e.batchSize,g,e.outChannels]:[e.batchSize,e.outChannels,g],b,w,P,W,V,G),H=d?[F,N]:[N,F];if(o&&H.push(o),V&&H.push(s),G){let Z=n.makeTensorInfo([],"float32",y.createScalarValue(i,"float32"));H.push(Z),I.push(Z)}let K=n.runWebGLProgram(q,H,"float32"),X=rt({inputs:{x:K},backend:n,attrs:{shape:e.outShape}});I.push(K);for(let Z of I)n.disposeIntermediateTensorInfo(Z);return X}function kst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dataFormat:u,dilations:l,dimRoundingMode:c}=n,p=S.convertConv2DDataFormat(u),m=S.computeConv2DInfo(o.shape,s.shape,i,l,a,c,!1,p),f;if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))f=TI({x:o,filter:s,convInfo:m,backend:e});else if(m.strideWidth<=2&&p==="channelsLast"&&L().getBool("WEBGL_EXP_CONV")){let h=new Vd(m),g=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]];f=e.runWebGLProgram(h,[o,s],"float32",g)}else if(L().getBool("WEBGL_CONV_IM2COL"))f=_I({x:o,filter:s,convInfo:m,backend:e});else{let h=new Bd(m);f=e.runWebGLProgram(h,[o,s],"float32")}let d=rt({inputs:{x:f},backend:e,attrs:{shape:m.outShape}});return e.disposeIntermediateTensorInfo(f),d}var G3={kernelName:ns,backendName:"webgl",kernelFunc:kst};var EI=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,n=t.strideWidth,o=t.padInfo.top,s=t.padInfo.left,i=t.dataFormat==="channelsLast";this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int wR = coords.x;
| int wC = coords.y;
| int d1 = coords.z;
| int d2 = coords.w;
|
| // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
|
| for (int b = 0; b < ${t.batchSize}; b++) {
| for (int yR = 0; yR < ${t.outHeight}; yR++) {
| int xR = wR + yR * ${e} - ${o};
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int yC = 0; yC < ${t.outWidth}; yC++) {
| int xC = wC + yC * ${n} - ${s};
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| ${i?`float dyValue = getDy(b, yR, yC, d2);
| float xValue = getX(b, xR, xC, d1);
| dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
| float xValue = getX(b, d1, xR, xC);
| dotProd += (xValue * dyValue);`}
| }
| }
| }
| setOutput(dotProd);
| }
| `}},AI=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,n=t.filterWidth,o=t.strideHeight,s=t.strideWidth,i=t.dataFormat==="channelsLast",a=e-1-t.padInfo.top,u=n-1-t.padInfo.left,l=i?1:2,c=i?2:3,p=i?3:1;this.userCode=`
| const ivec2 pads = ivec2(${a}, ${u});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords[0];
| int d1 = coords[${p}];
|
| ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - pads;
| int dyRCorner = dyCorner.x;
| int dyCCorner = dyCorner.y;
|
| // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
| for (int wR = 0; wR < ${e}; wR++) {
| float dyR = float(dyRCorner + wR) / ${o}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| int wRPerm = ${e} - 1 - wR;
|
| for (int wC = 0; wC < ${n}; wC++) {
| float dyC = float(dyCCorner + wC) / ${s}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| int wCPerm = ${n} - 1 - wC;
|
| for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
|
| if (${i}) {
| float xValue = getDy(batch, idyR, idyC, d2);
| float wValue = getW(wRPerm, wCPerm, d1, d2);
| dotProd += xValue * wValue;
| } else {
| float xValue = getDy(batch, d2, idyR, idyC);
| float wValue = getW(wRPerm, wCPerm, d1, d2);
| dotProd += xValue * wValue;
| }
|
| }
| }
| }
| setOutput(dotProd);
| }
| `}},DI=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideDepth,n=t.strideHeight,o=t.strideWidth,s=t.padInfo.front,i=t.padInfo.top,a=t.padInfo.left;this.userCode=`
| void main() {
| ivec5 coords = getOutputCoords();
| int wF = coords.x;
| int wR = coords.y;
| int wC = coords.z;
| int d1 = coords.w;
| int d2 = coords.u;
|
| float dotProd = 0.0;
|
| for (int b = 0; b < ${t.batchSize}; b++) {
| for (int yF = 0; yF < ${t.outDepth}; yF++) {
| int xF = wF + yF * ${e} - ${s};
|
| if (xF < 0 || xF >= ${t.inDepth}) {
| continue;
| }
|
| for (int yR = 0; yR < ${t.outHeight}; yR++) {
| int xR = wR + yR * ${n} - ${i};
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int yC = 0; yC < ${t.outWidth}; yC++) {
| int xC = wC + yC * ${o} - ${a};
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| float dyValue = getDy(b, yF, yR, yC, d2);
| float xValue = getX(b, xF, xR, xC, d1);
| dotProd += (xValue * dyValue);
| }
| }
| }
| }
| setOutput(dotProd);
| }
| `}},$I=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterDepth,n=t.filterHeight,o=t.filterWidth,s=t.strideDepth,i=t.strideHeight,a=t.strideWidth,u=e-1-t.padInfo.front,l=n-1-t.padInfo.top,c=o-1-t.padInfo.left;this.userCode=`
| const ivec3 pads = ivec3(${u}, ${l}, ${c});
|
| void main() {
| ivec5 coords = getOutputCoords();
| int batch = coords.x;
| int d1 = coords.u;
|
|
| ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
| int dyFCorner = dyCorner.x;
| int dyRCorner = dyCorner.y;
| int dyCCorner = dyCorner.z;
|
| float dotProd = 0.0;
| for (int wF = 0; wF < ${e}; wF++) {
| float dyF = float(dyFCorner + wF) / ${s}.0;
|
| if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) {
| continue;
| }
| int idyF = int(dyF);
|
| int wFPerm = ${e} - 1 - wF;
|
| for (int wR = 0; wR < ${n}; wR++) {
| float dyR = float(dyRCorner + wR) / ${i}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
| fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| int wRPerm = ${n} - 1 - wR;
|
| for (int wC = 0; wC < ${o}; wC++) {
| float dyC = float(dyCCorner + wC) / ${a}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| int wCPerm = ${o} - 1 - wC;
|
| for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
| float xValue = getDy(batch, idyF, idyR, idyC, d2);
| float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
| dotProd += xValue * wValue;
| }
| }
| }
| }
| setOutput(dotProd);
| }
| `}};function Tst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,dataFormat:u,dimRoundingMode:l,filterShape:c}=n,p=S.convertConv2DDataFormat(u),m=S.computeConv2DInfo(o.shape,c,i,1,a,l,!1,p),f=new EI(m);return e.runWebGLProgram(f,[o,s],"float32")}var W3={kernelName:Bp,backendName:"webgl",kernelFunc:Tst};var RI=class{constructor(t){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=t.inShape,this.enableShapeUniforms=de(this.outputShape.length);let e=t.filterHeight,n=t.filterWidth,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left;this.userCode=`
| const ivec2 pads = ivec2(${o}, ${s});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords[0];
| int d1 = coords[3];
|
| ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
| int dyRCorner = dyCorner.x;
| int dyCCorner = dyCorner.y;
|
| vec4 result = vec4(0.);
| for (int wR = 0; wR < ${e}; wR++) {
| float dyR = float(dyRCorner + wR) / strides[0];
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
| int wRPerm = ${e} - 1 - wR;
|
| for (int wC = 0; wC < ${n}; wC++) {
| int wCPerm = ${n} - 1 - wC;
|
| float dyC = float(dyCCorner + wC) / strides[1];
| bool idyCVal = (dyC >= 0.0) && (dyC < ${t.outWidth}.0)
| && (fract(dyC) == 0.0);
| int idyC = int(dyC);
|
| float dyC2 = float(dyCCorner + wC + 1) / strides[1];
| bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${t.outWidth}.0)
| && (fract(dyC2) == 0.0);
| int idyC2 = int(dyC2);
|
| if (idyCVal && idyCVal2) {
| for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) {
| vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
| vec4 dySample = getDy(batch, idyR, idyC, d2);
| vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
| dySample : getDy(batch, idyR, idyC2, d2);
|
| vec2 dyValue = mod(float(idyC), 2.) == 0. ?
| dySample.xy : dySample.zw;
| result.xy += vec2(dot(dyValue, wValue.xy),
| dot(dyValue, wValue.zw));
|
| dyValue = mod(float(idyC2), 2.) == 0. ?
| dySample2.xy : dySample2.zw;
| result.zw += vec2(dot(dyValue, wValue.xy),
| dot(dyValue, wValue.zw));
| }
| } else if (idyCVal) {
| for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) {
| vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
| vec4 dySample = getDy(batch, idyR, idyC, d2);
| vec2 dyValue = mod(float(idyC), 2.) == 0. ?
| dySample.xy : dySample.zw;
| result.xy += vec2(dot(dyValue, wValue.xy),
| dot(dyValue, wValue.zw));
| }
| } else if (idyCVal2) {
| for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) {
| vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
| vec4 dySample = getDy(batch, idyR, idyC2, d2);
| vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
| dySample.xy : dySample.zw;
| result.zw += vec2(dot(dyValue, wValue.xy),
| dot(dyValue, wValue.zw));
| }
| }
| }
| }
| setOutput(result);
| }
| `}};function _st(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{inputShape:i,strides:a,pad:u,dataFormat:l,dimRoundingMode:c}=n,p=S.convertConv2DDataFormat(l),m=S.computeConv2DInfo(i,s.shape,a,1,u,c,!1,p);if(L().getBool("WEBGL_PACK")&&p==="channelsLast"){let f=[[m.strideHeight,m.strideWidth]],d=new RI(m);return e.runWebGLProgram(d,[o,s],"float32",f)}else{let f=new AI(m);return e.runWebGLProgram(f,[o,s],"float32")}}var U3={kernelName:os,backendName:"webgl",kernelFunc:_st};function Est(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n,l=S.computeConv3DInfo(o.shape,s.shape,i,u,a),c=new SI(l);return e.runWebGLProgram(c,[o,s],"float32")}var H3={kernelName:ss,backendName:"webgl",kernelFunc:Est};function Ast(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,filterShape:u}=n,l=S.computeConv3DInfo(o.shape,u,i,1,a),c=new DI(l);return e.runWebGLProgram(c,[o,s],"float32")}var q3={kernelName:Ma,backendName:"webgl",kernelFunc:Ast};function Dst(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{pad:i,strides:a,inputShape:u}=n,l=S.computeConv3DInfo(u,s.shape,a,1,i),c=new $I(l);return e.runWebGLProgram(c,[o,s],"float32")}var K3={kernelName:La,backendName:"webgl",kernelFunc:Dst};var $st=Vo+`
| return cos(x);
| `,Rst=`
| vec4 result = cos(x);
| bvec4 isNaN = isnan(x);
| ${Qn}
| return result;
| `,Fst=It({opSnippet:$st,packedOpSnippet:Rst}),j3={kernelName:is,backendName:"webgl",kernelFunc:Fst};var Ost=`
| float e2x = exp(-x);
| return (e2x + 1.0 / e2x) / 2.0;
| `,Pst=It({opSnippet:Ost}),X3={kernelName:as,backendName:"webgl",kernelFunc:Pst};var FI=class{constructor(t,e,n,o,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[i,a,u,l]=t,[c]=e,[p,m]=n;this.outputShape=[c,p,m,l];let f=o==="bilinear"?1:0,[d,h]=[`${a-1}.0`,`${u-1}.0`],[g,x,b]=p>1?[`${(a-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,I,N]=m>1?[`${(u-1)/(m-1)}`,"(x2-x1) * width_ratio",`x1*${h} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${h}`];this.userCode=`
| const float height_ratio = float(${g});
| const float width_ratio = float(${w});
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int y = coords[1];
| int x = coords[2];
| int d = coords[3];
|
| // get box vals
| float y1 = getBoxes(b,0);
| float x1 = getBoxes(b,1);
| float y2 = getBoxes(b,2);
| float x2 = getBoxes(b,3);
|
| // get image in batch index
| int bInd = round(getBoxInd(b));
| if(bInd < 0 || bInd >= ${i}) {
| return;
| }
|
| float height_scale = ${x};
| float width_scale = ${I};
|
| float in_y = ${b};
| if( in_y < 0.0 || in_y > ${d} ) {
| setOutput(float(${s}));
| return;
| }
| float in_x = ${N};
| if( in_x < 0.0 || in_x > ${h} ) {
| setOutput(float(${s}));
| return;
| }
|
| vec2 sourceFracIndexCR = vec2(in_x,in_y);
| if(${f} == 1) {
| // Compute the four integer indices.
| ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
| ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
| float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
| float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
| float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
| float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
| vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
| float top = topLeft + (topRight - topLeft) * fracCR.x;
| float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
| float newValue = top + (bottom - top) * fracCR.y;
| setOutput(newValue);
| } else {
| // Compute the coordinators of nearest neighbor point.
| ivec2 sourceNearestCR = ivec2(floor(
| sourceFracIndexCR + vec2(0.5,0.5)));
| float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
| setOutput(newValue);
| }
| }
| `}};var Mst=r=>{let{inputs:t,backend:e,attrs:n}=r,{image:o,boxes:s,boxInd:i}=t,{cropSize:a,method:u,extrapolationValue:l}=n,c=new FI(o.shape,s.shape,a,u,l);return e.runWebGLProgram(c,[o,s,i],"float32")},Y3={kernelName:Ba,backendName:"webgl",kernelFunc:Mst};var Np;(function(r){r.Prod="*",r.Sum="+"})(Np||(Np={}));var hg=class{constructor(t,e,n,o){this.op=t,this.outputShape=e,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let s=this.outputShape.length,i=this.op===Np.Prod?"1.0":"0.0",a=n?i:`getX(${Z3(s,"coords",this.op)})`,u=this.outputShape[this.outputShape.length-1],l="",c="";n?(l=o?`end != ${u-1}`:"end != 0",c=o?"end + 1":"end - 1"):(l=o?`end + pow2 < ${u}`:"end >= pow2",c=o?"end + pow2":"end - pow2"),this.userCode=`
| void main() {
| ${zt(s)} coords = getOutputCoords();
| int end = ${J3(s,"coords",this.op)};
| float val = ${a};
| int pow2 = int(pow(2.0, index));
| if (${l}) {
| int idx = ${c};
| ${J3(s,"coords",this.op)} = idx;
| val ${this.op}= getX(${Z3(s,"coords",this.op)});
| }
| setOutput(val);
| }
| `}};function Z3(r,t,e){if(r===1)return`${t}`;if(r===2)return`${t}.x, ${t}.y`;if(r===3)return`${t}.x, ${t}.y, ${t}.z`;if(r===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${e} for rank ${r} is not yet supported`)}function J3(r,t,e){if(r===1)return`${t}`;if(r===2)return`${t}.y`;if(r===3)return`${t}.z`;if(r===4)return`${t}.w`;throw new Error(`Cumulative ${e} for rank ${r} is not yet supported`)}function OI(r,t,e,n,o,s){let i=t.shape.length,a=S.getAxesPermutation([n],i),u=t;a!=null&&(u=Pe({inputs:{x:t},backend:e,attrs:{perm:a}}));let l=S.getInnerMostAxes(1,i)[0];if(l!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let c=u.shape[l],p=rr({inputs:{x:u},backend:e});for(let m=0;m<=Math.ceil(Math.log2(c))-1;m++){let f=new hg(r,u.shape,!1,s),d=[[m]],h=p;p=e.runWebGLProgram(f,[p],p.dtype,d),e.disposeIntermediateTensorInfo(h)}if(o){let m=new hg(r,u.shape,o,s),f=p;p=e.runWebGLProgram(m,[p],p.dtype),e.disposeIntermediateTensorInfo(f)}if(a!=null){let m=S.getUndoAxesPermutation(a),f=Pe({inputs:{x:p},backend:e,attrs:{perm:m}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(u),f}return p}function Lst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n;return OI(Np.Prod,o,e,s,i,a)}var Q3={kernelName:za,backendName:"webgl",kernelFunc:Lst};function zst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n;return OI(Np.Sum,o,e,s,i,a)}var tB={kernelName:ls,backendName:"webgl",kernelFunc:zst};function Bst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,weights:s}=t,{size:i,binaryOutput:a}=n;if(o.shape.length===1){let u=e.readSync(o.dataId),l=e.readSync(s.dataId),c=Yw(u,l,s.dtype,s.shape,i);return e.makeTensorInfo([i],s.dtype,c)}else if(o.shape.length===2){let u=e.bufferSync(o),l=e.bufferSync(s),c=ML(u,l,i,a);return e.makeTensorInfo(c.shape,s.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var eB={kernelName:eu,backendName:"webgl",kernelFunc:Bst};var PI=class{constructor(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int h = ${this.getHeightCoordString()};
| int w = ${this.getWidthCoordString()};
| int d = ${this.getDepthCoordString()};
|
| int in_h = h / ${e};
| int offset_h = imod(h, ${e});
| int in_w = w / ${e};
| int offset_w = imod(w, ${e});
| int offset_d = (offset_h * ${e} + offset_w) *
| ${this.getOutputDepthSize()};
| int in_d = d + offset_d;
|
| float result = ${this.getInputSamplingString()};
| setOutput(result);
| }
| `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function Vst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockSize:s,dataFormat:i}=n,a=o.shape[0],u=i==="NHWC"?o.shape[1]:o.shape[2],l=i==="NHWC"?o.shape[2]:o.shape[3],c=i==="NHWC"?o.shape[3]:o.shape[1],p=u*s,m=l*s,f=c/(s*s),d=i==="NHWC"?[a,p,m,f]:[a,f,p,m],h=new PI(d,s,i);return e.runWebGLProgram(h,[o],o.dtype)}var rB={kernelName:Va,backendName:"webgl",kernelFunc:Vst};var Gd=class{constructor(t,e=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=t.outShape,this.enableShapeUniforms=de(this.outputShape.length);let i=t.filterHeight,a=t.filterWidth,u=t.outChannels/t.inChannels,l="",c="";n&&(o?l=`float activation(float a) {
| float b = getPreluActivationWeightsAtOutCoords();
| ${n}
| }`:s?l=`float activation(float a) {
| float b = getLeakyreluAlphaAtOutCoords();
| ${n}
| }`:l=`
| float activation(float x) {
| ${n}
| }
| `,c="result = activation(result);");let p=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
| ${l}
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords.x;
| ivec2 xRCCorner = coords.yz * strides - pads;
| int d2 = coords.w;
| int d1 = d2 / ${u};
| int q = d2 - d1 * ${u};
|
| int xRCorner = xRCCorner.x;
| int xCCorner = xRCCorner.y;
|
| // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
| // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
| for (int wR = 0; wR < ${i}; wR++) {
| int xR = xRCorner + wR * dilations[0];
|
| if (xR < 0 || xR >= inDims[0]) {
| continue;
| }
|
| for (int wC = 0; wC < ${a}; wC++) {
| int xC = xCCorner + wC * dilations[1];
|
| if (xC < 0 || xC >= inDims[1]) {
| continue;
| }
|
| float xVal = getX(batch, xR, xC, d1);
| float wVal = getW(wR, wC, d1, q);
| dotProd += xVal * wVal;
| }
| }
|
| float result = dotProd;
| ${p}
| ${c}
| setOutput(result);
| }
| `}};var Wd=class{constructor(t,e=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=t.outShape,this.enableShapeUniforms=de(this.outputShape.length);let i=t.outChannels/t.inChannels,a=t.padInfo.left,u=t.strideWidth,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,m=p,f=`
| int xR; int xC; int xCOffset;
| vec4 wTexel; vec4 previous; vec4 final;`;for(let x=0;x<p;x++)f+=`
| vec4 xTexelC${x*2};
| int xTexelC${x*2}Ready;
| vec4 xTexelC${x*2+1};
| int xTexelC${x*2+1}Ready;
| vec4 xC${x};`;f+=`
| for (int r = 0; r < ${c}; r++) {
| `;for(let x=0;x<p;x++)f+=`
| xTexelC${x*2} = vec4(0.0);
| xTexelC${x*2}Ready = 0;
| xTexelC${x*2+1} = vec4(0.0);
| xTexelC${x*2+1}Ready = 0;
| xC${x} = vec4(0.0);`;f+=`
| xR = xRCorner + r * dilations[0];
| if (xR >=0 && xR < inDims[0]) {
| `;for(let x=0;x<(m+1)/2;x++){let b=x*2;if(f+=`
| xC = xCCorner + ${b*l};
| `,u===1){if(b<p&&(a%2===1?(f+=`
| xCOffset = xC + 1;
| if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
| xTexelC${b} = getX(batch, xR, xCOffset, d1);
|
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${b}.zw = vec2(0.0);
| }
| xTexelC${b}Ready = 1;
| }
| `,l===1&&b>0?f+=`
| xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
| `:f+=`
| xCOffset = xC + 1 - 2;
|
| if (xCOffset >= 0 && xCOffset < inDims[1]) {
| previous = getX(batch, xR, xCOffset, d1);
|
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| previous.zw = vec2(0.0);
| }
|
| xC${b} = vec4(previous.zw, xTexelC${b}.xy);
| } else {
| xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
| }
| `):f+=`
| if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
| xTexelC${b} = getX(batch, xR, xC, d1);
| if (xC + 1 >= inDims[1]) {
| xTexelC${b}.zw = vec2(0.0);
| }
| xTexelC${b}Ready = 1;
| }
|
| xC${b} = xTexelC${b};
| `,b+1<p)){let w=a%2===0?y.nearestLargerEven(l):l;l%2===0&&a%2===1||l%2!==0&&a%2!==1?(f+=`
| xCOffset = xC + imod(pads[1], 2) + ${w};
|
| if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
| xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
|
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${b+1}.zw = vec2(0.0);
| }
| xTexelC${b+1}Ready = 1;
| }
| `,l>1?f+=`
| xCOffset -= 2;
| if (xCOffset >= 0 && xCOffset < inDims[1]) {
| previous = getX(batch, xR, xCOffset, d1);
| xC${b+1} = vec4(previous.zw, xTexelC${b+1}.xy);
| } else {
| xC${b+1} = vec4(0.0, 0.0, xTexelC${b+1}.xy);
| }
| `:f+=`
| xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
| `):w===1?f+=`
| xC${b+1} = xTexelC${b};
| `:f+=`
| xCOffset = xC + ${w};
|
| if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
| xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${b+1}.zw = vec2(0.0);
| }
| xTexelC${b+1}Ready = 1;
| }
|
| xC${b+1} = xTexelC${b+1};
| `}}else b<p&&(a%2===1?(f+=`
| xCOffset = xC + 1 - strides[1];
| if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
| xTexelC${b} = getX(batch, xR, xCOffset, d1);
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${b}.zw = vec2(0.0);
| }
| xTexelC${b}Ready = 1;
| }
|
| if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) {
| xTexelC${b+1} = getX(batch, xR, xC + 1, d1);
| // Need to manually clear unused channels in case
| // we're reading from recycled texture.
| if (xC + 2 >= inDims[1]) {
| xTexelC${b+1}.zw = vec2(0.0);
| }
| xTexelC${b+1}Ready = 1;
| }
|
| xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
| `,b+1<p&&(f+=`
| final = vec4(0.0);
| xCOffset = xC + 1 + strides[1];
| if(xCOffset >= 0 && xCOffset < inDims[1]) {
| final = getX(batch, xR, xCOffset, d1);
| }
| xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy);
| `)):(f+=`
| if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
| xTexelC${b} = getX(batch, xR, xC, d1);
| if (xC + 1 >= inDims[1]) {
| xTexelC${b}.zw = vec2(0.0);
| }
| xTexelC${b}Ready = 1;
| }
|
| xCOffset = xC + strides[1];
| if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
| xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
| if (xCOffset + 1 >= inDims[1]) {
| xTexelC${b+1}.zw = vec2(0.);
| }
| xTexelC${b+1}Ready = 1;
| }
|
| xC${b} = vec4(
| xTexelC${b}.xy, xTexelC${b+1}.xy);
| `,b+1<p&&(f+=`
| xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
| `)));b<p&&(f+=`
| wTexel = getW(r, ${b}, d1, q);
| dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
| `,b+1<p&&(f+=`
| wTexel = getW(r, ${b+1}, d1, q);
| dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
| `))}f+=`
| }
| `,f+=`
| }
| `;let d="",h="";n&&(o?d=`vec4 activation(vec4 a) {
| vec4 b = getPreluActivationWeightsAtOutCoords();
| ${n}
| }`:s?d=`vec4 activation(vec4 a) {
| vec4 b = getLeakyreluAlphaAtOutCoords();
| ${n}
| }`:d=`vec4 activation(vec4 x) {
| ${n}
| }`,h="result = activation(result);");let g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
| ${d}
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords.x;
| ivec2 xRCCorner = coords.yz * strides - pads;
| int d2 = coords.w;
| int d1 = d2 / ${i};
| int q = d2 - d1 * ${i};
| int xRCorner = xRCCorner.x;
| int xCCorner = xRCCorner.y;
|
| //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
| vec4 dotProd = vec4(0.000000000000001);
|
| ${f}
|
| vec4 result = dotProd - vec4(0.000000000000001);
| ${g}
| ${h}
| setOutput(result);
| }
| `}};function Gst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u,dimRoundingMode:l}=n,c=u;c==null&&(c=[1,1]),y.assert(S.eitherStridesOrDilationsAreOne(i,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let p=S.computeConv2DInfo(o.shape,s.shape,i,c,a,l,!0),m;L().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?m=new Wd(p):m=new Gd(p);let f=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return e.runWebGLProgram(m,[o,s],"float32",f)}var nB={kernelName:us,backendName:"webgl",kernelFunc:Gst};var MI=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,n=t.strideWidth,o=t.padInfo.top,s=t.padInfo.left,i=t.outChannels/t.inChannels;this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int wR = coords.x;
| int wC = coords.y;
| int d1 = coords.z;
| int dm = coords.w;
| int d2 = d1 * ${i} + dm;
|
| float dotProd = 0.0;
|
| // TO DO: Vec4 over the batch size
| for (int b = 0; b < ${t.batchSize}; b++) {
| for (int yR = 0; yR < ${t.outHeight}; yR++) {
| int xR = wR + yR * ${e} - ${o};
|
| if (xR < 0 || xR >= ${t.inHeight}) {
| continue;
| }
|
| for (int yC = 0; yC < ${t.outWidth}; yC++) {
| int xC = wC + yC * ${n} - ${s};
|
| if (xC < 0 || xC >= ${t.inWidth}) {
| continue;
| }
|
| float dyValue = getDy(b, yR, yC, d2);
| float xValue = getX(b, xR, xC, d1);
| dotProd += (xValue * dyValue);
| }
| }
| }
| setOutput(dotProd);
| }
| `}},LI=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,n=t.filterWidth,o=t.strideHeight,s=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left,u=t.outChannels/t.inChannels;this.userCode=`
| const ivec2 pads = ivec2(${i}, ${a});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords[0];
| int d1 = coords[3];
| ivec2 dyCorner = coords.yz - pads;
| int dyRCorner = dyCorner.x;
| int dyCCorner = dyCorner.y;
|
| float dotProd = 0.0;
|
| for (int wR = 0; wR < ${e}; wR++) {
| float dyR = float(dyRCorner + wR) / ${o}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| int wRPerm = ${e} - 1 - wR;
|
| for (int wC = 0; wC < ${n}; wC++) {
| float dyC = float(dyCCorner + wC) / ${s}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| int wCPerm = ${n} - 1 - wC;
|
| // TO DO: Vec4 over the channelMul
| for (int dm = 0; dm < ${u}; dm++) {
| int d2 = d1 * ${u} + dm;
| float xValue = getDy(batch, idyR, idyC, d2);
| float wValue = getW(wRPerm, wCPerm, d1, dm);
| dotProd += xValue * wValue;
| }
| }
| }
| setOutput(dotProd);
| }
| `}};function Wst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,dilations:a,pad:u,dimRoundingMode:l,filterShape:c}=n,p=S.computeConv2DInfo(o.shape,c,i,a,u,l,!0),m=new MI(p);return e.runWebGLProgram(m,[o,s],"float32")}var oB={kernelName:Vp,backendName:"webgl",kernelFunc:Wst};function Ust(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{strides:i,dilations:a,pad:u,dimRoundingMode:l,inputShape:c}=n,p=S.computeConv2DInfo(c,s.shape,i,a,u,l,!0),m=new LI(p);return e.runWebGLProgram(m,[o,s],"float32")}var sB={kernelName:Gp,backendName:"webgl",kernelFunc:Ust};var zI=class{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=`
| void main() {
| ivec2 coords = getOutputCoords();
| float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
| setOutput(val);
| }
| `}};function Hst(r){let{inputs:t,backend:e}=r,{x:n}=t,o=[...n.shape,...n.shape],s=y.sizeFromShape(n.shape),i=rt({inputs:{x:n},backend:e,attrs:{shape:[s]}}),a=new zI(s),u=e.runWebGLProgram(a,[i],i.dtype),l=rt({inputs:{x:u},backend:e,attrs:{shape:o}});return e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(u),l}var iB={kernelName:ru,backendName:"webgl",kernelFunc:Hst};var BI=class{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let{inHeight:e,inWidth:n,padInfo:o,strideHeight:s,strideWidth:i,filterHeight:a,filterWidth:u,dilationHeight:l,dilationWidth:c}=t,{top:p,left:m}=o;this.userCode=`
| const ivec2 strides = ivec2(${s}, ${i});
| const ivec2 pads = ivec2(${p}, ${m});
| const float neg_infinity = -3.4e38;
|
| void main() {
| ivec4 coords = getOutputCoords();
| int batch = coords.x;
| int d1 = coords.w;
| ivec2 outTopLeftCorner =
| coords.yz * strides - pads;
| int hBeg = outTopLeftCorner.x;
| int wBeg = outTopLeftCorner.y;
|
| float curVal = neg_infinity;
| for (int h = 0; h < ${a}; h++) {
| int hIn = hBeg + h * ${l};
|
| if (hIn >= 0 && hIn < ${e}) {
| for (int w = 0; w < ${u}; w++) {
| int wIn = wBeg + w * ${c};
|
| if (wIn >= 0 && wIn < ${n}) {
| float xVal = getX(batch, hIn, wIn, d1);
| float wVal = getW(h, w, d1);
|
| float val = xVal + wVal;
| if (val > curVal) {
| curVal = val;
| }
| }
| }
| }
| }
|
| float result = curVal;
| setOutput(result);
| }
| `}};function qst(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n,l=S.computeDilation2DInfo(o.shape,s.shape,i,a,"NHWC",u),c,p=new BI(l);c=e.runWebGLProgram(p,[o,s],"float32");let m=rt({inputs:{x:c},backend:e,attrs:{shape:l.outShape}});return e.disposeIntermediateTensorInfo(c),m}var aB={kernelName:cs,backendName:"webgl",kernelFunc:qst};function Kst(r){let{inputs:t,backend:e,attrs:n}=r,{equation:o}=n,s=t,{allDims:i,summedDims:a,idDims:u}=S.decodeEinsumEquation(o,s.length);S.checkEinsumDimSizes(i.length,u,s);let{path:l,steps:c}=S.getEinsumComputePath(a,u),p=c.length,m=null,f=i.length,d=[];for(let h=0;h<p;++h){for(let g of c[h]){let{permutationIndices:x,expandDims:b}=S.getEinsumPermutation(f,u[g]),w;S.isIdentityPermutation(x)?w=s[g]:(w=Pe({inputs:{x:s[g]},backend:e,attrs:{perm:x}}),d.push(w));let I=w.shape.slice();for(let N=0;N<b.length;++N)I.splice(b[N],0,1);y.arraysEqual(w.shape,I)||(w=rt({inputs:{x:w},backend:e,attrs:{shape:I}}),d.push(w)),m===null?m=w:(m=fg({inputs:{a:w,b:m},backend:e}),d.push(m))}h<p-1&&(l[h]>=0&&(m=Cp({inputs:{x:m},backend:e,attrs:{axis:l[h]-(i.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&e.disposeIntermediateTensorInfo(h);return m}var lB={kernelName:Wp,backendName:"webgl",kernelFunc:Kst};var jst="return (x >= 0.0) ? x : (exp(x) - 1.0);",Xst=`
| vec4 result;
|
| result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
| result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
| result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
| result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
|
| return result;
| `,Yst=It({opSnippet:jst,packedOpSnippet:Xst}),uB={kernelName:ms,backendName:"webgl",kernelFunc:Yst};var Zst="return (b >= 0.0) ? a : a * (b + 1.0);",Jst=`
| vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
| return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
| `,Qst=r=>{let{inputs:t,backend:e}=r,{dy:n,y:o}=t,s=L().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Jn(Jst,n.shape,o.shape):new On(Zst,n.shape,o.shape);return e.runWebGLProgram(s,[n,o],n.dtype)},cB={kernelName:Ga,backendName:"webgl",kernelFunc:Qst};var tit=`
| return vec4(equal(a, b));
| `,eit="return float(a == b);",rit=ue({opSnippet:eit,packedOpSnippet:tit,dtype:"bool",cpuKernelImpl:GL}),pB={kernelName:Wa,backendName:"webgl",kernelFunc:rit};var nit=`
| // Error function is calculated approximately with elementary function.
| // See "Handbook of Mathematical Functions with Formulas,
| // Graphs, and Mathematical Tables", Abramowitz and Stegun.
| float p = ${S.ERF_P};
| float a1 = ${S.ERF_A1};
| float a2 = ${S.ERF_A2};
| float a3 = ${S.ERF_A3};
| float a4 = ${S.ERF_A4};
| float a5 = ${S.ERF_A5};
|
| float sign = sign(x);
| x = abs(x);
| float t = 1.0 / (1.0 + p * x);
| return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
| `,oit=It({opSnippet:nit}),mB={kernelName:fs,backendName:"webgl",kernelFunc:oit};var sit=Vo+`
| return exp(x);
| `,iit=`
| vec4 result = exp(x);
| bvec4 isNaN = isnan(x);
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `,R1=It({opSnippet:sit,packedOpSnippet:iit,cpuKernelImpl:WL,dtype:"float32"}),fB={kernelName:ds,backendName:"webgl",kernelFunc:R1};function VI(r){let{inputs:t,attrs:e,backend:n}=r,{dim:o}=e,{input:s}=t,i=s.shape.length,a=s.shape.slice(),u=o;return o<0&&(y.assert(-(i+1)<=o,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),u=i+o+1),a.splice(u,0,1),rt({inputs:{x:s},backend:n,attrs:{shape:a}})}var dB={kernelName:Li,backendName:"webgl",kernelFunc:VI};var hB="return exp(x) - 1.0;",ait=It({opSnippet:hB,packedOpSnippet:hB,cpuKernelImpl:UL}),gB={kernelName:hs,backendName:"webgl",kernelFunc:ait};var gg=class{constructor(t,e,n){this.variableNames=["real","imag"];let o=e[1];this.outputShape=e;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=n?`${o}.0`:"1.0",a;if(t==="real")a="return real * expR - imag * expI;";else if(t==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);this.userCode=`
| const float exponentMultiplier = ${s};
|
| float unaryOpComplex(float real, float expR, float imag, float expI) {
| ${a}
| }
|
| float mulMatDFT(int batch, int index) {
| float indexRatio = float(index) / float(${o});
| float exponentMultiplierTimesIndexRatio =
| exponentMultiplier * indexRatio;
|
| float result = 0.0;
|
| for (int i = 0; i < ${o}; i++) {
| // x = (-2|2 * PI / N) * index * i;
| float x = exponentMultiplierTimesIndexRatio * float(i);
| float expR = cos(x);
| float expI = sin(x);
| float real = getReal(batch, i);
| float imag = getImag(batch, i);
|
| result +=
| unaryOpComplex(real, expR, imag, expI) / ${i};
| }
|
| return result;
| }
|
| void main() {
| ivec2 coords = getOutputCoords();
| setOutput(mulMatDFT(coords[0], coords[1]));
| }
| `}};function GI(r,t,e){let n=e.texData.get(r.dataId),o=y.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],i=o/s,a=rt({inputs:{x:r},backend:e,attrs:{shape:[i,s]}}),u=a.shape,l=new gg("real",u,t),c=new gg("imag",u,t),p=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:u},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:u}],m=e.runWebGLProgram(l,p,"float32"),f=e.runWebGLProgram(c,p,"float32"),d=Pn({inputs:{real:m,imag:f},backend:e});e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f);let h=rt({inputs:{x:d},backend:e,attrs:{shape:r.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(d),h}function lit(r){let{inputs:t,backend:e}=r,{input:n}=t;return GI(n,!1,e)}var xB={kernelName:Up,backendName:"webgl",kernelFunc:lit};var WI=class{constructor(t,e){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=t,this.userCode=`
| void main() {
| // Input can be obtained from uniform value.
| setOutput(value);
| }
| `}};function Hl(r){let{backend:t,attrs:e}=r,{shape:n,value:o}=e,{dtype:s}=e;if(s=s||y.inferDtype(o),s==="string"){let i=y.getArrayFromDType(s,y.sizeFromShape(n));return i.fill(o),t.makeTensorInfo(n,s,i)}else{let i=new WI(n,o),a=[[o]];return t.runWebGLProgram(i,[],s,a)}}var yB={kernelName:su,backendName:"webgl",kernelFunc:Hl};var UI=class{constructor(t){this.variableNames=["Image"],this.outputShape=[];let e=t[2];this.outputShape=t,this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int x = coords[2];
|
| int coordX = ${e} - x - 1;
| float outputValue;
| if(coordX >= 0 && coordX < ${e}) {
| outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
| } else {
| outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
| }
| setOutput(outputValue);
| }
| `}};var bB={kernelName:Ua,backendName:"webgl",kernelFunc:({inputs:r,backend:t})=>{let{image:e}=r,n=t,o=new UI(e.shape);return n.runWebGLProgram(o,[e],e.dtype)}};var wB="return floor(x);",uit=It({opSnippet:wB,packedOpSnippet:wB,cpuKernelImpl:HL}),IB={kernelName:gs,backendName:"webgl",kernelFunc:uit};var cit=`
| float s = sign(a) * sign(b);
| int ia = round(a);
| int ib = round(b);
| if (ib != 0) {
| // Windows (D3D) wants guaranteed non-zero int division at compile-time.
| return float(idiv(ia, ib, s));
| } else {
| return NAN;
| }
| `,pit=`
| ivec4 ia = round(a);
| ivec4 ib = round(b);
| bvec4 cond = notEqual(ib, ivec4(0));
| ivec4 result = ivec4(0);
| vec4 s = sign(a) * sign(b);
|
| // Windows (D3D) wants guaranteed non-zero int division at compile-time.
| if (cond[0]) {
| result[0] = idiv(ia[0], ib[0], s[0]);
| }
| if (cond[1]) {
| result[1] = idiv(ia[1], ib[1], s[1]);
| }
| if (cond[2]) {
| result[2] = idiv(ia[2], ib[2], s[2]);
| }
| if (cond[3]) {
| result[3] = idiv(ia[3], ib[3], s[3]);
| }
| return vec4(result);
| `,mit=ue({opSnippet:cit,packedOpSnippet:pit,dtype:"int32"}),CB={kernelName:xs,backendName:"webgl",kernelFunc:mit};var HI=class{constructor(t){this.variableNames=["A"];let e=We(),[n,o]=t;this.outputShape=t,this.userCode=`
| void main() {
| ivec3 coords = getOutputCoords();
| int texR = coords[0];
| int texC = coords[1];
| int depth = coords[2];
| vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}.0, ${n}.0);
|
| vec4 values = ${e.texture2D}(A, uv);
| float value;
| if (depth == 0) {
| value = values.r;
| } else if (depth == 1) {
| value = values.g;
| } else if (depth == 2) {
| value = values.b;
| } else if (depth == 3) {
| value = values.a;
| }
|
| setOutput(floor(value * 255.0 + 0.5));
| }
| `}};var qI=class{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let e=We(),[n,o]=t;this.outputShape=t,this.userCode=`
| void main() {
| ivec3 coords = getOutputCoords();
| int texR = coords[0];
| int texC = coords[1];
| int depth = coords[2];
|
| vec4 result = vec4(0.);
|
| for(int row=0; row<=1; row++) {
| for(int col=0; col<=1; col++) {
| texC = coords[1] + row;
| depth = coords[2] + col;
|
| vec2 uv = (vec2(texC, texR) + halfCR) /
| vec2(${o}.0, ${n}.0);
| vec4 values = ${e.texture2D}(A, uv);
| float value;
| if (depth == 0) {
| value = values.r;
| } else if (depth == 1) {
| value = values.g;
| } else if (depth == 2) {
| value = values.b;
| } else if (depth == 3) {
| value = values.a;
| }
|
| result[row * 2 + col] = floor(value * 255.0 + 0.5);
| }
| }
|
| ${e.output} = result;
| }
| `}};var vB={kernelName:oh,backendName:"webgl",kernelFunc:fit},Ud,F1=L().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function fit(r){let{inputs:t,backend:e,attrs:n}=r,{pixels:o}=t,{numChannels:s}=n,i=typeof HTMLVideoElement!="undefined"&&o instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&o instanceof HTMLImageElement,[u,l]=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],c=[l,u],p=[l,u,s];if(a||i){let h=L().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Ud==null||h!==F1)&&(F1=h,Ud=document.createElement("canvas").getContext("2d",{willReadFrequently:F1})),Ud.canvas.width=u,Ud.canvas.height=l,Ud.drawImage(o,0,0,u,l),o=Ud.canvas}let m=e.makeTensorInfo(c,"int32");e.texData.get(m.dataId).usage=Jr.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(m.dataId),o);let f=L().getBool("WEBGL_PACK")?new qI(p):new HI(p),d=e.runWebGLProgram(f,[m],"int32");return e.disposeData(m.dataId),d}function dit(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=S.convertConv2DDataFormat(c),g=S.computeConv2DInfo(o.shape,s.shape,u,p,l,m,!1,h),x,b=[],w=i!=null,I=a!=null,N=f==="leakyrelu",E=()=>{let D=[o,s],F=(P,V)=>{if(V==="NCHW"&&P.shape.length===1&&P.shape[0]!==1){let G=rt({inputs:{x:P},backend:e,attrs:{shape:[P.shape[0],1,1]}});return b.push(G),G}return P};if(w&&D.push(F(i,c)),I&&D.push(F(a,c)),N){let P=e.makeTensorInfo([],"float32",y.createScalarValue(d,"float32"));D.push(P),b.push(P)}return D};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))x=TI({x:o,filter:s,convInfo:g,backend:e,bias:i,activation:f,preluActivationWeights:a,leakyreluAlpha:d});else if(g.strideWidth<=2&&h==="channelsLast"&&L().getBool("WEBGL_EXP_CONV")){let D=f?Wl(f,!0):null,F=new Vd(g,w,D,I,N),P=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],V=E();x=e.runWebGLProgram(F,V,"float32",P)}else if(L().getBool("WEBGL_CONV_IM2COL"))x=_I({x:o,filter:s,convInfo:g,backend:e,bias:i,activation:f,preluActivationWeights:a,leakyreluAlpha:d});else{let D=f?Wl(f,!1):null,F=new Bd(g,w,D,I,N),P=E();x=e.runWebGLProgram(F,P,"float32")}let A=rt({inputs:{x},backend:e,attrs:{shape:g.outShape}});return b.push(x),b.forEach(D=>e.disposeIntermediateTensorInfo(D)),A}var SB={kernelName:Ji,backendName:"webgl",kernelFunc:dit};function hit(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:p,activation:m,leakyreluAlpha:f}=n,d=[],h=c;h==null&&(h=[1,1]),y.assert(S.eitherStridesOrDilationsAreOne(u,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${h}'`);let g=S.computeConv2DInfo(o.shape,s.shape,u,h,l,p,!0),x=L().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=m?Wl(m,x):null,w=[o,s],I=i!=null,N=a!=null,E=m==="leakyrelu";if(I&&w.push(i),N&&w.push(a),E){let P=e.makeTensorInfo([],"float32",y.createScalarValue(f,"float32"));w.push(P),d.push(P)}let A;x?A=new Wd(g,I,b,N,E):A=new Gd(g,I,b,N,E);let D=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],F=e.runWebGLProgram(A,w,"float32",D);return d.forEach(P=>e.disposeIntermediateTensorInfo(P)),F}var NB={kernelName:Qi,backendName:"webgl",kernelFunc:hit};var KI=class{constructor(t,e,n,o){this.sliceDim=t,this.strides=e,this.paramsShape=o,this.variableNames=["x","indices"],this.outputShape=n;let s=zt(n.length),i=`
| int index;`;for(let a=0;a<this.sliceDim;a++)i+=`
| index = round(getIndices(coords[0], ${a}));
| out_of_bounds = out_of_bounds || index < 0;
| out_of_bounds = out_of_bounds || index >= ${this.paramsShape[a]};
| flattenIndex += index * ${this.strides[a]};`;this.userCode=`
| void main() {
| ${s} coords = getOutputCoords();
| int flattenIndex = 0;
| bool out_of_bounds = false;
|
| ${i}
|
| setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
| }
| `}};function git(r){let{inputs:t,backend:e}=r,{params:n,indices:o}=t,s=o.shape,i=s[s.length-1],a=y.sizeFromShape(n.shape),[u,l,c,p]=S.prepareAndValidate(n,o),m=rt({inputs:{x:o},backend:e,attrs:{shape:[l,i]}}),f=rt({inputs:{x:n},backend:e,attrs:{shape:[y.sizeFromShape(n.shape)/c,c]}});if(e.shouldExecuteOnCPU([n,o])||n.dtype==="string"){let x=e.readSync(o.dataId),b=e.bufferSync(n),w=qL(x,b,n.dtype,l,i,c,p,n.shape,a);return e.makeTensorInfo(u,n.dtype,w.values)}let d=new KI(i,p,[l,c],n.shape),h=e.runWebGLProgram(d,[f,m],f.dtype),g=rt({inputs:{x:h},backend:e,attrs:{shape:u}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(h),g}var kB={kernelName:Ha,backendName:"webgl",kernelFunc:git};var jI=class{constructor(t,e){this.variableNames=["A","indices"],this.outputShape=e,this.rank=e.length;let n=zt(this.rank),o=xit(t,2);this.userCode=`
| void main() {
| ${n} resRC = getOutputCoords();
| int index = int(getIndices(resRC.x, resRC.z));
| float inBounds = (index >= 0) && (index < ${t[2]}) ? 1.0 : 0.0;
| setOutput(inBounds * getA(${o}));
| }
| `}};function xit(r,t){let e=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let o=0;o<r.length;o++)o===2?n.push("index"):n.push(`${e[o]}`);return n.join()}function O1(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,indices:s}=t,{axis:i,batchDims:a}=n,u=y.parseAxisParam(i,o.shape)[0];if(L().get("DEBUG")){let b=e.readSync(s.dataId),w=o.shape[u];for(let I=0;I<b.length;++I){let N=b[I];y.assert(N<=w-1&&N>=0,()=>`GatherV2: the index value ${N} is not in [0, ${w-1}]`)}}let l=S.segment_util.collectGatherOpShapeInfo(o,s,u,a),c=y.sizeFromShape(s.shape),p=[],m=rt({inputs:{x:o},backend:e,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),f=rt({inputs:{x:s},backend:e,attrs:{shape:[l.batchSize,c/l.batchSize]}});p.push(m),p.push(f);let d=[l.batchSize,l.outerSize,c/l.batchSize,l.sliceSize];if(e.shouldExecuteOnCPU([o,s])||o.dtype==="string"){let b=e.bufferSync(f),w=e.bufferSync(m),I=KL(w,b,d);return p.forEach(N=>e.disposeIntermediateTensorInfo(N)),e.makeTensorInfo(l.outputShape,I.dtype,I.values)}let h=new jI(m.shape,d),g=e.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let x=rt({inputs:{x:g},backend:e,attrs:{shape:l.outputShape}});return p.forEach(b=>e.disposeIntermediateTensorInfo(b)),x}var TB={kernelName:zi,backendName:"webgl",kernelFunc:O1};var yit="return float(a > b);",bit=`
| return vec4(greaterThan(a, b));
| `,wit=ue({opSnippet:yit,packedOpSnippet:bit,cpuKernelImpl:jL,dtype:"bool"}),_B={kernelName:qa,backendName:"webgl",kernelFunc:wit};var Iit="return float(a >= b);",Cit=`
| return vec4(greaterThanEqual(a, b));
| `,vit=ue({opSnippet:Iit,packedOpSnippet:Cit,dtype:"bool",cpuKernelImpl:XL}),EB={kernelName:bs,backendName:"webgl",kernelFunc:vit};function Sit(r){let{inputs:t,backend:e}=r,{input:n}=t;return GI(n,!0,e)}var AB={kernelName:Hp,backendName:"webgl",kernelFunc:Sit};var Nit="return float(!isnan(x) && !isinf(x));",kit=It({opSnippet:Nit,dtype:"bool"}),DB={kernelName:ws,backendName:"webgl",kernelFunc:kit};var Tit="return float(isinf(x));",_it=It({opSnippet:Tit,dtype:"bool"}),$B={kernelName:Is,backendName:"webgl",kernelFunc:_it};var Eit="return float(isnan(x));",Ait=It({opSnippet:Eit,dtype:"bool"}),RB={kernelName:Cs,backendName:"webgl",kernelFunc:Ait};var Dit="return float(a < b);",$it=`
| return vec4(lessThan(a, b));
| `,Rit=ue({opSnippet:Dit,packedOpSnippet:$it,cpuKernelImpl:YL,dtype:"bool"}),FB={kernelName:Ka,backendName:"webgl",kernelFunc:Rit};var Fit="return float(a <= b);",Oit=`
| return vec4(lessThanEqual(a, b));
| `,Pit=ue({opSnippet:Fit,packedOpSnippet:Oit,cpuKernelImpl:ZL,dtype:"bool"}),OB={kernelName:ja,backendName:"webgl",kernelFunc:Pit};function Mit(r){let{backend:t,attrs:e}=r,{start:n,stop:o,num:s}=e,i=JL(n,o,s);return t.makeTensorInfo([i.length],"float32",i)}var PB={kernelName:Xa,backendName:"webgl",kernelFunc:Mit};var Lit=Vo+`
| return x < 0.0 ? 0./0. : log(x);
| `,zit=`
| vec4 result = log(x);
| bvec4 isNaN = isnan(x);
| result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
| result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
| result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
| result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
| return result;
| `,Bit=It({opSnippet:Lit,packedOpSnippet:zit,cpuKernelImpl:QL}),MB={kernelName:Ss,backendName:"webgl",kernelFunc:Bit};var Vit=Vo+`
| return log(1.0 + x);
| `,Git=It({opSnippet:Vit}),LB={kernelName:Ns,backendName:"webgl",kernelFunc:Git};var Wit="return float(a >= 1.0 && b >= 1.0);",Uit=`
| return vec4(
| vec4(greaterThanEqual(a, vec4(1.0))) *
| vec4(greaterThanEqual(b, vec4(1.0))));
| `,Hit=ue({opSnippet:Wit,packedOpSnippet:Uit,dtype:"bool"}),zB={kernelName:Ya,backendName:"webgl",kernelFunc:Hit};var qit="return float(!(x >= 1.0));",Kit=It({opSnippet:qit}),BB={kernelName:Za,backendName:"webgl",kernelFunc:Kit};var jit="return float(a >= 1.0 || b >= 1.0);",Xit=`
| return min(
| vec4(greaterThanEqual(a, vec4(1.0))) +
| vec4(greaterThanEqual(b, vec4(1.0))),
| vec4(1.0));
| `,Yit=ue({opSnippet:jit,packedOpSnippet:Xit,dtype:"bool"}),VB={kernelName:Ja,backendName:"webgl",kernelFunc:Yit};var XI=class{constructor(t,e,n,o,s){this.variableNames=["x"],this.outputShape=[];let i=e,a=t[3]-1;this.outputShape=t;let u,l=`float(${n}) + float(${o}) * sum`;s===.5?u=`inversesqrt(${l})`:s===1?u=`1.0/(${l})`:u=`exp(log(${l}) * float(-${s}));`,this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int r = coords[1];
| int c = coords[2];
| int d = coords[3];
| float x = getX(b, r, c, d);
| float sum = 0.0;
| for (int j = -${i}; j <= ${i}; j++) {
| int idx = d + j;
| if (idx >= 0 && idx <= ${a}) {
| float z = getX(b, r, c, idx);
| sum += z * z;
| }
| }
| float val = x * ${u};
| setOutput(val);
| }
| `}};var YI=class{constructor(t,e,n,o,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let i=e,a=t[3]-1;this.outputShape=t;let u,l=`float(${n}) + float(${o}) * sum`;s===.5?u=`inversesqrt(${l})`:s===1?u=`1.0/(${l})`:u=`exp(log(${l}) * float(-${s}));`,this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords.x;
| int r = coords.y;
| int c = coords.z;
| int d = coords.w;
|
| bool hasNextCol = d < ${this.outputShape[3]};
| bool hasNextRow = c < ${this.outputShape[2]};
|
| vec4 sum = vec4(0.);
| vec4 xFragAtOutputCoords = getX(b, r, c, d);
|
| vec4 xAtOutputCoords = vec4(
| getChannel(xFragAtOutputCoords, vec2(c, d)),
| hasNextCol ?
| getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
| hasNextRow ?
| getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
| (hasNextRow && hasNextCol) ?
| getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
| );
|
| int firstChannel = d - ${i};
| vec2 cache = vec2(0.);
| if(firstChannel >= 0){
| vec4 firstChannelFrag = getX(b, r, c, firstChannel);
| cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
| if(hasNextRow){
| cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
| }
| }
|
| ivec2 depth = ivec2(d, d + 1);
| for (int j = - ${i}; j <= ${i}; j++) {
| ivec2 idx = depth + j;
| bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
| bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
|
| bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
| bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
| if(depthInRange || depthPlusOneInRange){
| vec4 z = vec4(0.);
| vec4 xFragAtCurrentDepth;
| z.xz = cache.xy;
| if(depthPlusOneInRange && hasNextCol){
| xFragAtCurrentDepth = idx.y != d ?
| getX(b, r, c, idx.y) : xFragAtOutputCoords;
| z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
| if(hasNextRow){
| z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
| }
| }
| cache.xy = z.yw;
| sum += z * z;
| }
| }
| vec4 result = xAtOutputCoords * ${u};
| setOutput(result);
| }
| `}};var Zit=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{depthRadius:s,bias:i,alpha:a,beta:u}=n,l=L().getBool("WEBGL_PACK_NORMALIZATION")?new YI(o.shape,s,i,a,u):new XI(o.shape,s,i,a,u);return e.runWebGLProgram(l,[o],o.dtype)},GB={kernelName:ks,backendName:"webgl",kernelFunc:Zit};var ZI=class{constructor(t,e,n,o,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=o,this.beta=s,this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int r = coords[1];
| int c = coords[2];
|
| float result = 0.0;
| for (int d = 0; d < ${this.depth}; ++d) {
| int depthBegin = int(max(0.0, float(d - ${e})));
| int depthEnd = int(min(float(${this.depth}),
| float(d + ${e} + 1)));
|
| const int MIN_DEPTH_BEGIN = 0;
| const int MAX_DEPTH_END = ${this.depth};
|
| float norm = 0.0;
| for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
| if (k < depthBegin){
| continue;
| }
| else if (k >= depthBegin && k < depthEnd) {
| norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
| }
| else {
| break;
| }
| }
|
| norm = float(${o}) * norm + float(${n});
|
| for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
| if (k < depthBegin){
| continue;
| }
| else if (k >= depthBegin && k < depthEnd){
| float dyi = -2.0 * float(${o})
| * float(${s})
| * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
| / norm;
| if (k == d) {
| dyi += pow(norm, -1.0 * ${s});
| }
| if (k == coords[3]) {
| dyi *= getDy(b, r, c, d);
| result += dyi;
| }
| }
| else {
| break;
| }
| }
| }
| setOutput(result);
| }
| `}};var Jit=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o,y:s,dy:i}=t,{depthRadius:a,bias:u,alpha:l,beta:c}=n,p=new ZI(o.shape,a,u,l,c);return e.runWebGLProgram(p,[o,s,i],o.dtype)},WB={kernelName:Qa,backendName:"webgl",kernelFunc:Jit};function UB(r,t,e,n){let o=y.sizeFromShape(t),i=y.sizeFromShape(r.shape)/o,a=rt({inputs:{x:r},attrs:{shape:[i,o]},backend:n}),u=to(a,r.dtype,"max",n),l=rt({inputs:{x:u},attrs:{shape:e},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(u),l}function P1(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reductionIndices:s,keepDims:i}=n,a=o.shape.length,u=y.parseAxisParam(s,o.shape),l=u,c=S.getAxesPermutation(l,a),p=c!=null,m=e.shouldExecuteOnCPU([o]),f=o;if(p){if(m){let w=e.texData.get(f.dataId).values,I=new Array(a);for(let A=0;A<I.length;A++)I[A]=o.shape[c[A]];let N=Ip(w,o.shape,o.dtype,c,I);f=e.makeTensorInfo(I,o.dtype);let E=e.texData.get(f.dataId);E.values=N}else f=tc(o,c,e);l=S.getInnerMostAxes(l.length,a)}S.assertAxesAreInnerMostDims("max",l,a);let[d,h]=S.computeOutAndReduceShapes(f.shape,l),g=d;i&&(g=S.expandShapeToKeepDim(d,u));let x;if(m){let w=e.texData.get(f.dataId).values,I=tz(w,y.sizeFromShape(h),g,o.dtype);x=e.makeTensorInfo(g,o.dtype);let N=e.texData.get(x.dataId);N.values=I}else x=UB(f,h,g,e);return p&&e.disposeIntermediateTensorInfo(f),x}var HB={kernelName:Ts,backendName:"webgl",kernelFunc:P1};var Qit=Md+`
| return max(a, b);
| `,tat=`
| vec4 result = vec4(max(a, b));
| bvec4 isNaNA = isnan(a);
| bvec4 isNaNB = isnan(b);
| bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
| `+Qn+`
| return result;
| `,eat=ue({opSnippet:Qit,packedOpSnippet:tat,cpuKernelImpl:ez}),qB={kernelName:_s,backendName:"webgl",kernelFunc:eat};function rat(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;Ni(o,"maxPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=n,l=1;y.assert(S.eitherStridesOrDilationsAreOne(i,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=S.computePool2DInfo(o.shape,s,i,l,a,u);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return rr({inputs:{x:o},backend:e});let p=new Ti(c,"max",!1);return e.runWebGLProgram(p,[o],o.dtype)}var KB={kernelName:Es,backendName:"webgl",kernelFunc:rat};function nat(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dataFormat:u,dimRoundingMode:l}=n,c=[1,1,1],p=S.computePool3DInfo(o.shape,s,i,c,a,l,u),m=new ec(p,"max",!1);return e.runWebGLProgram(m,[o],o.dtype)}var jB={kernelName:Bi,backendName:"webgl",kernelFunc:nat};var JI=class{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideHeight,n=t.strideWidth,o=t.dilationHeight,s=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=s-1-t.padInfo.top,u=i-1-t.padInfo.left,l=s*i-1;this.userCode=`
| const ivec2 pads = ivec2(${a}, ${u});
|
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
|
| ivec2 dyRCCorner = coords.yz - pads;
| int dyRCorner = dyRCCorner.x;
| int dyCCorner = dyRCCorner.y;
|
| // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
| for (int wR = 0; wR < ${s};
| wR += ${o}) {
| float dyR = float(dyRCorner + wR) / ${e}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| for (int wC = 0; wC < ${i}; wC++) {
| float dyC = float(dyCCorner + wC) / ${n}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| float dyValue = getDy(b, idyR, idyC, d);
| int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
|
| // Get the current value, check it against the value from the
| // position matrix.
| int curPosValue = wR * ${i} + wC;
| float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
| dotProd += dyValue * mask;
| }
| }
| setOutput(dotProd);
| }
| `}},QI=class{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideDepth,n=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,i=t.dilationHeight,a=t.dilationWidth,u=t.effectiveFilterDepth,l=t.effectiveFilterHeight,c=t.effectiveFilterWidth,p=u-1-t.padInfo.front,m=l-1-t.padInfo.top,f=c-1-t.padInfo.left,d=u*l*c-1;this.userCode=`
| const ivec3 pads = ivec3(${p}, ${m}, ${f});
|
| void main() {
| ivec5 coords = getOutputCoords();
| int batch = coords.x;
| int ch = coords.u;
|
| ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
| int dyDCorner = dyCorner.x;
| int dyRCorner = dyCorner.y;
| int dyCCorner = dyCorner.z;
|
| // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
| // dx(xD, xR, xC, ch).
| // ? = to be determined. : = across all values in that axis.
| float dotProd = 0.0;
|
| for (int wD = 0; wD < ${u};
| wD += ${s}) {
| float dyD = float(dyDCorner + wD) / ${e}.0;
|
| if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
| continue;
| }
| int idyD = int(dyD);
|
| for (int wR = 0; wR < ${l};
| wR += ${i}) {
| float dyR = float(dyRCorner + wR) / ${n}.0;
|
| if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
| fract(dyR) > 0.0) {
| continue;
| }
| int idyR = int(dyR);
|
| for (int wC = 0; wC < ${c};
| wC += ${a}) {
| float dyC = float(dyCCorner + wC) / ${o}.0;
|
| if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
| fract(dyC) > 0.0) {
| continue;
| }
| int idyC = int(dyC);
|
| float dyValue = getDy(batch, idyD, idyR, idyC, ch);
| int maxPosValue = ${d} -
| int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
| // Get the current value, check it against the value from the
| // position matrix.
| int curPosValue =
| wD * ${l} * ${c} +
| wR * ${c} + wC;
| float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
| dotProd += dyValue * mask;
| }
| }
| }
| setOutput(dotProd);
| }
| `}};function oat(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s,{filterSize:a,strides:u,pad:l,dimRoundingMode:c}=n,p=[1,1,1],m=S.computePool3DInfo(i.shape,a,u,p,l,c),f=new ec(m,"max",!0),d=e.runWebGLProgram(f,[i],i.dtype),h=new QI(m),g=e.runWebGLProgram(h,[o,d],i.dtype);return e.disposeIntermediateTensorInfo(d),g}var XB={kernelName:au,backendName:"webgl",kernelFunc:oat};function sat(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s,output:i}=t,a=s;Ni([s,i],"maxPoolGrad");let{filterSize:u,strides:l,pad:c,dimRoundingMode:p}=n,m=S.computePool2DInfo(a.shape,u,l,1,c,p),f=!0,d=new Ti(m,"max",f),h=e.runWebGLProgram(d,[a],a.dtype),g=new JI(m),x=e.runWebGLProgram(g,[o,h],a.dtype);return e.disposeIntermediateTensorInfo(h),x}var YB={kernelName:iu,backendName:"webgl",kernelFunc:sat};function ZB(r,t,e,n){let o=new Ti(e,"max",!1),s=n.runWebGLProgram(o,[r],"float32");o=new Ti(e,"max",!0,!0,t);let i=n.runWebGLProgram(o,[r],"float32");return[s,i]}var JB={kernelName:lu,backendName:"webgl",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{x:n}=r,{filterSize:o,strides:s,pad:i,includeBatchInIndex:a}=t,u=e;y.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let l=[1,1];y.assert(S.eitherStridesOrDilationsAreOne(s,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${l}'`);let c=S.computePool2DInfo(n.shape,o,s,l,i),[p,m]=ZB(n,a,c,u);return[p,m]}};function QB(r,t,e,n){let o=y.sizeFromShape(t),i=y.sizeFromShape(r.shape)/o,a=rt({inputs:{x:r},attrs:{shape:[i,o]},backend:n}),u=to(a,"float32","mean",n),l=rt({inputs:{x:u},attrs:{shape:e},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(u),l}var tV={kernelName:As,backendName:"webgl",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{x:n}=r,{keepDims:o,axis:s}=t,i=e,a=n.shape.length,u=y.parseAxisParam(s,n.shape),l=u,c=S.getAxesPermutation(l,a),p=c!=null,m=i.shouldExecuteOnCPU([n]),f=[],d=n;if(p){if(m){let I=i.texData.get(d.dataId).values,N=new Array(a);for(let D=0;D<N.length;D++)N[D]=n.shape[c[D]];let E=Ip(I,n.shape,n.dtype,c,N);d=i.makeTensorInfo(N,n.dtype);let A=i.texData.get(d.dataId);A.values=E}else d=tc(n,c,i);f.push(d),l=S.getInnerMostAxes(l.length,a)}S.assertAxesAreInnerMostDims("sum",l,a);let[h,g]=S.computeOutAndReduceShapes(d.shape,l),x=h;o&&(x=S.expandShapeToKeepDim(h,u));let b=QB(d,g,x,i);for(let w of f)i.disposeIntermediateTensorInfo(w);return b}};function iat(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=y.parseAxisParam(s,o.shape),l=u,c=S.getAxesPermutation(l,a),p=o;c!=null&&(p=Pe({inputs:{x:o},backend:e,attrs:{perm:c}}),l=S.getInnerMostAxes(l.length,o.shape.length)),S.assertAxesAreInnerMostDims("min",l,a);let[m,f]=S.computeOutAndReduceShapes(p.shape,l),d=y.sizeFromShape(f),h=rt({inputs:{x:p},backend:e,attrs:{shape:[-1,d]}}),g=to(h,h.dtype,"min",e),x;if(i){let b=S.expandShapeToKeepDim(m,u);x=rt({inputs:{x:g},backend:e,attrs:{shape:b}})}else x=rt({inputs:{x:g},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),c!=null&&e.disposeIntermediateTensorInfo(p),x}var eV={kernelName:Ds,backendName:"webgl",kernelFunc:iat};var aat=Md+`
| return min(a, b);
| `,lat=`
| vec4 result = vec4(min(a, b));
| bvec4 isNaNA = isnan(a);
| bvec4 isNaNB = isnan(b);
| bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
| `+Qn+`
| return result;
| `,uat=ue({opSnippet:aat,packedOpSnippet:lat,cpuKernelImpl:rz}),rV={kernelName:$s,backendName:"webgl",kernelFunc:uat};var tC=class{constructor(t,e,n){this.variableNames=["x"],this.outputShape=e.map((c,p)=>c[0]+t[p]+c[1]);let o=t.length,s=zt(o),i=e.map(c=>c[0]).join(","),a=e.map((c,p)=>c[0]+t[p]).join(","),u=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o),l=n==="reflect"?0:1;if(o===1){this.userCode=`
| int start = ${i};
| int end = ${a};
|
| void main() {
| int outC = getOutputCoords();
| if (outC < start) {
| outC = start * 2 - outC - ${l};
| } else if(outC >= end) {
| outC = (end - 1) * 2 - outC + ${l};
| }
| setOutput(getX(outC - start));
| }
| `;return}this.userCode=`
| ${s} start = ${s}(${i});
| ${s} end = ${s}(${a});
|
| void main() {
| ${s} outC = getOutputCoords();
| for (int i = 0; i < ${o}; i++) {
| if (outC[i] < start[i]) {
| outC[i] = start[i] * 2 - outC[i] - ${l};
| } else if(outC[i] >= end[i]) {
| outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
| }
| }
| ${s} coords = outC - start;
| setOutput(getX(${u}));
| }
| `}};var eC=class{constructor(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((d,h)=>d[0]+t[h]+d[1]);let o=t.length,s=zt(o),i=e.map(d=>d[0]).join(","),a=e.map((d,h)=>d[0]+t[h]).join(","),u=er("rc",o),l=er("source",o),c=`${u[o-1]} < ${this.outputShape[o-1]}`,p=o===1?"source":`vec2(${l.slice(-2).join()})`,m=n==="reflect"?0:1,f="";if(o===1){let d=`
| ${s} source = rc;
| if (source < start) {
| source = start * 2 - source - ${m};
| } else if (source >= end) {
| source = (end - 1) * 2 - source + ${m};
| }
| source -= start;
| `;f=`
| ${s} rc = outputLoc;
| ${d}
| result[0] = getChannel(getX(${l.join()}), ${p});
| ${u[o-1]} += 1;
| if(${c}) {
| ${d}
| result[1] = getChannel(getX(${l.join()}), ${p});
| }
| `}else{let d=`
| ${s} source = rc;
| ${s} lt = ${s}(lessThan(source, start));
| ${s} gte = ${s}(greaterThanEqual(source, end));
| ${s} orig = 1 - (lt + gte);
| source = orig * source +
| lt * (start * 2 - source - ${m}) +
| gte * ((end - 1) * 2 - source + ${m});
| source -= start;
| `;f=`
| ${s} rc = outputLoc;
| ${d}
| result[0] = getChannel(getX(${l.join()}), ${p});
| ${u[o-1]} += 1;
| if(${c}) {
| ${d}
| result[1] = getChannel(getX(${l.join()}), ${p});
| }
| rc = outputLoc;
| ${u[o-2]} += 1;
| if(${u[o-2]} < ${this.outputShape[o-2]}) {
| ${d}
| result[2] = getChannel(getX(${l.join()}), ${p});
| ${u[o-1]} += 1;
| if(${c}) {
| ${d}
| result[3] = getChannel(getX(${l.join()}), ${p});
| }
| }
| `}this.userCode=`
| const ${s} start = ${s}(${i});
| const ${s} end = ${s}(${a});
|
| void main() {
| ${s} outputLoc = getOutputCoords();
| vec4 result = vec4(0.);
| ${f}
| setOutput(result);
| }
| `}};var cat=({inputs:r,backend:t,attrs:e})=>{let{x:n}=r,{paddings:o,mode:s}=e,i=L().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new eC(n.shape,o,s):new tC(n.shape,o,s);return t.runWebGLProgram(i,[n],n.dtype)},nV={kernelName:Rs,backendName:"webgl",kernelFunc:cat};var pat=`if (b == 0.0) return NAN;
| return mod(a, b);`,mat=`
| vec4 result = mod(a, b);
| bvec4 isNaN = equal(b, vec4(0.0));
| `+Qn+`
| return result;
| `,fat=ue({opSnippet:pat,packedOpSnippet:mat}),oV={kernelName:Fs,backendName:"webgl",kernelFunc:fat};var rC=class{constructor(t,e,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[t,n],this.userCode=`
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
|
| float r = random(seed);
| float cdf = 0.0;
|
| for (int i = 0; i < ${e-1}; i++) {
| cdf += getProbs(batch, i);
|
| if (r < cdf) {
| setOutput(float(i));
| return;
| }
| }
|
| // If no other event happened, last event happened.
| setOutput(float(${e-1}));
| }
| `}};var dat=`
| if (a == b) {
| return 1.0;
| };
| return a / b;`,hat=`
| // vec4 one = vec4(equal(a, b));
| // return one + (vec4(1.0) - one) * a / b;
| vec4 result = a / b;
| if(a.x == b.x) {
| result.x = 1.;
| }
| if(a.y == b.y) {
| result.y = 1.;
| }
| if(a.z == b.z) {
| result.z = 1.;
| }
| if(a.w == b.w) {
| result.w = 1.;
| }
|
| return result;
| `,M1=ue({opSnippet:dat,packedOpSnippet:hat,checkOutOfBounds:!0}),sV={kernelName:ps,backendName:"webgl",kernelFunc:M1};var iV="return a - b;",L1=ue({opSnippet:iV,packedOpSnippet:iV,supportsComplex:!0,cpuKernelImpl:vz}),aV={kernelName:si,backendName:"webgl",kernelFunc:L1};function z1(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{dim:s}=n,i=y.parseAxisParam([s],o.shape),a=P1({inputs:{x:o},backend:e,attrs:{reductionIndices:i,keepDims:!1}}),u=S.expandShapeToKeepDim(a.shape,i),l=rt({inputs:{x:a},backend:e,attrs:{shape:u}}),c=L1({inputs:{a:o,b:l},backend:e}),p=R1({inputs:{x:c},backend:e}),m=Cp({inputs:{x:p},backend:e,attrs:{axis:i,keepDims:!1}}),f=rt({inputs:{x:m},backend:e,attrs:{shape:u}}),d=M1({inputs:{a:p,b:f},backend:e});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),d}var lV={kernelName:ni,backendName:"webgl",kernelFunc:z1};function gat(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{numSamples:s,seed:i,normalized:a}=n,u=a?o:z1({inputs:{logits:o},backend:e,attrs:{dim:o.shape.length-1}}),l=u.shape[0],c=u.shape[1],p=new rC(l,c,s),m=[[i]],f=e.runWebGLProgram(p,[u],"int32",m);return a||e.disposeIntermediateTensorInfo(u),f}var uV={kernelName:tl,backendName:"webgl",kernelFunc:gat};var xat=yr+`
| return -x;
| `,yat=`
| vec4 result = -x;
| bvec4 isNaN = isnan(x);
|
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `;function bat(r){let{inputs:t,backend:e}=r,{x:n}=t;if(e.shouldExecuteOnCPU([n])){let s=e.texData.get(n.dataId),[i,a]=oz(s.values,n.shape,n.dtype);return e.makeTensorInfo(a,n.dtype,i)}let o;return L().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Fn(n.shape,yat):o=new Br(n.shape,xat),e.runWebGLProgram(o,[n],n.dtype)}var cV={kernelName:Vi,backendName:"webgl",kernelFunc:bat};var wat=jr.nonMaxSuppressionV3Impl;function Iat(r){S.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u}=n,l=e.readSync(o.dataId),c=e.readSync(s.dataId),{selectedIndices:p}=wat(l,c,i,a,u);return e.makeTensorInfo([p.length],"int32",new Int32Array(p))}var pV={kernelName:rl,backendName:"webgl",kernelFunc:Iat};var Cat=jr.nonMaxSuppressionV4Impl;function vat(r){S.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u,padToMaxOutputSize:l}=n,c=e.readSync(o.dataId),p=e.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=Cat(c,p,i,a,u,l);return[e.makeTensorInfo([m.length],"int32",new Int32Array(m)),e.makeTensorInfo([],"int32",new Int32Array([f]))]}var mV={kernelName:nl,backendName:"webgl",kernelFunc:vat};var Sat=jr.nonMaxSuppressionV5Impl;function Nat(r){S.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u,softNmsSigma:l}=n,c=e.readSync(o.dataId),p=e.readSync(s.dataId),m=i,f=a,d=u,h=l,{selectedIndices:g,selectedScores:x}=Sat(c,p,m,f,d,h);return[e.makeTensorInfo([g.length],"int32",new Int32Array(g)),e.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var fV={kernelName:ol,backendName:"webgl",kernelFunc:Nat};var nC=class{constructor(t,e,n,o){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`
| void main() {
| ivec2 coords = getOutputCoords();
| int index = round(getIndices(coords.x));
| setOutput(mix(float(${o}), float(${n}),
| float(index == coords.y)));
| }
| `}};var kat=r=>{let{inputs:t,backend:e,attrs:n}=r,{indices:o}=t,{dtype:s,depth:i,onValue:a,offValue:u}=n,l=y.sizeFromShape(o.shape),c=new nC(l,i,a,u),p=rt({inputs:{x:o},backend:e,attrs:{shape:[l]}}),m=e.runWebGLProgram(c,[p],s);e.disposeIntermediateTensorInfo(p);let f=[...o.shape,i],d=rt({inputs:{x:m},backend:e,attrs:{shape:f}});return e.disposeIntermediateTensorInfo(m),d},dV={kernelName:Ps,backendName:"webgl",kernelFunc:kat};function xg(r){let{inputs:t,backend:e}=r,{x:n}=t;if(n.dtype==="complex64"){let o=Ul({inputs:{input:n},backend:e}),s=xg({inputs:{x:o},backend:e}),i=Sp({inputs:{input:n},backend:e}),a=xg({inputs:{x:i},backend:e}),u=Pn({inputs:{real:s,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),u}else return Hl({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:e})}var hV={kernelName:Yi,backendName:"webgl",kernelFunc:xg};function gV(r){let{inputs:t,backend:e}=r,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let o=Ul({inputs:{input:n},backend:e}),s=gV({inputs:{x:o},backend:e}),i=Sp({inputs:{input:n},backend:e}),a=xg({inputs:{x:i},backend:e}),u=Pn({inputs:{real:s,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),u}else return Hl({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:e})}var xV={kernelName:Gi,backendName:"webgl",kernelFunc:gV};function Tat(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n;if(t.length===1)return VI({inputs:{input:t[0]},backend:e,attrs:{dim:o}});let s=t[0].shape,i=t[0].dtype;t.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(i===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],u=t.map(c=>{let p=VI({inputs:{input:c},backend:e,attrs:{dim:o}});return a.push(p),p}),l=$1({inputs:u,backend:e,attrs:{axis:o}});return a.forEach(c=>e.disposeIntermediateTensorInfo(c)),l}var yV={kernelName:Wi,backendName:"webgl",kernelFunc:Tat};var oC=class{constructor(t,e,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((l,c)=>l[0]+t[c]+l[1]);let o=t.length,s=zt(o),i=e.map(l=>l[0]).join(","),a=e.map((l,c)=>l[0]+t[c]).join(","),u=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o);if(o===1){this.userCode=`
| int start = ${i};
| int end = ${a};
|
| void main() {
| int outC = getOutputCoords();
| if (outC < start || outC >= end) {
| setOutput(value);
| } else {
| setOutput(getX(outC - start));
| }
| }
| `;return}this.userCode=`
| ${s} start = ${s}(${i});
| ${s} end = ${s}(${a});
|
| void main() {
| ${s} outC = getOutputCoords();
| if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
| setOutput(value);
| } else {
| ${s} coords = outC - start;
| setOutput(getX(${u}));
| }
| }
| `}};var sC=class{constructor(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((h,g)=>h[0]+t[g]+h[1]);let o=t.length,s=zt(o),i=e.map(h=>h[0]).join(","),a=e.map((h,g)=>h[0]+t[g]).join(","),u=er("rc",o),l=er("source",o),c=`${u[o-1]} < ${this.outputShape[o-1]}`,p=o===1?"source":`vec2(${l.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${u[o-1]} += 1;
| if(${c}) {
| `,o===1?"":`}
| rc = outputLoc;
| ${u[o-2]} += 1;
| if(${u[o-2]} < ${this.outputShape[o-2]}) {`,o===1?"":` ${u[o-1]} += 1;
| if(${c}) {`],f=o===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="";for(let h=0,g=o===1?2:4;h<g;h++)d+=`
| ${m[h]}
| if (${f}) {
| result[${h}] = float(value);
| } else {
| ${s} source = rc - start;
| result[${h}] = getChannel(getX(${l.join()}), ${p});
| }
| `;d+=o===1?"} ":"}}",this.userCode=`
| const ${s} start = ${s}(${i});
| const ${s} end = ${s}(${a});
|
| void main() {
| ${s} outputLoc = getOutputCoords();
| vec4 result = vec4(0.);
| ${d}
| setOutput(result);
| }
| `}};var B1=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{paddings:s,constantValue:i}=n;if(y.sizeFromShape(o.shape)===0){let l=s.map((c,p)=>c[0]+o.shape[p]+c[1]);return Hl({backend:e,attrs:{shape:l,value:i,dtype:o.dtype}})}let a=L().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new sC(o.shape,s,i):new oC(o.shape,s,i),u=[[i]];return e.runWebGLProgram(a,[o],o.dtype,u)},bV={kernelName:Ms,backendName:"webgl",kernelFunc:B1};var _at=`
| if(a < 0.0 && floor(b) < b){
| return NAN;
| }
| if (b == 0.0) {
| return 1.0;
| }
| return (round(mod(b, 2.0)) != 1) ?
| pow(abs(a), b) : sign(a) * pow(abs(a), b);
| `,Eat=`
| // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
| vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
| vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
| vec4 result = multiplier * pow(abs(a), b);
|
| // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
| bvec4 isExpZero = equal(b, vec4(0.0));
| result.r = isExpZero.r ? 1.0 : result.r;
| result.g = isExpZero.g ? 1.0 : result.g;
| result.b = isExpZero.b ? 1.0 : result.b;
| result.a = isExpZero.a ? 1.0 : result.a;
|
| bvec4 isNaN1 = lessThan(a, vec4(0.0));
| bvec4 isNaN2 = lessThan(floor(b), b);
| bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
| `+Qn+`
| return result;
| `,Aat=ue({opSnippet:_at,packedOpSnippet:Eat}),wV={kernelName:Ls,backendName:"webgl",kernelFunc:Aat};function Dat(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=[],l=y.parseAxisParam(s,o.shape),c=l,p=S.getAxesPermutation(c,a),m=o;p!=null&&(m=Pe({inputs:{x:o},backend:e,attrs:{perm:p}}),c=S.getInnerMostAxes(c.length,a),u.push(m)),S.assertAxesAreInnerMostDims("prod",c,a);let f;if(e.shouldExecuteOnCPU([m])){let d=e.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:x}=iz(m.shape,m.dtype,d,c);f=e.makeTensorInfo(g,x,h)}else{let[d,h]=S.computeOutAndReduceShapes(m.shape,c),g=y.sizeFromShape(h),x=rt({inputs:{x:m},backend:e,attrs:{shape:[-1,g]}}),b=xc(o.dtype),w=to(x,b,"prod",e);f=rt({inputs:{x:w},backend:e,attrs:{shape:d}}),u.push(x),u.push(w)}if(i){u.push(f);let d=S.expandShapeToKeepDim(f.shape,l);f=rt({inputs:{x:f},backend:e,attrs:{shape:d}})}return u.forEach(d=>e.disposeIntermediateTensorInfo(d)),f}var IV={kernelName:Bs,backendName:"webgl",kernelFunc:Dat};function $at(r){let{inputs:t,backend:e,attrs:n}=r,{paramsNestedSplits:o,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:a}=n,u=o.map(x=>e.readSync(x.dataId)),l=o.map(x=>x.shape),c=e.readSync(s.dataId),p=e.readSync(i.dataId),[m,f,d]=az(u,l,c,s.shape,s.dtype,p,i.shape,a),h=m.map(x=>e.makeTensorInfo([x.length],"int32",x)),g=e.makeTensorInfo(d,s.dtype,f);return h.concat([g])}var CV={kernelName:Kp,backendName:"webgl",kernelFunc:$at};function Rat(r){let{inputs:t,backend:e}=r,{starts:n,limits:o,deltas:s}=t,i=e.readSync(n.dataId),a=e.readSync(o.dataId),u=e.readSync(s.dataId),[l,c]=lz(i,n.shape,n.dtype,a,o.shape,u,s.shape),p=e.makeTensorInfo([l.length],"int32",l),m=e.makeTensorInfo([c.length],n.dtype,c);return[p,m]}var vV={kernelName:jp,backendName:"webgl",kernelFunc:Rat};function Fat(r){let{inputs:t,backend:e,attrs:n}=r,{shape:o,values:s,defaultValue:i,rowPartitionTensors:a}=t,{rowPartitionTypes:u}=n,l=e.readSync(o.dataId),c=e.readSync(s.dataId),p=e.readSync(i.dataId),m=a.map(g=>e.readSync(g.dataId)),f=a.map(g=>g.shape),[d,h]=uz(l,o.shape,c,s.shape,s.dtype,p,i.shape,m,f,u);return e.makeTensorInfo(d,s.dtype,h)}var SV={kernelName:Xp,backendName:"webgl",kernelFunc:Fat};var V1=r=>{let{backend:t,attrs:e}=r,{start:n,stop:o,step:s,dtype:i}=e,a=cz(n,o,s,i);return t.makeTensorInfo([a.length],i,a)},NV={kernelName:uu,backendName:"webgl",kernelFunc:V1};var Oat="return 1.0 / x;",Pat=It({opSnippet:Oat}),kV={kernelName:Vs,backendName:"webgl",kernelFunc:Pat};var Mat=yr+`
| return (x < 0.0) ? 0.0 : x;
| `,Lat=`
| vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
| bvec4 isNaN = isnan(x);
|
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `,zat=It({opSnippet:Mat,packedOpSnippet:Lat}),TV={kernelName:Gs,backendName:"webgl",kernelFunc:zat};var Bat=yr+`
| return (x < 0.0) ? 0.0 : min(6.0, x);
| `,Vat=`
| vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
| bvec4 isNaN = isnan(x);
|
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `,Gat=It({opSnippet:Bat,packedOpSnippet:Vat}),_V={kernelName:Hs,backendName:"webgl",kernelFunc:Gat};var iC=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m;s?m="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":m="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
| const vec2 effectiveInputOverOutputRatioRC = vec2(
| ${c[0]/p[0]},
| ${c[1]/p[1]});
| const vec2 inputShapeRC = vec2(${a}.0, ${u}.0);
|
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
| ivec2 yRC = coords.yz;
|
| // Fractional source index.
| vec2 sourceFracIndexRC = ${m};
|
| // Compute the four integer indices.
| ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
| ivec2 sourceCeilRC = ivec2(
| min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
| float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
| float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
| float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
| float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
|
| vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
|
| float top = topLeft + (topRight - topLeft) * fracRC.y;
| float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
| float newValue = top + (bottom - top) * fracRC.x;
|
| setOutput(newValue);
| }
| `}};var aC=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m;s?m="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":m="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
| const vec3 effectiveInputOverOutputRatioRC = vec3(
| ${c[0]/p[0]},
| ${c[1]/p[1]},
| ${c[1]/p[1]});
| const vec3 inputShapeRC = vec3(${a}.0, ${u}.0,
| ${u}.0);
|
| float getAValue(int b, int r, int c, int d) {
| return getChannel(getA(b, r, c, d), vec2(c, d));
| }
|
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
| // Calculate values for next column in yRC.z.
| ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
| // Fractional source index.
| vec3 sourceFracIndexRC = ${m};
|
| // Compute the four integer indices.
| ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
| ivec3 sourceCeilRC = ivec3(
| min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
| // Should we calculate next column and row elements in 2x2 packed cell.
| bool hasNextCol = d < ${l-1};
| bool hasNextRow = coords.z < ${n-1};
|
| // In parallel, construct four corners for all four components in
| // packed 2x2 cell.
| vec4 topLeft = vec4(
| getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
| hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
| : 0.0,
| hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
| : 0.0,
| (hasNextRow && hasNextCol) ?
| getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
| vec4 bottomLeft = vec4(
| getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
| hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
| : 0.0,
| hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
| : 0.0,
| (hasNextRow && hasNextCol) ?
| getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
| vec4 topRight = vec4(
| getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
| hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
| : 0.0,
| hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
| : 0.0,
| (hasNextRow && hasNextCol) ?
| getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
| vec4 bottomRight = vec4(
| getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
| hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
| : 0.0,
| hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
| : 0.0,
| (hasNextRow && hasNextCol) ?
| getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
| vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
|
| vec4 top = mix(topLeft, topRight, fracRC.yyzz);
| vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
| vec4 newValue = mix(top, bottom, fracRC.x);
|
| setOutput(newValue);
| }
| `}};function Wat(r){let{inputs:t,backend:e,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n,[u,l]=a,c=L().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new aC(o.shape,u,l,s,i):new iC(o.shape,u,l,s,i);return e.runWebGLProgram(c,[o],"float32")}var EV={kernelName:Us,backendName:"webgl",kernelFunc:Wat};var lC=class{constructor(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;let[,o,s]=e,[,i,a]=t,u=[n&&i>1?o-1:o,n&&a>1?s-1:s],l=[n&&i>1?i-1:i,n&&a>1?a-1:a],c=u[0]/l[0],p=u[1]/l[1],m=1/c,f=1/p,d=Math.ceil(m)*2+2,h=Math.ceil(f)*2+2;this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
| int r = coords[1];
| int c = coords[2];
|
| float accumulator = 0.0;
|
| const float heightScale = float(${c});
| const float widthScale = float(${p});
|
| const float invHeightScale = float(${m});
| const float invWidthScale = float(${f});
|
| const int winHeight = int(${d});
| const int winWidth = int(${h});
|
| // Compute bounds for where in dy we will look
| float startRLerp = floor(float(r) * invHeightScale);
| int startDyR = int(startRLerp - float(winHeight / 2));
|
| float startCLerp = floor(float(c) * invWidthScale);
| int startDyC = int(startCLerp - float(winWidth / 2));
|
| // Loop over dy
| for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
| int dyR = dyROffset + startDyR;
|
| // Guard against the window exceeding the bounds of dy
| if (dyR < 0 || dyR >= ${i}) {
| continue;
| }
|
| for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
| int dyC = dyCOffset + startDyC;
|
| // Guard against the window exceeding the bounds of dy
| if (dyC < 0 || dyC >= ${a}) {
| continue;
| }
|
| float dxR = float(dyR) * heightScale;
| int topDxRIndex = int(floor(dxR));
| int bottomDxRIndex = int(min(ceil(dxR), ${o-1}.0));
| float dxRLerp = dxR - float(topDxRIndex);
| float inverseDxRLerp = 1.0 - dxRLerp;
|
| float dxC = float(dyC) * widthScale;
| int leftDxCIndex = int(floor(dxC));
| int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));
| float dxCLerp = dxC - float(leftDxCIndex);
| float inverseDxCLerp = 1.0 - dxCLerp;
|
| if (r == topDxRIndex && c == leftDxCIndex) {
| // topLeft
| accumulator +=
| getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
| }
|
| if (r == topDxRIndex && c == rightDxCIndex) {
| // topRight
| accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
| }
|
| if (r == bottomDxRIndex && c == leftDxCIndex) {
| // bottomLeft
| accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
| }
|
| if (r == bottomDxRIndex && c == rightDxCIndex) {
| // bottomRight
| accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
| }
| }
| }
| // End loop over dy
|
| setOutput(accumulator);
| }
| `}};function Uat(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n,a=new lC(s.shape,o.shape,i);return e.runWebGLProgram(a,[s],s.dtype)}var AV={kernelName:il,backendName:"webgl",kernelFunc:Uat};var uC=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m=o?"0.5":"0.0",f;s?f="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":f="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
| const vec2 effectiveInputOverOutputRatioRC = vec2(
| ${c[0]/p[0]},
| ${c[1]/p[1]});
| const vec2 inputShapeRC = vec2(${a}.0, ${u}.0);
|
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
| ivec2 yRC = coords.yz;
|
| // Fractional source index.
| vec2 sourceFracIndexRC = ${f};
|
| // Compute the coordinators of nearest neighbor point.
| ivec2 sourceNearestRC = ivec2(
| min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
| float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
| setOutput(newValue);
| }
| `}};var cC=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m=o?"0.5":"0.0",f;s?f="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":f="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
| const vec3 effectiveInputOverOutputRatioRC = vec3(
| ${c[0]/p[0]},
| ${c[1]/p[1]},
| ${c[1]/p[1]});
| const vec3 inputShapeRC = vec3(${a}.0, ${u}.0,
| ${u}.0);
|
| float getAValue(int b, int r, int c, int d) {
| return getChannel(getA(b, r, c, d), vec2(c, d));
| }
|
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
| // Calculate values for next column in yRC.z.
| ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
| // Fractional source index.
| vec3 sourceFracIndexRC = ${f};
|
| // Compute the coordinators of nearest neighbor point.
| ivec3 sourceNearestRC = ivec3(
| min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
|
| // Should we calculate next column and row elements in 2x2 packed cell.
| bool hasNextCol = d < ${l-1};
| bool hasNextRow = coords.z < ${n-1};
|
| vec4 newValue = vec4(
| getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
| hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
| : 0.0,
| hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
| : 0.0,
| (hasNextRow && hasNextCol) ?
| getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
| setOutput(newValue);
| }
| `}};function Hat(r){let{inputs:t,backend:e,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n,[u,l]=a,c=L().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cC(o.shape,u,l,s,i):new uC(o.shape,u,l,s,i);return e.runWebGLProgram(c,[o],o.dtype)}var DV={kernelName:Ws,backendName:"webgl",kernelFunc:Hat};var pC=class{constructor(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;let[,o,s]=e,[,i,a]=t,u=[n&&i>1?o-1:o,n&&a>1?s-1:s],l=[n&&i>1?i-1:i,n&&a>1?a-1:a],c=u[0]/l[0],p=u[1]/l[1],m=1/c,f=1/p,d=Math.ceil(m)*2+2,h=Math.ceil(f)*2+2;this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int b = coords[0];
| int d = coords[3];
| int r = coords[1];
| int c = coords[2];
|
| float accumulator = 0.0;
|
| const float heightScale = float(${c});
| const float widthScale = float(${p});
|
| const float invHeightScale = float(${m});
| const float invWidthScale = float(${f});
|
| const int winHeight = int(${d});
| const int winWidth = int(${h});
|
| // Compute bounds for where in dy we will look
| float startRLerp = floor(float(r) * invHeightScale);
| int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
| float startCLerp = floor(float(c) * invWidthScale);
| int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
| // Loop over dy
| for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
| int dyR = dyROffset + startDyR;
|
| // Guard against the window exceeding the bounds of dy
| if (dyR < 0 || dyR >= ${i}) {
| continue;
| }
|
| for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
| int dyC = dyCOffset + startDyC;
|
| // Guard against the window exceeding the bounds of dy
| if (dyC < 0 || dyC >= ${a}) {
| continue;
| }
|
| float sourceFracRow =
| float(${u[0]}) *
| (float(dyR) / float(${l[0]}));
|
| float sourceFracCol =
| float(${u[1]}) *
| (float(dyC) / float(${l[1]}));
|
| int sourceNearestRow = int(min(
| float(int(${o}) - 1),
| ${n} ? float(round(sourceFracRow)) :
| float(floor(sourceFracRow))));
|
| int sourceNearestCol = int(min(
| float(int(${s}) - 1),
| ${n} ? float(round(sourceFracCol)) :
| float(floor(sourceFracCol))));
|
| if (r == sourceNearestRow && c == sourceNearestCol) {
| accumulator += getDy(b, dyR, dyC, d);
| }
| }
| }
| // End loop over dy
|
| setOutput(accumulator);
| }
| `}};function qat(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n,a=new pC(s.shape,o.shape,i);return e.runWebGLProgram(a,[s],s.dtype)}var $V={kernelName:sl,backendName:"webgl",kernelFunc:qat};var mC=class{constructor(t,e){this.variableNames=["x"];let n=t.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=t,n===1){this.userCode=`
| void main() {
| int coord = getOutputCoords();
| setOutput(getX(${t[0]} - coord - 1));
| }
| `;return}let o=a=>e.indexOf(a)!==-1&&t[a]!==1?`${t[a]} - coords[${a}] - 1`:`coords[${a}]`,s=t.map((a,u)=>o(u)).join(","),i=zt(n);this.userCode=`
| void main() {
| ${i} coords = getOutputCoords();
| setOutput(getX(${s}));
| }
| `}};var fC=class{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=t.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=t;let o=er("rc",n),s=`${o[n-1]} + 1 < ${this.outputShape[n-1]}`,i=`${o[n-2]} + 1 < ${this.outputShape[n-2]}`,a=zt(n);n===1?this.userCode=`
| void main(){
| int rc = getOutputCoords();
| vec4 result = vec4(0.);
| result.r = getChannel(getX(${t[0]} - rc - 1),
| ${t[0]} - rc - 1);
| if(${s}){
| result.g = getChannel(getX(${t[0]} - (rc + 1) - 1),
| ${t[0]} - (rc + 1) - 1);
| }
| setOutput(result);
| }
| `:this.userCode=`
| void main() {
| ${a} rc = getOutputCoords();
| vec4 result = vec4(0.);
| result.r = ${u(o.slice())};
| if(${s}){
| result.g = ${l(o.slice())};
| }
| if(${i}) {
| result.b = ${c(o.slice())};
| if(${s}) {
| result.a = ${p(o.slice())};
| }
| }
| setOutput(result);
| }
| `;function u(d){return m(d)}function l(d){return d[n-1]="("+d[n-1]+" + 1)",m(d)}function c(d){return d[n-2]="("+d[n-2]+" + 1)",m(d)}function p(d){return d[n-1]="("+d[n-1]+" + 1)",d[n-2]="("+d[n-2]+" + 1)",m(d)}function m(d){let h=t.map((b,w)=>f(w,d)),g=h.join(","),x=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${x}))`}function f(d,h){return e.indexOf(d)!==-1&&t[d]!==1?`${t[d]} - ${h[d]} - 1`:`${h[d]}`}}};function Kat(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dims:s}=n,i=o.shape.length,a=y.parseAxisParam(s,o.shape);if(i===0)return rr({inputs:{x:o},backend:e});let u=L().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fC(o.shape,a):new mC(o.shape,a);return e.runWebGLProgram(u,[o],o.dtype)}var RV={kernelName:qs,backendName:"webgl",kernelFunc:Kat};var dC=class{constructor(t,e){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=t[1],o=t[2];this.outputShape=t;let s="";typeof e=="number"?s=`float outputValue = ${e.toFixed(2)};`:s=`
| vec3 fill = vec3(${e.join(",")});
| float outputValue = fill[coords[3]];`,this.userCode=`
| void main() {
| ivec4 coords = getOutputCoords();
| int x = coords[2];
| int y = coords[1];
| float coordXFloat = (float(x) - params[0]) * params[3] -
| (float(y) - params[1]) * params[2];
| float coordYFloat = (float(x) - params[0]) * params[2] +
| (float(y) - params[1]) * params[3];
| int coordX = int(round(coordXFloat + params[0]));
| int coordY = int(round(coordYFloat + params[1]));
| ${s}
| if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${n}) {
| outputValue = getImage(coords[0], coordY, coordX, coords[3]);
| }
| setOutput(outputValue);
| }
| `}};var FV={kernelName:hl,backendName:"webgl",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{image:n}=r,{radians:o,fillValue:s,center:i}=t,a=e,u=new dC(n.shape,s),[l,c]=S.getImageCenter(i,n.shape[1],n.shape[2]),p=[[l,c,Math.sin(o),Math.cos(o)]];return a.runWebGLProgram(u,[n],n.dtype,p)}};var jat=`
| // OpenGL ES does not support round function.
| // The algorithm is based on banker's rounding.
| float base = floor(x);
| if ((x - base) < 0.5) {
| return floor(x);
| } else if ((x - base) > 0.5) {
| return ceil(x);
| } else {
| if (mod(base, 2.0) == 0.0) {
| return base;
| } else {
| return base + 1.0;
| }
| }
| `,Xat=It({opSnippet:jat}),OV={kernelName:Ks,backendName:"webgl",kernelFunc:Xat};var Yat="return inversesqrt(x);",Zat=It({opSnippet:Yat,cpuKernelImpl:pz}),PV={kernelName:js,backendName:"webgl",kernelFunc:Zat};var rc=class{constructor(t,e,n,o,s,i,a=!0,u=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;let l=zt(s.length),c=zt(i.length),p="";n===1?p="i":n===2&&(p="i, j");let m=`getIndices(${p})`,f="";o===1?f="i":o===2&&(f="i, coords[1]");let d=`getUpdates(${f})`,h="";u&&(h="coords[0], coords[1]");let g=`getDefaultValue(${h})`,x=e>1?"strides[j]":"strides";this.userCode=`
| ${l} strides = ${l}(${s});
|
| void main() {
| ${c} coords = getOutputCoords();
| float sum = 0.0;
| bool found = false;
| for (int i = 0; i < ${t}; i++) {
| int flattenedIndex = 0;
| for (int j = 0; j < ${e}; j++) {
| int index = round(${m});
| flattenedIndex += index * ${x};
| }
| if (flattenedIndex == coords[0]) {
| sum += ${d};
| found = true;
| }
| }
| setOutput(mix(${g}, sum, float(found)));
| }
| `}};var hC=class{constructor(t,e,n,o,s,i,a=!0,u=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=i;let l=zt(s.length),c=zt(i.length),p="";n===1?p="i":n===2&&(p="i, j");let m=`getIndices(${p})`,f="";o===1?f="i":o===2&&(f="i, coords[1]");let d=`getUpdates(${f})`,h="";u&&(h="coords[0], coords[1]");let g=`getDefaultValue(${h})`,x=e>1?"strides[j]":"strides",b=e>1?"strides[j + 1]":"strides";this.userCode=`
| ${l} strides = ${l}(${s});
|
| void main() {
| ${c} coords = getOutputCoords();
| vec4 sum = vec4(0.);
| vec4 found = vec4(0.);
| for (int i = 0; i < ${t}; i+=2) {
| ivec2 flattenedIndex = ivec2(0);
| for (int j = 0; j < ${e}; j+=2) {
| ivec4 index = round(${m});
| flattenedIndex += index.xz * ${x};
| if (j + 1 < ${e}) {
| flattenedIndex += index.yw * ${b};
| }
| }
| if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
| flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
| vec4 updVals = ${d};
| if (flattenedIndex[0] == coords[0]) {
| sum.xy += updVals.xy;
| found.xy = vec2(1.);
| } else if (flattenedIndex[0] == coords[0] + 1) {
| sum.zw += updVals.xy;
| found.zw = vec2(1.);
| }
| if (flattenedIndex[1] == coords[0]) {
| sum.xy += updVals.zw;
| found.xy = vec2(1.);
| } else if (flattenedIndex[1] == coords[0] + 1) {
| sum.zw += updVals.zw;
| found.zw = vec2(1.);
| }
| }
| }
| setOutput(mix(${g}, sum, found));
| }
| `}};function Jat(r){let{inputs:t,backend:e,attrs:n}=r,{indices:o,updates:s}=t,{shape:i}=n,{sliceRank:a,numUpdates:u,sliceSize:l,strides:c,outputSize:p}=S.calculateShapes(s,o,i),m=[p/l,l];if(p===0)return e.makeTensorInfo(i,o.dtype);let f=rt({inputs:{x:o},backend:e,attrs:{shape:[u,a]}}),d=rt({inputs:{x:s},backend:e,attrs:{shape:[u,l]}}),h=e.makeTensorInfo([],"float32",new Float32Array([0])),g;L().getBool("WEBGL_PACK")?g=new hC(u,a,f.shape.length,d.shape.length,c,m):g=new rc(u,a,f.shape.length,d.shape.length,c,m);let x=e.runWebGLProgram(g,[d,f,h],d.dtype),b=rt({inputs:{x},backend:e,attrs:{shape:i}});return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(h),b}var MV={kernelName:al,backendName:"webgl",kernelFunc:Jat};var gC=class{constructor(t,e,n,o){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[t,n];let s="while (left < right) {",i=`for (int i = 0; i < ${Math.ceil(Math.log2(e+1))}; ++i) { if (left >= right) break;`,a=L().getNumber("WEBGL_VERSION")===2?s:i,u=o==="left"?"<":"<=";this.userCode=`
| int findBound(int batch, float value) {
| int left = 0;
| int right = numInputs;
| int mid;
| ${a}
| mid = (left + right) / 2;
| if (getSortedSequence(batch, mid) ${u} value) {
| left = mid + 1;
| } else {
| right = mid;
| }
| }
| return right;
| }
|
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int valueIndex = coords[1];
|
| float value = getValues(batch, valueIndex);
|
| setOutput(float(findBound(batch, value)));
| }
| `}};function Qat(r){let{inputs:t,backend:e,attrs:n}=r,{sortedSequence:o,values:s}=t,{side:i}=n,a=new gC(o.shape[0],o.shape[1],s.shape[1],i),u=[[o.shape[1]]];return e.runWebGLProgram(a,[o,s],"int32",u)}var LV={kernelName:ul,backendName:"webgl",kernelFunc:Qat};var xC=class{constructor(t,e,n){this.variableNames=["c","a","b"],this.outputShape=e;let o,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",o="resRC";else{let a=["resRC.x","resRC.y","resRC.z","resRC.w"],u=[],l=[];for(let c=0;c<e.length;c++)l.push(`${a[c]}`),c<t&&u.push(`${a[c]}`);o=u.join(),s=l.join()}let i=zt(n);this.userCode=`
| void main() {
| ${i} resRC = getOutputCoords();
| float cVal = getC(${o});
| if (cVal >= 1.0) {
| setOutput(getA(${s}));
| } else {
| setOutput(getB(${s}));
| }
| }
| `}};function tlt(r){let{inputs:t,backend:e}=r,{condition:n,t:o,e:s}=t,i=new xC(n.shape.length,o.shape,o.shape.length);return e.runWebGLProgram(i,[n,o,s],ur(o.dtype,s.dtype))}var zV={kernelName:Hi,backendName:"webgl",kernelFunc:tlt};var elt=`
| // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
| // see: https://arxiv.org/abs/1706.02515
| float scaleAlpha = ${S.SELU_SCALEALPHA};
| float scale = ${S.SELU_SCALE};
| return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
| `,rlt=It({opSnippet:elt}),BV={kernelName:Xs,backendName:"webgl",kernelFunc:rlt};var nlt=Vo+`
| return 1.0 / (1.0 + exp(-1.0 * x));
| `,olt=`
| vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
| bvec4 isNaN = isnan(x);
|
| result.r = isNaN.r ? x.r : result.r;
| result.g = isNaN.g ? x.g : result.g;
| result.b = isNaN.b ? x.b : result.b;
| result.a = isNaN.a ? x.a : result.a;
|
| return result;
| `,slt=It({opSnippet:nlt,packedOpSnippet:olt,cpuKernelImpl:fz}),VV={kernelName:Qs,backendName:"webgl",kernelFunc:slt};var ilt=`
| if (isnan(x)) { return 0.0; }
| return sign(x);
| `,alt=It({opSnippet:ilt}),GV={kernelName:Js,backendName:"webgl",kernelFunc:alt};var llt=Vo+`
| return sin(x);
| `,ult=`
| vec4 result = sin(x);
| bvec4 isNaN = isnan(x);
| ${Qn}
| return result;
| `,clt=It({opSnippet:llt,packedOpSnippet:ult}),WV={kernelName:Ys,backendName:"webgl",kernelFunc:clt};var plt=`
| float e2x = exp(x);
| return (e2x - 1.0 / e2x) / 2.0;
| `,mlt=It({opSnippet:plt}),UV={kernelName:Zs,backendName:"webgl",kernelFunc:mlt};var flt=`
| float epsilon = 1.1920928955078125e-7;
| float threshold = log(epsilon) + 2.0;
|
| bool too_large = x > -threshold;
| bool too_small = x < threshold;
|
| float result;
| float exp_x = exp(x);
|
| if (too_large){
| result = x;
| }
| else if (too_small){
| result = exp_x;
| }
| else{
| result = log(exp_x + 1.0);
| }
| return result;
| `,dlt=It({opSnippet:flt}),HV={kernelName:ti,backendName:"webgl",kernelFunc:dlt};var hlt=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,paddings:i}=n;y.assert(o.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let a=s.reduce((x,b)=>x*b),u=[[0,0]];u.push(...i);for(let x=1+s.length;x<o.shape.length;++x)u.push([0,0]);let l=[],c=B1({inputs:{x:o},backend:e,attrs:{paddings:u,constantValue:0}}),p=S.getReshaped(c.shape,s,a,!1),m=S.getPermuted(p.length,s.length,!1),f=S.getReshapedPermuted(c.shape,s,a,!1),d=rt({inputs:{x:c},backend:e,attrs:{shape:p}}),h=Pe({inputs:{x:d},backend:e,attrs:{perm:m}}),g=rt({inputs:{x:h},backend:e,attrs:{shape:f}});return l.push(c),l.push(d),l.push(h),l.forEach(x=>e.disposeIntermediateTensorInfo(x)),g},qV={kernelName:Ki,backendName:"webgl",kernelFunc:hlt};function glt(r){let{inputs:t,backend:e}=r,{indices:n,values:o,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
| ${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
| ${n.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
| ${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
| ${i.shape}`);let a=e.readSync(n.dataId),u=e.readSync(o.dataId),l=e.readSync(s.dataId),c=e.readSync(i.dataId)[0],[p,m,f,d,h]=hz(a,n.shape,n.dtype,u,o.dtype,l,c);return[e.makeTensorInfo(m,n.dtype,p),e.makeTensorInfo([m[0]],o.dtype,f),e.makeTensorInfo([d.length],"bool",new Uint8Array(d.map(g=>Number(g)))),e.makeTensorInfo([h.length],n.dtype,new Int32Array(h))]}var KV={kernelName:cu,backendName:"webgl",kernelFunc:glt};function xlt(r){let{inputs:t,backend:e}=r,{inputIndices:n,inputShape:o,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(e.readSync(o.dataId)),a=e.readSync(n.dataId),u=Array.from(e.readSync(s.dataId)),[l,c,p]=gz(a,n.shape,n.dtype,i,u);return[e.makeTensorInfo(c,n.dtype,l),e.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var jV={kernelName:cl,backendName:"webgl",kernelFunc:xlt};function ylt(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
| ${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
| ${s.shape}`);let i=e.readSync(n.dataId),a=e.readSync(o.dataId),u=e.readSync(s.dataId),[l,c]=Jw(i,n.shape,n.dtype,a,u,!0);return e.makeTensorInfo(c,n.dtype,l)}var XV={kernelName:pu,backendName:"webgl",kernelFunc:ylt};function blt(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
| ${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
| ${s.shape}`);let i=e.readSync(n.dataId),a=e.readSync(o.dataId),u=e.readSync(s.dataId),[l,c]=Jw(i,n.shape,n.dtype,a,u);return e.makeTensorInfo(c,n.dtype,l)}var YV={kernelName:mu,backendName:"webgl",kernelFunc:blt};function wlt(r){let{inputs:t,backend:e,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=t,{outputShape:a}=n,{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:m}=S.calculateShapes(s,o,a),f=!1;if(s.dtype==="string"){let x=e.bufferSync(o),b=e.bufferSync(s),w=y.decodeString(e.readSync(i.dataId)[0]),I=mz(x,b,a,m,c,l,u,p,w,f);return e.makeTensorInfo(a,I.dtype,I.values)}let d=new rc(l,u,o.shape.length,s.shape.length,p,[m,1],f),h=e.runWebGLProgram(d,[s,o,i],s.dtype),g=rt({inputs:{x:h},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(h),g}var ZV={kernelName:pl,backendName:"webgl",kernelFunc:wlt};function Ilt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{numOrSizeSplits:s,axis:i}=n,a=y.parseAxisParam(i,o.shape)[0],u=S.prepareSplitSize(o,s,a),l=o.shape.length,c=new Array(l).fill(0),p=o.shape.slice();return u.map(m=>{let f=[...p];f[a]=m;let d=_i({inputs:{x:o},backend:e,attrs:{begin:c,size:f}});return c[a]+=m,d})}var JV={kernelName:ji,backendName:"webgl",kernelFunc:Ilt};var QV="return sqrt(x);",Clt=It({opSnippet:QV,packedOpSnippet:QV,cpuKernelImpl:xz}),tG={kernelName:ei,backendName:"webgl",kernelFunc:Clt};var vlt="return x * x;",Slt=It({opSnippet:vlt}),eG={kernelName:fu,backendName:"webgl",kernelFunc:Slt};var rG="return (a - b) * (a - b);",Nlt=ue({opSnippet:rG,packedOpSnippet:rG}),nG={kernelName:oi,backendName:"webgl",kernelFunc:Nlt};function klt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;if(o.dtype!=="string")throw new Error("Input must be of datatype string");let s=e.readSync(o.dataId),i=S.fromUint8ToStringArray(s),a=yz(i,"string",n);return e.makeTensorInfo(o.shape,"string",a)}var oG={kernelName:cc,backendName:"webgl",kernelFunc:klt};function Tlt({inputs:r,attrs:t,backend:e}){let{x:n}=r,o=yr+`
| return x > 0.0 ? 1.0 : float(${t.alpha});
| `,s=new Br(n.shape,o);return e.runWebGLProgram(s,[n],n.dtype)}var sG={kernelName:wo,backendName:"webgl",kernelFunc:Tlt};var yC=class{constructor(t,e,n){this.variableNames=["x"],this.outputShape=n;let o=n.length,s=zt(n.length),i=zt(n.length),a="";if(o===1)a="coords * strides + begin";else{let u=0;a=n.map((l,c)=>(u++,n.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${u-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
| ${s} begin = ${s}(${t});
| ${s} strides = ${s}(${e});
|
| void main() {
| ${i} coords = getOutputCoords();
| setOutput(getX(${a}));
| }
| `}};function _lt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,end:i,strides:a,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n,{finalShapeSparse:f,finalShape:d,isIdentity:h,sliceDim0:g,isSimpleSlice:x,begin:b,end:w,strides:I}=ze.sliceInfo(o.shape,s,i,a,u,l,c,p,m),N;if(h)N=rt({inputs:{x:o},backend:e,attrs:{shape:d}});else if(g||x){y.assert(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);let A=ze.computeOutShape(b,w,I),D=_i({inputs:{x:o},backend:e,attrs:{begin:b,size:A}});N=rt({inputs:{x:D},backend:e,attrs:{shape:d}}),e.disposeIntermediateTensorInfo(D)}else if(e.shouldExecuteOnCPU([o])){let D=e.readSync(o.dataId),F=wt(o.shape,o.dtype,D),P=bz(f,F,I,b);N=e.makeTensorInfo(d,o.dtype,P.values)}else{let D=new yC(b,I,f);N=e.runWebGLProgram(D,[o],o.dtype)}let E=rt({inputs:{x:N},backend:e,attrs:{shape:d}});return e.disposeIntermediateTensorInfo(N),E}var iG={kernelName:ml,backendName:"webgl",kernelFunc:_lt};function Elt(r){let{inputs:t,backend:e,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:i,rightPad:a,padWidth:u,preserveShortSequences:l}=n,{data:c,dataSplits:p}=t,m=e.readSync(c.dataId),f=e.readSync(p.dataId),[d,h]=wz(m,f,o,s,i,a,u,l);return[e.makeTensorInfo([d.length],"string",d),e.makeTensorInfo(p.shape,"int32",h)]}var aG={kernelName:du,backendName:"webgl",kernelFunc:Elt};function Alt(r){let{inputs:t,backend:e,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let a=e.readSync(s.dataId),u=e.readSync(i.dataId)[0],[l,c,p]=Iz(a,u,o),m=c.length;return[e.makeTensorInfo([m,2],"int32",l),e.makeTensorInfo([m],"string",c),e.makeTensorInfo([2],"int32",new Int32Array(p))]}var lG={kernelName:hu,backendName:"webgl",kernelFunc:Alt};function Dlt(r){let{inputs:t,backend:e,attrs:n}=r,{numBuckets:o}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");let i=e.readSync(s.dataId),a=Cz(i,o);return e.makeTensorInfo(s.shape,"int32",a)}var uG={kernelName:gu,backendName:"webgl",kernelFunc:Dlt};var $lt="return tan(x);",Rlt=It({opSnippet:$lt}),cG={kernelName:ii,backendName:"webgl",kernelFunc:Rlt};var Flt=`
| float e2x = exp(-2.0 * abs(x));
| return sign(x) * (1.0 - e2x) / (1.0 + e2x);
| `,Olt=It({opSnippet:Flt}),pG={kernelName:ai,backendName:"webgl",kernelFunc:Olt};function Plt(r){let{inputs:t,backend:e,attrs:n}=r,{tensor:o,indices:s,updates:i}=t,{}=n,{sliceRank:a,numUpdates:u,sliceSize:l,strides:c,outputSize:p}=S.calculateShapes(i,s,o.shape),m=[p/l,l];if(p===0)return e.makeTensorInfo(o.shape,s.dtype);let f=rt({inputs:{x:s},backend:e,attrs:{shape:[u,a]}}),d=rt({inputs:{x:i},backend:e,attrs:{shape:[u,l]}}),h=rt({inputs:{x:o},backend:e,attrs:{shape:m}}),g=new rc(u,a,f.shape.length,d.shape.length,c,m,!1,!0),x=e.runWebGLProgram(g,[d,f,h],h.dtype),b=rt({inputs:{x},backend:e,attrs:{shape:o.shape}});return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(x),b}var mG={kernelName:ll,backendName:"webgl",kernelFunc:Plt};var bC=class{constructor(t,e){this.variableNames=["A"];let n=new Array(t.length);for(let i=0;i<n.length;i++)n[i]=t[i]*e[i];this.outputShape=n,this.rank=n.length;let o=zt(this.rank),s=Mlt(t);this.userCode=`
| void main() {
| ${o} resRC = getOutputCoords();
| setOutput(getA(${s}));
| }
| `}};function Mlt(r){let t=r.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${r[0]})`;let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let o=0;o<r.length;o++)n.push(`imod(${e[o]}, ${r[o]})`);return n.join()}function G1(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reps:s}=n;if(o.dtype==="string"||o.shape.length>5){let u=e.readSync(o.dataId),l=o.dtype==="string"?u.map(m=>y.decodeString(m)):u,c=wt(o.shape,o.dtype,l),p=Sz(c,s);return e.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new bC(o.shape,s);return e.runWebGLProgram(i,[o],o.dtype)}var fG={kernelName:lo,backendName:"webgl",kernelFunc:G1};var wC=class{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=t,this.userCode=`
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int elemIdx = coords[1];
|
| // We compare elements pair-wise within a group of size 2 * inc.
| // The comparing rule for each group alternates between ascending
| // and descending. Within each group, we compare each pair at
| // positions i and i+inc. To decide whether an element at position i
| // is x0 or x1, we mod it by 2 * inc, if the result is smaller than
| // inc, it is in the first half of the group, we denote it as x0,
| // otherwise we denote it as x1.
| // For example, as shown in the Bitonic top K paper referenced above,
| // Figure5(a) shows that element[1] is in the
| // second half of the group when group size is 2, but it is in the
| // first half of the group when group size is 4.
|
| bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
| int i = isFirstInPair ? elemIdx : elemIdx - inc;
|
| int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
| int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
| float x0 = i0 < n ? getX(batch, i0) : negativeInf;
| float x1 = i1 < n ? getX(batch, i1) : negativeInf;
|
| // Denotes which direction indices are in (ascending or descending).
| bool reverse = imod(elemIdx, 2 * dir) >= dir;
| bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
| if (reverse == isGreater) { // Elements in opposite order of direction
| int iTemp = i0;
| i0 = i1;
| i1 = iTemp;
| }
| if (isFirstInPair) {
| setOutput(float(i0));
| } else {
| setOutput(float(i1));
| }
| }
| `}},IC=class{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=t,this.userCode=`
| void main() {
| // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int elemIdx = coords[1];
|
| // The output size is half of the previous size.
| // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
| // we only need to output the indices at positions |, the indices at
| // positions _ can be thrown away, see Figure5(b) After Phase 2
| // (Merge phase) in the Bitonic Top K paper referenced above.
| // For example, the paper shows we only need to output the orange bars.
| // The output sequence should look like this | | | | | | | |.
| // Because the sequence is halved, to map the output index back
| // to the previous sequence to find the corresponding value,
| // we need to double the index. When we double the index,
| // we basically interpolate a position, so 2i looks like
| // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
| // of each 2k positions by - elemIdx % k. E.g. for output at
| // index 4,5,6,7, we want to get the corresponding element at
| // original index 8,9,10,11, for output at index 8,9,10,11,
| // we want to get the corresponding element at original index
| // 16,17,18,19, so on and so forth.
|
| int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
| int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
| int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
|
| float x0 = getX(batch, i0);
| float x1 = i1 < n ? getX(batch, i1) : x0;
|
| setOutput(x0 >= x1 ? float(i0) : float(i1));
| }
| `}};function kp(r,t){t!==null&&r.disposeIntermediateTensorInfo(t)}function dG(r){let t=1;for(;t<r;)t*=2;return t}function Llt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{k:s,sorted:i}=n,a=L().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),u=L().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=o.shape,c=l[l.length-1];if(e.shouldExecuteOnCPU([o])||c<a||s>u){let P=e.readSync(o.dataId),[V,G]=Nz(P,l,o.dtype,s,i);return[e.makeTensorInfo(V.shape,V.dtype,V.values),e.makeTensorInfo(G.shape,G.dtype,G.values)]}if(s===0)return l[l.length-1]=0,[e.makeTensorInfo(l,o.dtype,[]),e.makeTensorInfo(l,"int32",[])];if(c===1)return[o,Hl({attrs:{shape:l,dtype:"int32",value:0},backend:e})];let p=e.texData.get(o.dataId),m=p!==null&&p.isPacked,f=m?e.unpackTensor(o):o,h=y.sizeFromShape(l)/c,g=rt({inputs:{x:f},attrs:{shape:[h,c]},backend:e});m&&kp(e,f);let x=dG(s),b=dG(c),w=null,I=()=>w===null?[g,g]:[g,w],N=(P,V,G)=>{let W=I(),q=new wC(G),K=[[c],[w===null?1:0],[Number.NEGATIVE_INFINITY],[P],[V]],X=w;w=e.runWebGLProgram(q,W,"int32",K),kp(e,X)};for(let P=1;P<x;P*=2){let V=P*2;for(let G=P;G>=1;G/=2)N(V,G,[h,b])}for(let P=b;P>x;P/=2){let V=I(),G=new IC([h,P/2]),q=[[c],[w===null?1:0],[x]],H=w;w=e.runWebGLProgram(G,V,"int32",q),kp(e,H);let K=x/2,X=K*2;for(let Z=K;Z>=1;Z/=2)N(X,Z,w.shape)}let E=w;w=_i({inputs:{x:w},backend:e,attrs:{begin:0,size:[h,s]}}),kp(e,E);let A=O1({inputs:{x:g,indices:w},backend:e,attrs:{axis:1,batchDims:1}});kp(e,g);let D=l.slice(0,-1);D.push(s),E=w,w=rt({inputs:{x:w},attrs:{shape:D},backend:e}),kp(e,E);let F=A;return A=rt({inputs:{x:A},attrs:{shape:D},backend:e}),kp(e,F),[A,w]}var hG={kernelName:fl,backendName:"webgl",kernelFunc:Llt};var CC=class{constructor(t,e,n,o,s,i){this.variableNames=["Image","Transforms"],this.outputShape=i;let a=n==="nearest"?1:2,u;switch(o){case"constant":u=1;break;case"reflect":u=2;break;case"wrap":u=3;break;case"nearest":u=4;break;default:u=1;break}this.userCode=`
| float mapCoord(float outCoord, float len) {
| float inCoord = outCoord;
| if(${u} == 2) {
| if (inCoord < 0.0) {
| if (len <= 1.0) {
| inCoord = 0.0;
| } else {
| float sz2 = 2.0 * len;
| if (inCoord < sz2) {
| inCoord = sz2 * float(int(float(-inCoord / sz2))) +
| inCoord;
| }
| inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
| }
| } else if (inCoord > len - 1.0) {
| if (len <= 1.0) {
| inCoord = 0.0;
| } else {
| float sz2 = 2.0 * len;
| inCoord -= sz2 * float(int(float(inCoord / sz2)));
| if (inCoord >= len) {
| inCoord = sz2 - inCoord - 1.0;
| }
| }
| }
| return clamp(inCoord, 0.0, len - 1.0);
| } else if (${u} == 3) {
| if (inCoord < 0.0) {
| if (len <= 1.0) {
| inCoord = 0.0;
| } else {
| float sz = len - 1.0;
| inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
| }
| } else if (inCoord > len - 1.0) {
| if (len <= 1.0) {
| inCoord = 0.0;
| } else {
| float sz = len - 1.0;
| inCoord -= len * float(int(float(inCoord / sz)));
| }
| }
| return clamp(inCoord, 0.0, len - 1.0);
| } else if (${u} == 4) {
| return clamp(outCoord, 0.0, len - 1.0);
| } else {
| return outCoord;
| }
| }
|
| float readWithFillValue(int batch, int coordY, int coordX,
| int channel) {
| float outputValue;
| if (0 <= coordY && coordY < ${t} && 0 <= coordX && coordX < ${e}) {
| outputValue = getImage(batch, coordY, coordX, channel);
| } else {
| outputValue = float(${s});
| }
| return outputValue;
| }
|
| void main() {
| ivec4 coords = getOutputCoords();
| float outputValue;
| int batch = coords[0];
| int x = coords[2];
| int y = coords[1];
| int channel = coords[3];
| float xf = float(x);
| float yf = float(y);
| float a1 = getTransforms(batch, 0);
| float a2 = getTransforms(batch, 1);
| float a3 = getTransforms(batch, 2);
| float b1 = getTransforms(batch, 3);
| float b2 = getTransforms(batch, 4);
| float b3 = getTransforms(batch, 5);
| float c1 = getTransforms(batch, 6);
| float c2 = getTransforms(batch, 7);
| float projection = c1 * xf + c2 * yf + 1.0;
| if (projection == 0.0) {
| outputValue = float(${s});
| } else {
| float inX = (a1 * xf + a2 * yf + a3) / projection;
| float inY = (b1 * xf + b2 * yf + b3) / projection;
| float mapX = mapCoord(inX, float(${e}));
| float mapY = mapCoord(inY, float(${t}));
|
| if (${a} == 1) {
| int coordY = int(round(mapY));
| int coordX = int(round(mapX));
| outputValue = readWithFillValue(batch, coordY, coordX,
| channel);
| } else {
| float yFloor = floor(mapY);
| float xFloor = floor(mapX);
| float yCeil = yFloor + 1.0;
| float xCeil = xFloor + 1.0;
| float valueYFloor = (xCeil - mapX) *
| readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
| (mapX - xFloor) *
| readWithFillValue(batch, int(yFloor), int(xCeil), channel);
| float valueYCeil = (xCeil - mapX) *
| readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
| (mapX - xFloor) *
| readWithFillValue(batch, int(yCeil), int(xCeil), channel);
| outputValue = (yCeil - mapY) * valueYFloor +
| (mapY - yFloor) * valueYCeil;
| }
| }
| setOutput(outputValue);
| }
| `}};function zlt(r){let{inputs:t,backend:e,attrs:n}=r,{image:o,transforms:s}=t,{interpolation:i,fillMode:a,fillValue:u,outputShape:l}=n,[c,p,m,f]=o.shape,[d,h]=l!=null?l:[p,m],g=[c,d,h,f],x=new CC(p,m,i,a,u,g);return e.runWebGLProgram(x,[o,s],"float32")}var gG={kernelName:dl,backendName:"webgl",kernelFunc:zlt};function Blt(r){let{inputs:t,attrs:e,backend:n}=r,{axis:o}=e,{x:s}=t;Ni(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:a,outputShape:u,indices:l}=kz(i,o,s.shape,s.dtype);return[n.makeTensorInfo(u,s.dtype,a),n.makeTensorInfo([l.length],"int32",l)]}var xG={kernelName:xu,backendName:"webgl",kernelFunc:Blt};function Vlt(r){let{inputs:t,backend:e,attrs:n}=r,{value:o}=t,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o,a=i.shape.length,u=o.shape[s],l=new Array(a-1),c=0;for(let h=0;h<a;h++)h!==s&&(l[c++]=i.shape[h]);let p=[],m=new Array(a).fill(0),f=i.shape.slice();f[s]=1;let d=new Array(u);for(let h=0;h<d.length;h++){m[s]=h;let g=_i({inputs:{x:i},backend:e,attrs:{begin:m,size:f}}),x=rt({inputs:{x:g},backend:e,attrs:{shape:l}});d[h]=x,p.push(g)}return p.forEach(h=>e.disposeIntermediateTensorInfo(h)),d}var yG={kernelName:Xi,backendName:"webgl",kernelFunc:Vlt};var vC=class{constructor(t,e){this.variableNames=["x","segmentIds"];let n=t.windowSize,o=t.batchSize,s=t.inSize,i=t.numSegments,a=i*Math.ceil(s/n);this.outputShape=[o,a];let u="0.0",l="sumValue",c=Math.floor(n/4)*4,p=n%4,m=`
| sumValue += dot(values, segFilter);
| `,f="";s%n>0&&(f=`
| if (inIdx < 0 || inIdx >= ${s}) {
| return initializationValue;
| }
| `);let d="";s%n>0&&(d=`
| if (inIdx < 0 || inIdx >= ${s}) {
| return -1.0;
| }
| `),this.userCode=`
| const float initializationValue = ${u};
|
| float getValue(int batch, int inIdx) {
| ${f}
| return getX(batch, inIdx);
| }
|
| float getSegmentIdAtIndex(int inIdx) {
| ${d}
| return getSegmentIds(inIdx);
| }
|
| void main() {
| ivec2 coords = getOutputCoords();
| int batch = coords[0];
| int outIdx = coords[1];
| int inOffset = int(floor(float(outIdx) / float(
| ${i})) * float(${n}));
| int currentSeg = int(mod(float(outIdx), float(${i})));
|
| float sumValue = 0.0;
|
| for (int i = 0; i < ${c}; i += 4) {
| int inIdx = inOffset + i;
| vec4 values = vec4(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| getValue(batch, inIdx + 2),
| getValue(batch, inIdx + 3)
| );
|
| vec4 segFilter = vec4(
| int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
| int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
| int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
| int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
| );
|
| ${m}
| }
|
| int inIdx = inOffset + ${c};
| if (${p===1}) {
| vec4 values = vec4(
| getValue(batch, inIdx),
| initializationValue,
| initializationValue,
| initializationValue
| );
|
| int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
| vec4 segFilter = vec4(
| int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
| 0,
| 0,
| 0
| );
|
| ${m}
| } else if (${p===2}) {
| vec4 values = vec4(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| initializationValue,
| initializationValue
| );
|
| vec4 segFilter = vec4(
| int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
| int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
| 0,
| 0
| );
|
| ${m}
| } else if (${p===3}) {
| vec4 values = vec4(
| getValue(batch, inIdx),
| getValue(batch, inIdx + 1),
| getValue(batch, inIdx + 2),
| initializationValue
| );
|
| vec4 segFilter = vec4(
| int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
| int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
| int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
| 0
| );
|
| ${m}
| }
| setOutput(${l});
| }
| `}};function Glt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,segmentIds:s}=t,{numSegments:i}=n,a=o.shape.length,u=[],l=0,c=S.getAxesPermutation([l],a),p=o;c!=null&&(p=Pe({inputs:{x:o},backend:e,attrs:{perm:c}}),u.push(p),l=S.getInnerMostAxes(1,a)[0]);let m=S.segment_util.computeOutShape(p.shape,l,i),f=y.sizeFromShape([p.shape[l]]),d=rt({inputs:{x:p},backend:e,attrs:{shape:[-1,f]}});u.push(d);let h=xc(o.dtype),g=(I,N,E,A,D)=>{let F=I.shape[0],P=I.shape[1],V=S.segment_util.segOpComputeOptimalWindowSize(P,D),G={windowSize:V,inSize:P,batchSize:F,numSegments:D},W=new vC(G,N),q=e.compileAndRun(W,[I,E],A);if(u.push(q),q.shape[1]===D)return q;let H=V1({backend:e,attrs:{start:0,stop:D,step:1,dtype:"float32"}}),K=G1({inputs:{x:H},backend:e,attrs:{reps:[P/V]}});return u.push(H),u.push(K),g(q,N,K,A,D)},x=g(d,"unsortedSegmentSum",s,h,i),b=rt({inputs:{x},backend:e,attrs:{shape:m}}),w=b;if(c!=null){u.push(b);let I=S.getUndoAxesPermutation(c);w=Pe({inputs:{x:w},backend:e,attrs:{perm:I}})}return u.forEach(I=>e.disposeIntermediateTensorInfo(I)),w}var bG={kernelName:yu,backendName:"webgl",kernelFunc:Glt};var Wlt=[e3,n3,o3,s3,a3,l3,u3,c3,f3,d3,h3,g3,x3,y3,b3,w3,I3,C3,v3,S3,N3,T3,_3,E3,A3,F3,P3,M3,Hz,z3,V3,G3,W3,U3,H3,q3,K3,j3,X3,Y3,Q3,tB,eB,rB,nB,oB,sB,iB,aB,lB,uB,cB,pB,mB,fB,dB,gB,xB,yB,bB,IB,CB,vB,SB,NB,kB,TB,_B,EB,Uz,AB,B3,DB,$B,RB,qz,FB,OB,PB,MB,LB,zB,BB,VB,GB,WB,HB,qB,KB,jB,XB,YB,JB,tV,eV,rV,nV,oV,uV,Xz,cV,pV,mV,fV,D3,dV,xV,yV,bV,wV,Kz,IV,CV,vV,SV,NV,$3,sV,kV,TV,_V,Zz,EV,AV,DV,$V,RV,FV,OV,PV,MV,LV,zV,BV,VV,GV,WV,UV,k3,lV,HV,qV,KV,jV,XV,YV,ZV,JV,tG,eG,nG,oG,sG,iG,aG,lG,uG,aV,Qz,cG,pG,mG,fG,hG,gG,t3,xG,yG,bG,hV];for(let r of Wlt)pc(r);var Nt;(function(r){r[r.float32=0]="float32",r[r.int32=1]="int32",r[r.bool=2]="bool",r[r.string=3]="string",r[r.complex64=4]="complex64"})(Nt||(Nt={}));var nc;(function(r){r[r.linear=0]="linear",r[r.relu=1]="relu",r[r.relu6=2]="relu6",r[r.prelu=3]="prelu",r[r.leakyrelu=4]="leakyrelu",r[r.sigmoid=5]="sigmoid",r[r.elu=6]="elu"})(nc||(nc={}));var wG;function Ult(r){wG=r.wasm.cwrap(Zi,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Hlt(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=t;if(o.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=n,m=e.dataIdMap.get(o.dataId).id,f=e.dataIdMap.get(s.dataId).id,d=0;if(i!=null){let D=e.dataIdMap.get(i.dataId);if(D.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${D.shape.length}.`);d=D.id}let h=a==null?0:e.dataIdMap.get(a.dataId).id,g=nc[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let x=u?o.shape[2]:o.shape[1],b=l?s.shape[1]:s.shape[2],w=Hr.assertAndGetBroadcastShape(o.shape.slice(0,-2),s.shape.slice(0,-2)),I=e.makeOutput([...w,x,b],o.dtype),N=e.dataIdMap.get(I.dataId).id,E=new Uint8Array(new Int32Array(o.shape).buffer),A=new Uint8Array(new Int32Array(s.shape).buffer);return wG(m,E,o.shape.length,f,A,s.shape.length,u,l,g,d,h,p||0,N),I}var IG={kernelName:Zi,backendName:"wasm",setupFunc:Ult,kernelFunc:Hlt};function yt(r,t){let e;function n(s){e=s.wasm.cwrap(r,null,["number","number","number"])}function o(s){let{backend:i,inputs:{x:a}}=s,u=i.dataIdMap.get(a.dataId).id,l=i.makeOutput(a.shape,t||a.dtype),c=i.dataIdMap.get(l.dataId).id;return y.sizeFromShape(l.shape)===0||e(u,Nt[a.dtype],c),l}return{kernelName:r,backendName:"wasm",setupFunc:n,kernelFunc:o}}var CG=yt($i);var vG=yt(qo);var SG=yt(Ko);function ee(r,t,e){let n;function o(i){n=i.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:a,inputs:u}=i,{a:l,b:c}=u,p=a.dataIdMap.get(l.dataId).id,m=a.dataIdMap.get(c.dataId).id,f=e!=null?e:l.dtype,d=S.assertAndGetBroadcastShape(l.shape,c.shape),h=a.makeOutput(d,f);if(y.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(l.shape).buffer),x=new Uint8Array(new Int32Array(c.shape).buffer),b=a.dataIdMap.get(h.dataId).id;return(()=>n(p,g,l.shape.length,m,x,c.shape.length,Nt[l.dtype],b))(),h}return{kernelName:r,backendName:"wasm",setupFunc:o,kernelFunc:s}}var qlt=!0,NG=ee(ao,qlt);var kG;function Klt(r){kG=r.wasm.cwrap(jo,null,["array","number","number","number"])}function jlt(r){let{inputs:t,backend:e}=r,n=e.makeOutput(t[0].shape,t[0].dtype);if(y.sizeFromShape(n.shape)===0)return n;let o=t.map(a=>e.dataIdMap.get(a.dataId).id),s=new Uint8Array(new Int32Array(o).buffer),i=e.dataIdMap.get(n.dataId).id;return kG(s,o.length,Nt[n.dtype],i),n}var TG={kernelName:jo,backendName:"wasm",setupFunc:Klt,kernelFunc:jlt};function Tp(r){let{inputs:{x:t},backend:e}=r;if(t.dtype==="string")return sr(e.readSync(t.dataId),t.shape,t.dtype);let n=e.makeOutput(t.shape,t.dtype),o=e.typedArrayFromHeap(t);return e.typedArrayFromHeap(n).set(o),n}var _G={kernelName:bo,backendName:"wasm",kernelFunc:Tp};var EG;function Xlt(r){EG=r.wasm.cwrap(uo,null,["number","array","number","number","number","array","number"])}function go(r){let{inputs:t,backend:e,attrs:n}=r,[o,s]=Zlt(t.x.shape,n.perm),i=!0;for(let d=0;d<s.length;d++)s[d]!==d&&(i=!1);let a=Ylt(t.x.shape,n.perm),u={dataId:t.x.dataId,shape:o,dtype:t.x.dtype};if(i){let d=Tp({inputs:t,backend:e});return d.shape=a,d}let l=e.makeOutput(a,u.dtype),c=e.dataIdMap.get(u.dataId).id,p=e.dataIdMap.get(l.dataId).id,m=new Uint8Array(new Int32Array(s).buffer),f=new Uint8Array(new Int32Array(u.shape).buffer);return EG(c,f,u.shape.length,Nt[u.dtype],p,m,s.length),l}function Ylt(r,t){let e=new Array(r.length);for(let n=0;n<e.length;n++)e[n]=r[t[n]];return e}function Zlt(r,t){let e=[],n=[];for(let o=0;o<r.length;++o)r[o]!==1&&e.push(r[o]),r[t[o]]!==1&&n.push(t[o]);for(let o=0;o<n.length;++o){let s=-1;for(let i=0;i<n.length;++i)n[i]>=o&&(s===-1||n[s]>n[i])&&(s=i);n[s]=o}return[e,n]}var AG={kernelName:uo,backendName:"wasm",kernelFunc:go,setupFunc:Xlt};function Sn(r,t,e){let n=r.shape,o=r.shape.length,s=y.parseAxisParam(t,n),i=s,a=S.getAxesPermutation(i,o),u=null,l=!1;if(a!=null){let c=new Array(o);for(let f=0;f<c.length;f++)c[f]=n[a[f]];i=S.getInnerMostAxes(i.length,o),u=go({inputs:{x:r},attrs:{perm:a},backend:e});let p=e.dataIdMap.get(r.dataId).id;e.dataIdMap.get(u.dataId).id!==p&&(l=!0)}return{transposed:u,originalAxes:s,axes:i,inputWasTransposed:l}}var DG;function Jlt(r){DG=r.wasm.cwrap(Ra,null,["number, number, number"])}function Qlt(r){let{backend:t,inputs:e,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=e,u=t.dataIdMap.get(i.dataId).id,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t);if(f){let w=t.dataIdMap.get(c.dataId).id;l=c,u=w}let d=l.shape.length;S.assertAxesAreInnerMostDims("all",p,d);let[h,g]=S.computeOutAndReduceShapes(l.shape,p),x=y.sizeFromShape(g),b=t.makeOutput(h,i.dtype);if(y.sizeFromShape(l.shape)!==0){let w=t.dataIdMap.get(b.dataId).id;DG(u,x,w)}if(f&&t.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var $G={kernelName:Ra,backendName:"wasm",setupFunc:Jlt,kernelFunc:Qlt};var RG;function tut(r){RG=r.wasm.cwrap(Fa,null,["number, number, number"])}function eut(r){let{backend:t,inputs:e,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=e,u=t.dataIdMap.get(i.dataId).id,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t);if(f){let w=t.dataIdMap.get(c.dataId).id;l=c,u=w}let d=l.shape.length;S.assertAxesAreInnerMostDims("any",p,d);let[h,g]=S.computeOutAndReduceShapes(l.shape,p),x=y.sizeFromShape(g),b=t.makeOutput(h,i.dtype);if(y.sizeFromShape(l.shape)!==0){let w=t.dataIdMap.get(b.dataId).id;RG(u,x,w)}if(f&&t.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var FG={kernelName:Fa,backendName:"wasm",setupFunc:tut,kernelFunc:eut};function SC(r){let t;function e(o){t=o.wasm.cwrap(r,null,["number","number","number","number","number"])}function n(o){let{backend:s,inputs:i,attrs:a}=o,{axis:u}=a,{x:l}=i,c=s.dataIdMap.get(l.dataId).id,p=c,m=l,{transposed:f,axes:d,inputWasTransposed:h}=Sn(l,u,s);if(h){let N=s.dataIdMap.get(f.dataId).id;N!==c&&(m=f,p=N)}let g=m.shape.slice(0,-1),x=s.makeOutput(g,"int32"),b=s.dataIdMap.get(x.dataId).id,w=y.sizeFromShape(x.shape),I=m.shape[d[0]];return t(p,Nt[m.dtype],w,I,b),h&&s.disposeData(f.dataId),x}return{kernelName:r,backendName:"wasm",setupFunc:e,kernelFunc:n}}var OG=SC(Ri);var PG=SC(Fi);var MG=yt(Xo);var LG=yt(Yo);var zG=yt(Zo);var BG=ee(Qo,!1);var VG=yt(Jo);var GG;function rut(r){GG=r.wasm.cwrap(ts,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function nut(r){let{inputs:t,attrs:e,backend:n}=r,o=t.x,s=n.dataIdMap.get(o.dataId).id,{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=e,c=S.computePool2DInfo(o.shape,i,a,1,u,l),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,x=c.strideHeight,b=c.strideWidth,w=c.inChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);if(c.dilationWidth!==1||c.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);let I=n.makeOutput(c.outShape,"float32"),N=n.dataIdMap.get(I.dataId).id;return GG(s,o.shape[0],o.shape[1],o.shape[2],p,m,f,d,h,g,x,b,w,N),I}var WG={kernelName:ts,backendName:"wasm",setupFunc:rut,kernelFunc:nut};var UG;function out(r){UG=r.wasm.cwrap("AvgPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function sut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u,dataFormat:l}=n,c=S.computePool3DInfo(o.shape,s,i,1,a,u,l),p=e.makeOutput(c.outShape,o.dtype);return UG(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),p}var HG={kernelName:Oi,backendName:"wasm",setupFunc:out,kernelFunc:sut};var qG;function iut(r){qG=r.wasm.cwrap("AvgPool3DGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function aut(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=n,c=S.computePool3DInfo(s.shape,i,a,1,u,l),p=e.makeOutput(s.shape,s.dtype);return qG(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left,c.filterDepth,c.filterHeight,c.filterWidth),p}var KG={kernelName:Jl,backendName:"wasm",setupFunc:iut,kernelFunc:aut};var jG;function lut(r){jG=r.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function uut(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,{filterSize:i,strides:a,pad:u}=n,l=S.computePool2DInfo(s.shape,i,a,1,u),c=e.makeOutput(s.shape,s.dtype);return jG(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(c.dataId).id,l.batchSize,l.inChannels,l.inHeight,l.inWidth,l.outHeight,l.outWidth,l.strideHeight,l.strideWidth,l.dilationHeight,l.dilationWidth,l.effectiveFilterHeight,l.effectiveFilterWidth,l.padInfo.top,l.padInfo.left,l.filterHeight,l.filterWidth),c}var XG={kernelName:Zl,backendName:"wasm",setupFunc:lut,kernelFunc:uut};function mr(r){let{inputs:t,attrs:e}=r,{x:n}=t,{shape:o}=e,s=y.sizeFromShape(n.shape),i=y.inferFromImplicitShape(o,s);return y.assert(s===y.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`),r.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var YG={kernelName:Ui,backendName:"wasm",kernelFunc:mr};var ZG;function cut(r){ZG=r.wasm.cwrap(es,null,["number","array","number","number","array","number","number","number","number"])}function put(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s}=t,{transposeA:i,transposeB:a}=n;if(o.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let u=o.shape.length,l=s.shape.length,c=i?o.shape[u-2]:o.shape[u-1],p=a?s.shape[l-1]:s.shape[l-2],m=i?o.shape[u-1]:o.shape[u-2],f=a?s.shape[l-2]:s.shape[l-1],d=o.shape.slice(0,-2),h=s.shape.slice(0,-2),g=y.sizeFromShape(d),x=y.sizeFromShape(h),w=Hr.assertAndGetBroadcastShape(o.shape.slice(0,-2),s.shape.slice(0,-2)).concat([m,f]);y.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${i} and transposeB=${a} must match.`);let I=i?[g,c,m]:[g,m,c],N=a?[x,f,p]:[x,p,f],E=mr({inputs:{x:o},backend:e,attrs:{shape:I}}),A=mr({inputs:{x:s},backend:e,attrs:{shape:N}}),D=e.dataIdMap.get(E.dataId).id,F=e.dataIdMap.get(A.dataId).id,P=i?E.shape[2]:E.shape[1],V=a?A.shape[1]:A.shape[2],G=Math.max(g,x),W=e.makeOutput([G,P,V],E.dtype),q=e.dataIdMap.get(W.dataId).id,H=new Uint8Array(new Int32Array(E.shape).buffer),K=new Uint8Array(new Int32Array(A.shape).buffer);return ZG(D,H,E.shape.length,F,K,A.shape.length,i,a,q),e.disposeData(E.dataId),e.disposeData(A.dataId),W.shape=w,W}var JG={kernelName:es,backendName:"wasm",setupFunc:cut,kernelFunc:put};function Go(r){let{inputs:{x:t},attrs:{begin:e,size:n},backend:o}=r,[s,i]=ze.parseSliceParams(t,e,n),a=ze.isSliceContinous(t.shape,s,i),u=o.readSync(t.dataId),l=o.makeOutput(i,t.dtype),c=y.computeStrides(t.shape),p=o.dataIdMap.get(l.dataId);if(a){let d=ze.computeFlatOffset(s,c);return t.dtype==="string"?p.stringBytes=u.slice(d,d+y.sizeFromShape(i)):o.typedArrayFromHeap(l).set(u.subarray(d,d+y.sizeFromShape(i))),l}if(t.dtype==="string"){let d=cp(u,s,i,t.shape,t.dtype);return p.stringBytes=d,l}let m=o.typedArrayFromHeap(l),f=t.shape.length;if(f===2)mut(u,c[0],m,s,i);else if(f===3)fut(u,c[0],c[1],m,s,i);else if(f===4)dut(u,c[0],c[1],c[2],m,s,i);else{let d=cp(u,s,i,t.shape,t.dtype);m.set(d)}return l}function mut(r,t,e,n,o){let s=0,i=n[0],a=n[1],u=i+o[0];for(let l=i;l<u;l++){let c=l*t+a;e.set(r.subarray(c,c+o[1]),s),s+=o[1]}}function fut(r,t,e,n,o,s){let i=0,a=o[0],u=o[1],l=o[2],c=a+s[0],p=u+s[1];for(let m=a;m<c;m++)for(let f=u;f<p;f++){let d=m*t+f*e+l;n.set(r.subarray(d,d+s[2]),i),i+=s[2]}}function dut(r,t,e,n,o,s,i){let a=0,u=s[0],l=s[1],c=s[2],p=u+i[0],m=l+i[1],f=c+i[2],d=s[3];for(let h=u;h<p;h++)for(let g=l;g<m;g++)for(let x=c;x<f;x++){let b=h*t+g*e+x*n+d;o.set(r.subarray(b,b+i[3]),a),a+=i[3]}}var QG={kernelName:qi,backendName:"wasm",kernelFunc:Go};function hut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,crops:i}=n,a=s.reduce((x,b)=>x*b),u=S.getReshaped(o.shape,s,a),l=S.getPermuted(u.length,s.length),c=S.getReshapedPermuted(o.shape,s,a),p=S.getSliceBeginCoords(i,s.length),m=S.getSliceSize(c,i,s.length),f=mr({inputs:{x:o},backend:e,attrs:{shape:u}}),d=go({inputs:{x:f},backend:e,attrs:{perm:l}}),h=mr({inputs:{x:d},backend:e,attrs:{shape:c}}),g=Go({inputs:{x:h},backend:e,attrs:{begin:p,size:m}});return e.disposeData(f.dataId),e.disposeData(d.dataId),e.disposeData(f.dataId),g}var tW={kernelName:Pi,backendName:"wasm",kernelFunc:hut};var eW;function gut(r){eW=r.wasm.cwrap(Oa,null,["number","number","boolean","number","number","number"])}function xut(r){let{backend:t,inputs:e,attrs:n}=r,{x:o,weights:s}=e,{size:i}=n,a=s.shape.reduce((p,m)=>p*m,1)!==0,u=o.shape.length===1?[i]:[o.shape[0],i],l=t.makeOutput(u,s.dtype);function c(p){return t.dataIdMap.get(p.dataId).id}return eW(c(o),i,a,c(s),Nt[s.dtype],c(l)),l}var rW={kernelName:Oa,backendName:"wasm",setupFunc:gut,kernelFunc:xut};var yut=!0,nW=ee(Pa,yut);function but(r){let{inputs:t,backend:e}=r,{s0:n,s1:o}=t,s=e.typedArrayFromHeap(n),i=e.typedArrayFromHeap(o),a=S.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return e.makeOutput([a.length],"int32",void 0,new Int32Array(a))}var oW={kernelName:Ql,backendName:"wasm",kernelFunc:but};function Mn(r){let{inputs:{x:t},attrs:{dtype:e},backend:n}=r,o=n.makeOutput(t.shape,e),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(o).set(s),o}var sW={kernelName:xo,backendName:"wasm",kernelFunc:Mn};var iW=yt(rs);var aW;function wut(r){aW=r.wasm.cwrap(yo,null,["number","number","number","number"])}function Iut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{clipValueMin:s,clipValueMax:i}=n,a=e.dataIdMap.get(o.dataId).id,u=e.makeOutput(o.shape,o.dtype),l=e.dataIdMap.get(u.dataId).id;return aW(a,s,i,l),u}var lW={kernelName:yo,backendName:"wasm",setupFunc:wut,kernelFunc:Iut};function W1(r){let{inputs:t,backend:e}=r,n=y.parseAxisParam(r.attrs.axis,t[0].shape)[0],o=t.map(f=>f.shape);S.assertParamsConsistent(o,n);let s=S.computeOutShape(t.map(f=>f.shape),n),i=t.filter(f=>y.sizeFromShape(f.shape)>0);if(i.length===1)return Tp({inputs:{x:i[0]},backend:e});let a=e.makeOutput(s,t[0].dtype);if(y.sizeFromShape(s)===0)return a;if(i[0].dtype==="string"){let f=i.map(w=>{let N=[-1,y.sizeFromShape(w.shape.slice(n))];return mr({inputs:{x:w},backend:e,attrs:{shape:N}})}),d=f.map(w=>({vals:e.readSync(w.dataId),shape:w.shape}));s=S.computeOutShape(f.map(w=>w.shape),1);let h=f[0].shape[0]===1,g=ap(d,s,t[0].dtype,h),x=S.computeOutShape(i.map(w=>w.shape),n);a.shape=x;let b=e.dataIdMap.get(a.dataId);return b.stringBytes=S.fromStringArrayToUint8(g),f.forEach(w=>e.disposeData(w.dataId)),a}let u=y.sizeFromShape(i[0].shape.slice(0,n)),l=0,c=i.map(f=>{let d=y.sizeFromShape(f.shape.slice(n));return l+=d,d}),p=i.map(f=>e.typedArrayFromHeap(f)),m=e.typedArrayFromHeap(a);for(let f=0;f<u;f++){let d=f*l;for(let h=0;h<p.length;h++){let g=c[h],x=f*g,b=p[h].subarray(x,x+g);m.set(b,d),d+=g}}return a}var uW={kernelName:Mi,backendName:"wasm",kernelFunc:W1};var cW;function Cut(r){cW=r.wasm.cwrap(ns,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function vut(r){let{inputs:t,attrs:e,backend:n}=r,{x:o,filter:s}=t,i=n.dataIdMap.get(o.dataId).id,a=n.dataIdMap.get(s.dataId).id,{strides:u,dilations:l,pad:c,dimRoundingMode:p,dataFormat:m}=e,f=S.convertConv2DDataFormat(m),d=S.computeConv2DInfo(o.shape,s.shape,u,l,c,p,!1,f),h=d.filterHeight,g=d.filterWidth,x=d.padInfo.top,b=d.padInfo.right,w=d.padInfo.bottom,I=d.padInfo.left,N=d.dilationHeight,E=d.dilationWidth,A=d.strideHeight,D=d.strideWidth,F=d.inChannels,P=d.outChannels,V=d.padInfo.type==="SAME"?1:0;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let G=n.makeOutput(d.outShape,"float32"),W=n.dataIdMap.get(G.dataId).id;return cW(i,o.shape[0],o.shape[1],o.shape[2],a,h,g,x,b,w,I,V,N,E,A,D,F,P,W),G}var pW={kernelName:ns,backendName:"wasm",setupFunc:Cut,kernelFunc:vut};var mW;function Sut(r){mW=r.wasm.cwrap(os,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Nut(r){let{backend:t,inputs:e,attrs:n}=r,{dy:o,filter:s}=e,{strides:i,pad:a,dataFormat:u,dimRoundingMode:l,inputShape:c}=n,p=1,m=S.convertConv2DDataFormat(u),f=S.computeConv2DInfo(c,s.shape,i,p,a,l,!1,m),{batchSize:d,filterHeight:h,filterWidth:g,inChannels:x,inHeight:b,inWidth:w,outChannels:I,outHeight:N,outWidth:E,strideHeight:A,strideWidth:D}=f,F=h-1-f.padInfo.top,P=g-1-f.padInfo.left,V=f.dataFormat==="channelsLast",G=y.computeStrides(f.inShape),W=y.computeStrides(o.shape),[q,H,K]=y.computeStrides(s.shape),X=G[0],Z=V?G[1]:G[2],et=V?G[2]:1,nt=V?1:G[1],st=W[0],at=V?W[1]:W[2],ot=V?W[2]:1,it=V?1:W[1],mt=t.makeOutput(f.inShape,"float32"),gt=t.dataIdMap.get(mt.dataId).id,Ct=t.dataIdMap.get(o.dataId).id,Rt=t.dataIdMap.get(s.dataId).id;return mW(Ct,Rt,d,h,g,b,w,x,N,E,I,A,D,F,P,q,H,K,X,Z,et,nt,st,at,ot,it,gt),mt}var fW={kernelName:os,backendName:"wasm",setupFunc:Sut,kernelFunc:Nut};var dW;function kut(r){dW=r.wasm.cwrap(ss,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Tut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n;if(o.dtype!=="float32")throw new Error(`Tensor x must have dtype float32, got ${o.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let l=S.computeConv3DInfo(o.shape,s.shape,i,u,a),c=e.makeOutput(l.outShape,o.dtype);return dW(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(c.dataId).id,l.batchSize,l.inDepth,l.inHeight,l.inWidth,l.inChannels,l.outDepth,l.outHeight,l.outWidth,l.outChannels,l.strideDepth,l.strideHeight,l.strideWidth,l.dilationDepth,l.dilationHeight,l.dilationWidth,l.filterDepth,l.filterHeight,l.filterWidth,l.padInfo.front,l.padInfo.top,l.padInfo.left),c}var hW={kernelName:ss,backendName:"wasm",setupFunc:kut,kernelFunc:Tut};var gW;function _ut(r){gW=r.wasm.cwrap(Ma,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Eut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,filterShape:u}=n;if(o.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${o.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let l=S.computeConv3DInfo(o.shape,u,i,1,a),c=e.makeOutput(l.filterShape,s.dtype);return gW(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(c.dataId).id,l.batchSize,l.inDepth,l.inHeight,l.inWidth,l.inChannels,l.outDepth,l.outHeight,l.outWidth,l.outChannels,l.strideDepth,l.strideHeight,l.strideWidth,l.dilationDepth,l.dilationHeight,l.dilationWidth,l.filterDepth,l.filterHeight,l.filterWidth,l.padInfo.front,l.padInfo.top,l.padInfo.left),c}var xW={kernelName:Ma,backendName:"wasm",setupFunc:_ut,kernelFunc:Eut};var yW;function Aut(r){yW=r.wasm.cwrap(La,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Dut(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{pad:i,strides:a,inputShape:u}=n;if(o.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${o.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let l=S.computeConv3DInfo(u,s.shape,a,1,i),c=e.makeOutput(l.inShape,o.dtype);return yW(e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(c.dataId).id,l.batchSize,l.inDepth,l.inHeight,l.inWidth,l.inChannels,l.outDepth,l.outHeight,l.outWidth,l.outChannels,l.strideDepth,l.strideHeight,l.strideWidth,l.dilationDepth,l.dilationHeight,l.dilationWidth,l.filterDepth,l.filterHeight,l.filterWidth,l.padInfo.front,l.padInfo.top,l.padInfo.left),c}var bW={kernelName:La,backendName:"wasm",setupFunc:Aut,kernelFunc:Dut};var wW=yt(is);var IW=yt(as);var U1;(function(r){r[r.bilinear=0]="bilinear",r[r.nearest=1]="nearest"})(U1||(U1={}));var CW;function $ut(r){CW=r.wasm.cwrap(Ba,null,["number","number","number","number","array","number","number","number","number","number"])}function Rut(r){let{backend:t,inputs:e,attrs:n}=r,{method:o,extrapolationValue:s,cropSize:i}=n,{image:a,boxes:u,boxInd:l}=e,c=u.shape[0],[p,m]=i,f=[c,p,m,a.shape[3]],d=t.dataIdMap.get(a.dataId),h;a.dtype!=="float32"&&(h=Mn({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),d=t.dataIdMap.get(h.dataId));let g=d.id,x=t.dataIdMap.get(u.dataId).id,b=t.dataIdMap.get(l.dataId).id,w=t.makeOutput(f,"float32"),I=t.dataIdMap.get(w.dataId).id,N=new Uint8Array(new Int32Array(a.shape).buffer);return CW(g,x,b,c,N,p,m,U1[o],s,I),h!=null&&t.disposeData(h.dataId),w}var vW={kernelName:Ba,backendName:"wasm",setupFunc:$ut,kernelFunc:Rut};var SW;function Fut(r){SW=r.wasm.cwrap(za,null,["number","number","number","number","number","number"])}function Out(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n,u=o.shape.length;y.assert(o.dtype==="float32"||o.dtype==="int32",()=>`cumprod does not support ${o.dtype} tensors in the WASM backend`);let l=S.getAxesPermutation([s],u),c=o;l!==null&&(c=go({inputs:{x:o},attrs:{perm:l},backend:e}));let p=S.getInnerMostAxes(1,u)[0];S.assertAxesAreInnerMostDims("cumprod",[p],u);let m=e.makeOutput(c.shape,c.dtype),f=c.shape[p],d=e.dataIdMap.get(c.dataId).id,h=e.dataIdMap.get(m.dataId).id;SW(d,i?1:0,a?1:0,f,h,Nt[o.dtype]);let g=m;if(l!==null){let x=S.getUndoAxesPermutation(l);g=go({inputs:{x:m},attrs:{perm:x},backend:e}),e.disposeData(c.dataId),e.disposeData(m.dataId)}return g}var NW={kernelName:za,backendName:"wasm",setupFunc:Fut,kernelFunc:Out};var kW;function Put(r){kW=r.wasm.cwrap(ls,null,["number","number","number","number","number","number"])}function Mut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n,u=o.shape.length;y.assert(o.dtype==="float32"||o.dtype==="int32",()=>`cumsum does not support ${o.dtype} tensors in the WASM backend`);let l=S.getAxesPermutation([s],u),c=o;l!==null&&(c=go({inputs:{x:o},attrs:{perm:l},backend:e}));let p=S.getInnerMostAxes(1,u)[0];S.assertAxesAreInnerMostDims("cumsum",[p],u);let m=e.makeOutput(c.shape,c.dtype),f=c.shape[p],d=e.dataIdMap.get(c.dataId).id,h=e.dataIdMap.get(m.dataId).id;kW(d,i?1:0,a?1:0,f,h,Nt[o.dtype]);let g=m;if(l!==null){let x=S.getUndoAxesPermutation(l);g=go({inputs:{x:m},attrs:{perm:x},backend:e}),e.disposeData(c.dataId),e.disposeData(m.dataId)}return g}var TW={kernelName:ls,backendName:"wasm",setupFunc:Put,kernelFunc:Mut};var _W;function Lut(r){_W=r.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])}function zut(r){let{backend:t,inputs:e,attrs:n}=r,{x:o,weights:s}=e,{size:i,binaryOutput:a}=n,u=s.shape.reduce((m,f)=>m*f,1)!==0,l=o.shape.length===1?[i]:[o.shape[0],i],c=t.makeOutput(l,s.dtype);function p(m){return t.dataIdMap.get(m.dataId).id}return _W(p(o),new Uint8Array(new Int32Array(o.shape).buffer),o.shape.length,i,u,p(s),Nt[s.dtype],a,p(c)),c}var EW={kernelName:eu,backendName:"wasm",setupFunc:Lut,kernelFunc:zut};var AW;function But(r){AW=r.wasm.cwrap(Va,null,["number","number","number","array","number","array","array","number","number"])}function Vut(r){let{backend:t,inputs:e,attrs:n}=r,{x:o}=e,{blockSize:s,dataFormat:i}=n,a=o.shape[0],u=i==="NHWC"?o.shape[1]:o.shape[2],l=i==="NHWC"?o.shape[2]:o.shape[3],c=i==="NHWC"?o.shape[3]:o.shape[1],p=u*s,m=l*s,f=c/(s*s),d=i==="NHWC"?[a,p,m,f]:[a,f,p,m],h=t.makeOutput(d,"float32"),x=t.dataIdMap.get(o.dataId).id,b=new Uint8Array(new Int32Array(y.computeStrides(o.shape)).buffer),w=new Uint8Array(new Int32Array(d).buffer),I=new Uint8Array(new Int32Array(y.computeStrides(d)).buffer),N=t.dataIdMap.get(h.dataId).id;return AW(x,s,i==="NHWC"?1:0,b,o.shape.length-1,w,I,d.length,N),h}var DW={kernelName:Va,backendName:"wasm",setupFunc:But,kernelFunc:Vut};var $W;function Gut(r){$W=r.wasm.cwrap(us,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Wut(r){let{inputs:t,attrs:e,backend:n}=r,{x:o,filter:s}=t,i=n.dataIdMap.get(o.dataId).id,a=n.dataIdMap.get(s.dataId).id,{strides:u,dilations:l,pad:c,dimRoundingMode:p}=e,m=l==null?[1,1]:l,f=S.computeConv2DInfo(o.shape,s.shape,u,m,c,p,!0),d=f.filterHeight,h=f.filterWidth,g=f.padInfo.top,x=f.padInfo.right,b=f.padInfo.bottom,w=f.padInfo.left,I=f.dilationHeight,N=f.dilationWidth,E=f.strideHeight,A=f.strideWidth,D=f.inChannels,F=f.outChannels,P=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let V=n.makeOutput(f.outShape,"float32"),G=n.dataIdMap.get(V.dataId).id;return $W(i,o.shape[0],o.shape[1],o.shape[2],a,d,h,g,x,b,w,P,I,N,E,A,D,F,G),V}var RW={kernelName:us,backendName:"wasm",setupFunc:Gut,kernelFunc:Wut};var FW;function Uut(r){FW=r.wasm.cwrap("Diag",null,["number","number","number","number"])}function Hut(r){let{inputs:t,backend:e}=r,{x:n}=t,o=y.sizeFromShape(n.shape),s=e.makeOutput([...n.shape,...n.shape],n.dtype);return FW(e.dataIdMap.get(n.dataId).id,Nt[n.dtype],o,e.dataIdMap.get(s.dataId).id),s}var OW={kernelName:ru,backendName:"wasm",setupFunc:Uut,kernelFunc:Hut};var PW;function qut(r){PW=r.wasm.cwrap(cs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Kut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n;if(o.dtype!==s.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${o.dtype} and ${s.dtype}`);let l=S.computeDilation2DInfo(o.shape,s.shape,i,a,"NHWC",u),c=e.makeOutput(l.outShape,o.dtype);return PW(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(c.dataId).id,Nt[o.dtype],l.batchSize,l.inChannels,l.inHeight,l.inWidth,l.outHeight,l.outWidth,l.strideHeight,l.strideWidth,l.dilationHeight,l.dilationWidth,l.filterHeight,l.filterWidth,l.padInfo.top,l.padInfo.left),c}var MW={kernelName:cs,backendName:"wasm",setupFunc:qut,kernelFunc:Kut};var LW;function jut(r){LW=r.wasm.cwrap(ou,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Xut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,dy:i}=t,{strides:a,pad:u,dilations:l}=n;if(o.dtype!==s.dtype||o.dtype!==i.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${o.dtype}, ${s.dtype}, and ${i.dtype}`);let c=S.computeDilation2DInfo(o.shape,s.shape,a,u,"NHWC",l),p=e.makeOutput(s.shape,s.dtype);return LW(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(i.dataId).id,e.dataIdMap.get(p.dataId).id,Nt[o.dtype],c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.filterHeight,c.filterWidth,c.padInfo.top,c.padInfo.left),p}var zW={kernelName:ou,backendName:"wasm",setupFunc:jut,kernelFunc:Xut};var BW;function Yut(r){BW=r.wasm.cwrap(nu,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Zut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,dy:i}=t,{strides:a,pad:u,dilations:l}=n;if(o.dtype!==s.dtype||o.dtype!==i.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${o.dtype}, ${s.dtype}, and ${i.dtype}`);let c=S.computeDilation2DInfo(o.shape,s.shape,a,u,"NHWC",l),p=e.makeOutput(o.shape,o.dtype);return BW(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(i.dataId).id,e.dataIdMap.get(p.dataId).id,Nt[o.dtype],c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.filterHeight,c.filterWidth,c.padInfo.top,c.padInfo.left),p}var VW={kernelName:nu,backendName:"wasm",setupFunc:Yut,kernelFunc:Zut};var GW=yt(ms);var WW;function Jut(r){WW=r.wasm.cwrap(Ga,null,["number","number","number"])}function Qut(r){let{inputs:t,backend:e}=r,{dy:n,y:o}=t,s=e.makeOutput(o.shape,"float32"),i=a=>e.dataIdMap.get(a.dataId).id;return WW(i(o),i(n),i(s)),s}var UW={kernelName:Ga,backendName:"wasm",setupFunc:Jut,kernelFunc:Qut};var tct=!1,HW=ee(Wa,tct,"bool");var qW=yt(fs);var KW=yt(ds,"float32");function NC(r){let{inputs:t,attrs:e,backend:n}=r,{input:o}=t,{dim:s}=e,i=o.shape.length,a=o.shape.slice(),u=s;return s<0&&(y.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),u=i+s+1),a.splice(u,0,1),mr({inputs:{x:o},backend:n,attrs:{shape:a}})}var jW={kernelName:Li,backendName:"wasm",kernelFunc:NC};var XW=yt(hs,"float32");function H1(r){let{attrs:{shape:t,value:e,dtype:n},backend:o}=r,s=o.makeOutput(t,n);return o.typedArrayFromHeap(s).fill(e),s}var YW={kernelName:su,backendName:"wasm",kernelFunc:H1};var ZW;function ect(r){ZW=r.wasm.cwrap(Ua,null,["number","number","number","number","number","number"])}function rct(r){let{inputs:t,backend:e}=r,{image:n}=t,o=e.makeOutput(n.shape,n.dtype),s=e.dataIdMap.get(n.dataId).id,i=e.dataIdMap.get(o.dataId).id,[a,u,l,c]=n.shape;return ZW(s,a,u,l,c,i),o}var JW={kernelName:Ua,backendName:"wasm",kernelFunc:rct,setupFunc:ect};var QW=yt(gs);var nct=!1,tU=ee(xs,nct);var eU;function oct(r){eU=r.wasm.cwrap(ys,null,["number","number","number","number","number","number","number"])}function sct(r){let{backend:t,inputs:e,attrs:n}=r,{varianceEpsilon:o}=n,{x:s,mean:i,variance:a,offset:u,scale:l}=e,c=t.dataIdMap.get(s.dataId).id,p=t.dataIdMap.get(i.dataId).id,m=t.dataIdMap.get(a.dataId).id,f=u!=null?t.dataIdMap.get(u.dataId).id:0,d=l!=null?t.dataIdMap.get(l.dataId).id:0,h=t.makeOutput(s.shape,s.dtype);if(y.sizeFromShape(s.shape)===0)return h;let g=t.dataIdMap.get(h.dataId).id;return eU(c,p,m,f,d,o,g),h}var rU={kernelName:ys,backendName:"wasm",setupFunc:oct,kernelFunc:sct};var nU;function ict(r){nU=r.wasm.cwrap(Ji,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function act(r){let{inputs:t,attrs:e,backend:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=e,h=S.computeConv2DInfo(o.shape,s.shape,u,c,l,m),g=nc[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);let x=n.dataIdMap.get(o.dataId).id,b=n.dataIdMap.get(s.dataId).id,w=h.outChannels,I=0;if(i!=null){let ot=n.dataIdMap.get(i.dataId);if(ot.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${ot.shape.length}.`);if(ot.shape[0]!==w)throw new Error(`FusedConv2D bias shape (${ot.shape}) does not match the number of output channels (${w})`);I=ot.id}let N=h.filterHeight,E=h.filterWidth,A=h.padInfo.top,D=h.padInfo.right,F=h.padInfo.bottom,P=h.padInfo.left,V=h.dilationHeight,G=h.dilationWidth,W=h.strideHeight,q=h.strideWidth,H=h.inChannels,K=h.padInfo.type==="SAME"?1:0,X=h.batchSize,Z=h.inHeight,et=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let nt=n.makeOutput(h.outShape,"float32"),st=n.dataIdMap.get(nt.dataId).id,at=a==null?0:n.dataIdMap.get(a.dataId).id;return nU(x,X,Z,et,b,N,E,I,A,D,F,P,K,V,G,W,q,H,w,g,at,d||0,st),nt}var oU={kernelName:Ji,backendName:"wasm",setupFunc:ict,kernelFunc:act};var sU;function lct(r){sU=r.wasm.cwrap(Qi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function uct(r){let{inputs:t,attrs:e,backend:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=e,h=S.computeConv2DInfo(o.shape,s.shape,u,c,l,m,!0),g=nc[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let x=n.dataIdMap.get(o.dataId).id,b=n.dataIdMap.get(s.dataId).id,w=h.outChannels,I=0;if(i!=null){let ot=n.dataIdMap.get(i.dataId);if(ot.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${ot.shape.length}.`);if(ot.shape[0]!==w)throw new Error(`FusedDepthwiseConv2D bias shape (${ot.shape}) does not match the number of output channels (${w})`);I=ot.id}let N=h.filterHeight,E=h.filterWidth,A=h.padInfo.top,D=h.padInfo.right,F=h.padInfo.bottom,P=h.padInfo.left,V=h.dilationHeight,G=h.dilationWidth,W=h.strideHeight,q=h.strideWidth,H=h.inChannels,K=h.padInfo.type==="SAME"?1:0,X=h.batchSize,Z=h.inHeight,et=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let nt=n.makeOutput(h.outShape,"float32"),st=n.dataIdMap.get(nt.dataId).id,at=a==null?0:n.dataIdMap.get(a.dataId).id;return sU(x,X,Z,et,b,N,E,I,A,D,F,P,K,V,G,W,q,H,w,g,at,d||0,st),nt}var iU={kernelName:Qi,backendName:"wasm",setupFunc:lct,kernelFunc:uct};var aU;function cct(r){aU=r.wasm.cwrap(Ha,null,["number","number","number","number","number","number","array","number"])}function pct(r){let{backend:t,inputs:e}=r,{params:n,indices:o}=e,[s,i,a,u]=Dy.prepareAndValidate(n,o),l=t.makeOutput(s,n.dtype);if(i===0)return l;let c=o.shape,p=c[c.length-1],f=t.dataIdMap.get(n.dataId).id,h=t.dataIdMap.get(o.dataId).id,g=new Uint8Array(new Int32Array(u).buffer),x=t.dataIdMap.get(l.dataId).id;return aU(f,Nt[n.dtype],h,i,p,a,g,x),l}var lU={kernelName:Ha,backendName:"wasm",setupFunc:cct,kernelFunc:pct};var uU;function mct(r){uU=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function fct(r){let{backend:t,inputs:e,attrs:n}=r,{x:o,indices:s}=e,{axis:i,batchDims:a}=n,u=y.parseAxisParam(i,o.shape)[0],l=t.readSync(s.dataId),c=o.shape[u];for(let F=0;F<l.length;++F){let P=l[F];y.assert(P<=c-1&&P>=0,()=>`GatherV2: the index value ${P} is not in [0, ${c-1}]`)}let p=S.segment_util.collectGatherOpShapeInfo(o,s,u,a),m=mr({inputs:{x:o},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),f=y.sizeFromShape(s.shape),d=mr({inputs:{x:s},attrs:{shape:[p.batchSize,f/p.batchSize]},backend:t}),h=[p.batchSize,p.outerSize,f/p.batchSize,p.sliceSize],g=t.makeOutput(h,o.dtype);if(y.sizeFromShape(o.shape)===0)return g;let x=m.shape.length-1,w=t.dataIdMap.get(m.dataId).id,N=t.dataIdMap.get(d.dataId).id,E=t.dataIdMap.get(g.dataId).id,A=new Uint8Array(new Int32Array(y.computeStrides(m.shape)).buffer),D=new Uint8Array(new Int32Array(y.computeStrides(h)).buffer);return uU(w,Nt[o.dtype],A,x,N,p.batchSize,D,E),t.disposeData(m.dataId),t.disposeData(d.dataId),g.shape=p.outputShape,g}var cU={kernelName:zi,backendName:"wasm",setupFunc:mct,kernelFunc:fct};var dct=!1,pU=ee(qa,dct,"bool");var hct=!1,mU=ee(bs,hct,"bool");var fU=yt(ws,"bool");var dU=yt(Is,"bool");var hU=yt(Cs,"bool");var gU;function gct(r){gU=r.wasm.cwrap(vs,null,["number","number","number","number"])}function xct(r){let{inputs:{x:t},attrs:{alpha:e},backend:n}=r,o=n.dataIdMap.get(t.dataId).id,s=n.makeOutput(t.shape,"float32");if(y.sizeFromShape(t.shape)!==0){let i=n.dataIdMap.get(s.dataId).id;gU(o,Nt[t.dtype],e,i)}return s}var xU={kernelName:vs,backendName:"wasm",setupFunc:gct,kernelFunc:xct};var yct=!1,yU=ee(Ka,yct,"bool");var bct=!1,bU=ee(ja,bct,"bool");var wU;function wct(r){wU=r.wasm.cwrap(Xa,null,["number","number","number","number"])}function Ict(r){let{attrs:t,backend:e}=r,{start:n,stop:o,num:s}=t,i=Math.floor(s),a=e.makeOutput([i],"float32");return wU(e.dataIdMap.get(a.dataId).id,n,o,i),a}var IU={kernelName:Xa,backendName:"wasm",setupFunc:wct,kernelFunc:Ict};var CU=yt(Ss);var vU=yt(Ns);var Cct=!1,SU=ee(Ya,Cct,"bool");var NU=yt(Za);var vct=!1,kU=ee(Ja,vct,"bool");var Sct=!1,TU=ee(v_,Sct,"bool");var _U;function Nct(r){_U=r.wasm.cwrap(ks,null,["number","number","number","number","number","number","number"])}function kct(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{depthRadius:s,bias:i,alpha:a,beta:u}=n;if(o.dtype!=="float32")throw new Error("LRN error: x must have dtype float32");let l=e.makeOutput(o.shape,o.dtype);return _U(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(l.dataId).id,o.shape[3],s,i,a,u),l}var EU={kernelName:ks,backendName:"wasm",setupFunc:Nct,kernelFunc:kct};var AU;function Tct(r){AU=r.wasm.cwrap(Qa,null,["number","number","number","number","number","number","number","number","number"])}function _ct(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,y:s,dy:i}=t,{depthRadius:a,bias:u,alpha:l,beta:c}=n;if(o.dtype!=="float32"||s.dtype!=="float32"||i.dtype!=="float32")throw new Error("LRNGrad error: x, y, and dy must have dtype float32");let p=e.makeOutput(o.shape,o.dtype);return AU(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(i.dataId).id,e.dataIdMap.get(p.dataId).id,i.shape[3],a,u,l,c),p}var DU={kernelName:Qa,backendName:"wasm",setupFunc:Tct,kernelFunc:_ct};var $U;function Ect(r){$U=r.wasm.cwrap(Ts,null,["number","number","number","number"])}function Act(r){let{backend:t,inputs:e,attrs:n}=r,{reductionIndices:o,keepDims:s}=n,{x:i}=e,u=t.dataIdMap.get(i.dataId).id,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t);if(f){let w=t.dataIdMap.get(c.dataId).id;l=c,u=w}let d=l.shape.length;S.assertAxesAreInnerMostDims("max",p,d);let[h,g]=S.computeOutAndReduceShapes(l.shape,p),x=y.sizeFromShape(g),b=t.makeOutput(h,i.dtype);if(y.sizeFromShape(l.shape)!==0){let w=t.dataIdMap.get(b.dataId).id;$U(u,Nt[i.dtype],x,w)}if(f&&t.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var RU={kernelName:Ts,backendName:"wasm",setupFunc:Ect,kernelFunc:Act};var Dct=!1,FU=ee(_s,Dct);var OU;function $ct(r){OU=r.wasm.cwrap(Es,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Rct(r){let{inputs:t,attrs:e,backend:n}=r,o=t.x,s=n.dataIdMap.get(o.dataId).id;y.assert(o.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${o.dtype}.`);let{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=e,c=S.computePool2DInfo(o.shape,i,a,1,u,l),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,x=c.dilationHeight,b=c.dilationWidth,w=c.strideHeight,I=c.strideWidth,N=c.inChannels,E=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let A=n.makeOutput(c.outShape,"float32"),D=n.dataIdMap.get(A.dataId).id;return OU(s,o.shape[0],o.shape[1],o.shape[2],p,m,f,d,h,g,x,b,w,I,N,E,D),A}var PU={kernelName:Es,backendName:"wasm",setupFunc:$ct,kernelFunc:Rct};var MU;function Fct(r){MU=r.wasm.cwrap("MaxPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Oct(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u,dataFormat:l}=n,c=S.computePool3DInfo(o.shape,s,i,1,a,u,l),p=e.makeOutput(c.outShape,o.dtype);return MU(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),p}var LU={kernelName:Bi,backendName:"wasm",setupFunc:Fct,kernelFunc:Oct};var zU;function Pct(r){zU=r.wasm.cwrap("MaxPool3DGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Mct(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=n,c=S.computePool3DInfo(s.shape,i,a,1,u,l),p=e.makeOutput(s.shape,s.dtype);return zU(e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),p}var BU={kernelName:au,backendName:"wasm",setupFunc:Pct,kernelFunc:Mct};var VU;function Lct(r){VU=r.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function zct(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,{filterSize:i,strides:a,pad:u,dimRoundingMode:l}=n,c=S.computePool2DInfo(s.shape,i,a,1,u,l),p=e.makeOutput(s.shape,s.dtype);return VU(e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.top,c.padInfo.left),p}var GU={kernelName:iu,backendName:"wasm",setupFunc:Lct,kernelFunc:zct};var WU;function Bct(r){WU=r.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Vct(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,includeBatchInIndex:u}=n;y.assert(o.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.shape.length}.`);let l=[1,1];y.assert(S.eitherStridesOrDilationsAreOne(i,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=S.computePool2DInfo(o.shape,s,i,[1,1],a),p=e.makeOutput(c.outShape,o.dtype),m=e.makeOutput(c.outShape,"int32");return WU(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(p.dataId).id,e.dataIdMap.get(m.dataId).id,Nt[o.dtype],u,c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.top,c.padInfo.left),[p,m]}var UU={kernelName:lu,backendName:"wasm",setupFunc:Bct,kernelFunc:Vct};var HU;function Gct(r){HU=r.wasm.cwrap(As,null,["number, number, number"])}function Wct(r){let{backend:t,inputs:e,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=e,a=t.dataIdMap.get(i.dataId).id,u=a,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t),d=p;if(f){let I=t.dataIdMap.get(c.dataId).id;I!==a&&(l=c,u=I,d=S.getInnerMostAxes(d.length,l.shape.length))}S.assertAxesAreInnerMostDims("mean",d,l.shape.length);let[h,g]=S.computeOutAndReduceShapes(l.shape,d),x=y.sizeFromShape(g),b=l;l.dtype!=="float32"&&(b=Mn({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),u=t.dataIdMap.get(b.dataId).id);let w=t.makeOutput(h,"float32");if(y.sizeFromShape(l.shape)!==0){let I=t.dataIdMap.get(w.dataId).id;HU(u,x,I)}if(f&&t.disposeData(c.dataId),s){let I=S.expandShapeToKeepDim(w.shape,m);w.shape=I}return l.dtype!=="float32"&&t.disposeData(b.dataId),w}var qU={kernelName:As,backendName:"wasm",setupFunc:Gct,kernelFunc:Wct};var KU;function Uct(r){KU=r.wasm.cwrap(Ds,null,["number","number","number","number"])}function Hct(r){let{backend:t,inputs:e,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=e,a=t.dataIdMap.get(i.dataId).id,u=a,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t);if(f){let w=t.dataIdMap.get(c.dataId).id;w!==a&&(l=c,u=w)}let d=l.shape.length;S.assertAxesAreInnerMostDims("min",p,d);let[h,g]=S.computeOutAndReduceShapes(l.shape,p),x=y.sizeFromShape(g),b=t.makeOutput(h,l.dtype);if(y.sizeFromShape(l.shape)!==0){let w=t.dataIdMap.get(b.dataId).id;KU(u,Nt[i.dtype],x,w)}if(f&&t.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var jU={kernelName:Ds,backendName:"wasm",setupFunc:Uct,kernelFunc:Hct};var qct=!1,XU=ee($s,qct);var q1;(function(r){r[r.reflect=0]="reflect",r[r.symmetric=1]="symmetric"})(q1||(q1={}));var YU;function Kct(r){YU=r.wasm.cwrap(Rs,null,["number","array","number","number","array","array","number","number"])}function jct(r){let{inputs:{x:t},backend:e,attrs:{paddings:n,mode:o}}=r,s=n.map((d,h)=>d[0]+t.shape[h]+d[1]),i=e.dataIdMap.get(t.dataId).id,a=e.makeOutput(s,t.dtype),u=e.dataIdMap.get(a.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),c=n.map(d=>d[0]),p=n.map(d=>d[1]),m=new Uint8Array(new Int32Array(c).buffer),f=new Uint8Array(new Int32Array(p).buffer);return YU(i,l,t.shape.length,Nt[t.dtype],m,f,q1[o],u),a}var ZU={kernelName:Rs,backendName:"wasm",kernelFunc:jct,setupFunc:Kct};var JU;function Xct(r){JU=r.wasm.cwrap(ni,null,["number","number","number","number"])}function K1(r){let{backend:t,inputs:{logits:e},attrs:{dim:n}}=r,o=t.dataIdMap.get(e.dataId).id,s=t.makeOutput(e.shape,e.dtype),i=t.dataIdMap.get(s.dataId).id,a=e.shape[n],u=y.sizeFromShape(e.shape)/a;return y.sizeFromShape(s.shape)===0||JU(o,i,a,u),s}var QU={kernelName:ni,backendName:"wasm",setupFunc:Xct,kernelFunc:K1};var t4;function Yct(r){t4=r.wasm.cwrap(tl,null,["number","number","number","number","number","number"])}function Zct(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{numSamples:s,seed:i,normalized:a}=n;if(o.dtype!=="float32")throw new Error(`Tensor logits must have dtype float32, got ${o.dtype}`);let u=a?o:K1({inputs:{logits:o},backend:e,attrs:{dim:o.shape.length-1}}),[l,c]=u.shape,p=e.makeOutput([l,s],"int32");return t4(e.dataIdMap.get(u.dataId).id,l,c,s,i,e.dataIdMap.get(p.dataId).id),a||e.disposeData(u.dataId),p}var e4={kernelName:tl,backendName:"wasm",setupFunc:Yct,kernelFunc:Zct};var r4=ee(Fs,!0);var Jct=!0,n4=ee(Os,Jct);var o4=yt(Vi);function Hd(r,t){let e=new Int32Array(r.wasm.HEAPU8.buffer,t,4),n=e[0],o=e[1],s=e[2],i=e[3];return r.wasm._free(t),{pSelectedIndices:n,selectedSize:o,pSelectedScores:s,pValidOutputs:i}}var s4;function Qct(r){s4=r.wasm.cwrap(rl,"number",["number","number","number","number","number"])}function tpt(r){let{backend:t,inputs:e,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:i}=n,{boxes:a,scores:u}=e,l=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(u.dataId).id,p=s4(l,c,s,o,i),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=Hd(t,p);return t.wasm._free(d),t.wasm._free(h),t.makeOutput([f],"int32",m)}var i4={kernelName:rl,backendName:"wasm",setupFunc:Qct,kernelFunc:tpt};var a4;function ept(r){a4=r.wasm.cwrap(nl,"number",["number","number","number","number","number","bool"])}function rpt(r){let{backend:t,inputs:e,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:a}=n,{boxes:u,scores:l}=e,c=t.dataIdMap.get(u.dataId).id,p=t.dataIdMap.get(l.dataId).id,m=a4(c,p,s,o,i,a),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=Hd(t,m);t.wasm._free(h);let x=t.makeOutput([d],"int32",f),b=t.makeOutput([],"int32",g);return[x,b]}var l4={kernelName:nl,backendName:"wasm",setupFunc:ept,kernelFunc:rpt};var u4;function npt(r){u4=r.wasm.cwrap(ol,"number",["number","number","number","number","number","number"])}function opt(r){let{backend:t,inputs:e,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:i,softNmsSigma:a}=n,{boxes:u,scores:l}=e,c=t.dataIdMap.get(u.dataId).id,p=t.dataIdMap.get(l.dataId).id,m=u4(c,p,s,o,i,a),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=Hd(t,m);t.wasm._free(g);let x=t.makeOutput([d],"int32",f),b=t.makeOutput([d],"float32",h);return[x,b]}var c4={kernelName:ol,backendName:"wasm",setupFunc:npt,kernelFunc:opt};var spt=!1,p4=ee(el,spt,"bool");var m4;function ipt(r){m4=r.wasm.cwrap(Ps,null,["number","number","number","number","number"])}function apt(r){let{inputs:t,backend:e,attrs:n}=r,{indices:o}=t,{dtype:s,depth:i,onValue:a,offValue:u}=n,l=e.makeOutput([...o.shape,i],s),c=e.dataIdMap.get(l.dataId).id,m=e.dataIdMap.get(o.dataId).id;return m4(m,i,a,u,c),l}var f4={kernelName:Ps,backendName:"wasm",setupFunc:ipt,kernelFunc:apt};function lpt(r){let{inputs:{x:t},backend:e}=r,n=e.makeOutput(t.shape,t.dtype);return e.typedArrayFromHeap(n).fill(1),n}var d4={kernelName:Gi,backendName:"wasm",kernelFunc:lpt};function upt(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n;if(t.length===1)return NC({inputs:{input:t[0]},backend:e,attrs:{dim:o}});let s=t[0].shape,i=t[0].dtype;t.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(i===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],u=t.map(c=>{let p=NC({inputs:{input:c},backend:e,attrs:{dim:o}});return a.push(p),p}),l=W1({inputs:u,backend:e,attrs:{axis:o}});return a.forEach(c=>e.disposeData(c.dataId)),l}var h4={kernelName:Wi,backendName:"wasm",kernelFunc:upt};var g4;function cpt(r){g4=r.wasm.cwrap(Ms,null,["number","array","number","number","array","array","number","number"])}function ppt(r){let{inputs:{x:t},backend:e,attrs:{paddings:n,constantValue:o}}=r,s=n.map((h,g)=>h[0]+t.shape[g]+h[1]);if(y.sizeFromShape(t.shape)===0)return H1({backend:e,attrs:{shape:s,value:o,dtype:t.dtype}});let i=e.dataIdMap.get(t.dataId).id,a=e.makeOutput(s,t.dtype),l=e.dataIdMap.get(a.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),p=n.map(h=>h[0]),m=n.map(h=>h[1]),f=new Uint8Array(new Int32Array(p).buffer),d=new Uint8Array(new Int32Array(m).buffer);return g4(i,c,t.shape.length,Nt[t.dtype],f,d,o,l),a}var kC={kernelName:Ms,backendName:"wasm",kernelFunc:ppt,setupFunc:cpt};var mpt=!1,x4=ee(Ls,mpt);var y4;function fpt(r){y4=r.wasm.cwrap(zs,null,["number","number","number"])}function dpt(r){let{inputs:t,backend:e}=r,{x:n,alpha:o}=t,s=e.dataIdMap.get(n.dataId).id,i=e.dataIdMap.get(o.dataId).id,a=s,u=n,l=u;u.dtype!=="float32"&&(l=Mn({backend:e,inputs:{x:n},attrs:{dtype:"float32"}}),a=e.dataIdMap.get(l.dataId).id);let c=e.makeOutput(n.shape,"float32"),p=e.dataIdMap.get(c.dataId).id;return y4(a,i,p),u.dtype!=="float32"&&e.disposeData(l.dataId),c}var b4={kernelName:zs,backendName:"wasm",setupFunc:fpt,kernelFunc:dpt};var w4;function hpt(r){w4=r.wasm.cwrap(Bs,null,["number","number","number","number"])}function gpt(r){let{backend:t,inputs:e,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=e,a=t.dataIdMap.get(i.dataId).id,u=a,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t),d=p;if(f){let w=t.dataIdMap.get(c.dataId).id;w!==a&&(l=c,u=w,d=S.getInnerMostAxes(d.length,l.shape.length))}S.assertAxesAreInnerMostDims("prod",d,l.shape.length);let[h,g]=S.computeOutAndReduceShapes(l.shape,d),x=y.sizeFromShape(g),b=t.makeOutput(h,l.dtype);if(y.sizeFromShape(l.shape)!==0){let w=t.dataIdMap.get(b.dataId).id;w4(u,x,Nt[b.dtype],w)}if(f&&t.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var I4={kernelName:Bs,backendName:"wasm",setupFunc:hpt,kernelFunc:gpt};var xpt=r=>{let{backend:t,attrs:e}=r,{start:n,stop:o,step:s,dtype:i}=e,a=up(n,o,s,i),u=t.makeOutput([a.length],i);return t.typedArrayFromHeap(u).set(a),u},C4={kernelName:uu,backendName:"wasm",kernelFunc:xpt};var ypt=!0,v4=ee(ps,ypt);var S4=yt(Vs);var N4=yt(Gs);var k4=yt(Hs);var T4;function bpt(r){T4=r.wasm.cwrap(Us,null,["number","number","number","number","number","number","number","number","number","number"])}function wpt(r){let{backend:t,inputs:e,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:i,size:a}=n,[u,l]=a,[c,p,m,f]=o.shape,d=[c,u,l,f],h=t.dataIdMap.get(o.dataId),g;h.dtype!=="float32"&&(g=Mn({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),h=t.dataIdMap.get(g.dataId));let x=h.id,b=t.makeOutput(d,"float32");if(y.sizeFromShape(o.shape)===0)return b;let w=t.dataIdMap.get(b.dataId).id;return T4(x,c,p,m,f,u,l,s?1:0,i?1:0,w),g!=null&&t.disposeData(g.dataId),b}var _4={kernelName:Us,backendName:"wasm",setupFunc:bpt,kernelFunc:wpt};var E4;function Ipt(r){E4=r.wasm.cwrap(il,null,["number","number","number","array","array","boolean"])}function Cpt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n,a=e.makeOutput(o.shape,"float32"),u=e.dataIdMap.get(o.dataId),l;return u.dtype!=="float32"&&(l=Mn({backend:e,inputs:{x:o},attrs:{dtype:"float32"}}),u=e.dataIdMap.get(l.dataId)),E4(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(a.dataId).id,new Uint8Array(new Int32Array(o.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),l!=null&&e.disposeData(l.dataId),a}var A4={kernelName:il,backendName:"wasm",setupFunc:Ipt,kernelFunc:Cpt};var D4;function vpt(r){D4=r.wasm.cwrap(Ws,null,["number","number","number","number","number","number","number","number","number","number"])}function Spt(r){let{backend:t,inputs:e,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:i,size:a}=n,[u,l]=a,[c,p,m,f]=o.shape,d=[c,u,l,f],h=t.makeOutput(d,"float32");if(y.sizeFromShape(o.shape)===0)return h;let g=t.dataIdMap.get(o.dataId),x;g.dtype!=="float32"&&(x=Mn({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(x.dataId));let b=g.id,w=t.dataIdMap.get(h.dataId).id;return D4(b,c,p,m,f,u,l,s?1:0,i?1:0,w),x!=null&&t.disposeData(x.dataId),h}var $4={kernelName:Ws,backendName:"wasm",setupFunc:vpt,kernelFunc:Spt};var R4;function Npt(r){R4=r.wasm.cwrap(sl,null,["number","number","number","array","array","boolean"])}function kpt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n,a=e.makeOutput(o.shape,"float32"),u=e.dataIdMap.get(o.dataId),l;return u.dtype!=="float32"&&(l=Mn({backend:e,inputs:{x:o},attrs:{dtype:"float32"}}),u=e.dataIdMap.get(l.dataId)),R4(e.dataIdMap.get(o.dataId).id,e.dataIdMap.get(s.dataId).id,e.dataIdMap.get(a.dataId).id,new Uint8Array(new Int32Array(o.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),l!=null&&e.disposeData(l.dataId),a}var F4={kernelName:sl,backendName:"wasm",setupFunc:Npt,kernelFunc:kpt};var O4;function Tpt(r){O4=r.wasm.cwrap(qs,null,["number","array","number","array","number","number"])}function _pt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dims:s}=n,i=y.parseAxisParam(s,o.shape);if(o.shape.length===0)return Tp({inputs:{x:o},backend:e});let a=e.makeOutput(o.shape,o.dtype),u=e.dataIdMap.get(o.dataId).id,l=e.dataIdMap.get(a.dataId).id,c=new Uint8Array(new Int32Array(i).buffer),p=new Uint8Array(new Int32Array(o.shape).buffer);O4(u,c,i.length,p,o.shape.length,l);let m=mr({inputs:{x:a},attrs:{shape:o.shape},backend:e});return e.disposeData(a.dataId),m}var P4={kernelName:qs,backendName:"wasm",kernelFunc:_pt,setupFunc:Tpt};var M4;function Ept(r){M4=r.wasm.cwrap(hl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Apt(r){let{inputs:t,backend:e,attrs:n}=r,{image:o}=t,{radians:s,fillValue:i,center:a}=n,u=e.makeOutput(o.shape,o.dtype),l=e.dataIdMap.get(o.dataId).id,c=e.dataIdMap.get(u.dataId).id,[p,m,f,d]=o.shape,[h,g]=S.getImageCenter(a,m,f),x=i===0,b=255,w=typeof i=="number"?[i,i,i,x?0:b]:[...i,b],I=new Uint8Array(new Int32Array(w).buffer);return M4(l,p,m,f,d,s,h,g,I,w.length,c),u}var L4={kernelName:hl,backendName:"wasm",kernelFunc:Apt,setupFunc:Ept};var z4=yt(Ks);var B4=yt(js);var V4;function Dpt(r){V4=r.wasm.cwrap(al,null,["number","number","number","number","number","number","array","number","number"])}function $pt(r){let{backend:t,inputs:e,attrs:n}=r,{indices:o,updates:s}=e,{shape:i}=n,a=t.makeOutput(i,s.dtype);if(y.sizeFromShape(i)===0)return a;let{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:m}=Mu.calculateShapes(s,o,i),d=t.dataIdMap.get(o.dataId).id,g=t.dataIdMap.get(s.dataId).id,x=new Uint8Array(new Int32Array(p).buffer),b=t.dataIdMap.get(a.dataId).id;return V4(d,g,Nt[s.dtype],u,l,c,x,m,b),a}var G4={kernelName:al,backendName:"wasm",setupFunc:Dpt,kernelFunc:$pt};var W4;function Rpt(r){W4=r.wasm.cwrap(ul,null,["number","number","number","number","number","number","bool","number"])}function Fpt(r){let{inputs:t,backend:e,attrs:n}=r,{sortedSequence:o,values:s}=t,{side:i}=n;if(o.dtype!==s.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${o.dtype} and ${s.dtype}`);let a=e.makeOutput(s.shape,"int32");function u(l){return e.dataIdMap.get(l.dataId).id}return W4(u(o),u(s),o.shape[0],o.shape[1],s.shape[1],Nt[o.dtype],i==="left",u(a)),a}var U4={kernelName:ul,backendName:"wasm",setupFunc:Rpt,kernelFunc:Fpt};var H4;function Opt(r){H4=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Ppt(r){let{inputs:t,backend:e}=r,{condition:n,t:o,e:s}=t,i=e.dataIdMap.get(n.dataId).id,a=e.dataIdMap.get(o.dataId).id,u=e.dataIdMap.get(s.dataId).id,l=e.makeOutput(o.shape,o.dtype),c=e.dataIdMap.get(l.dataId).id,p=n.shape.length,m=o.shape.length,f=p===0||p>1||m===1?1:y.sizeFromShape(o.shape.slice(1));return H4(i,a,u,f,c),l}var q4={kernelName:Hi,backendName:"wasm",kernelFunc:Ppt,setupFunc:Opt};var K4=yt(Xs);var j4;function Mpt(r){j4=r.wasm.cwrap(Qs,null,["number","number"])}function Lpt(r){let{backend:t,inputs:{x:e}}=r,n=t.dataIdMap.get(e.dataId).id,o=t.makeOutput(e.shape,e.dtype),s=t.dataIdMap.get(o.dataId).id;return y.sizeFromShape(o.shape)===0||j4(n,s),o}var X4={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Mpt,kernelFunc:Lpt};var Y4=yt(Js);var Z4=yt(Ys);var J4=yt(Zs);var Q4=yt(ti);function zpt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,paddings:i}=n,a=y.sizeFromShape(s),u=[[0,0]];u.push(...i);for(let E=1+s.length;E<o.shape.length;++E)u.push([0,0]);let l=kC.kernelFunc({inputs:{x:o},backend:e,attrs:{paddings:u,constantValue:0}}),c=S.getReshaped(l.shape,s,a,!1),p=S.getPermuted(c.length,s.length,!1),m=S.getReshapedPermuted(l.shape,s,a,!1),h=mr({inputs:{x:l},backend:e,attrs:{shape:c}}),b=go({inputs:{x:h},backend:e,attrs:{perm:p}}),N=mr({inputs:{x:b},backend:e,attrs:{shape:m}});return e.disposeData(l.dataId),e.disposeData(h.dataId),e.disposeData(b.dataId),N}var tH={kernelName:Ki,backendName:"wasm",kernelFunc:zpt};var eH;function Bpt(r){eH=r.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function Vpt(r){let{backend:t,inputs:e}=r,{indices:n,values:o,denseShape:s,defaultValue:i}=e,a=n.shape[0],u=n.shape[1],l=t.readSync(s.dataId)[0],c=[a+l,u],p=t.dataIdMap.get(n.dataId).id,m=t.dataIdMap.get(o.dataId).id,f=t.dataIdMap.get(i.dataId).id,d=t.makeOutput(c,n.dtype),h=t.dataIdMap.get(d.dataId).id,g=t.makeOutput(c.slice(0,1),o.dtype),x=t.dataIdMap.get(g.dataId).id,b=t.makeOutput([l],"bool"),w=t.dataIdMap.get(b.dataId).id,I=t.makeOutput([a],n.dtype),N=t.dataIdMap.get(I.dataId).id,E=t.makeOutput([4],"int32"),A=t.dataIdMap.get(E.dataId).id,D=eH(p,m,Nt[o.dtype],a,l,u,f,h,x,w,N,A),F=t.readSync(E.dataId),P;switch(F[0]){case 1:{P=S.getSparseFillEmptyRowsIndicesDenseShapeMismatch(F[1]);break}case 2:{P=S.getSparseFillEmptyRowsNegativeIndexErrorMessage(F[1],F[2]);break}case 3:P=S.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(F[1],F[2],F[3]);break;default:P=""}if(t.disposeData(E.dataId),P)throw t.disposeData(d.dataId),t.disposeData(g.dataId),t.disposeData(b.dataId),t.disposeData(I.dataId),new Error(P);let V=d,G=g;return D!==c[0]&&(V=Go({inputs:{x:d},attrs:{begin:0,size:[D,u]},backend:t}),G=Go({inputs:{x:g},attrs:{begin:0,size:D},backend:t}),t.disposeData(d.dataId),t.disposeData(g.dataId)),[V,G,b,I]}var rH={kernelName:cu,backendName:"wasm",setupFunc:Bpt,kernelFunc:Vpt};var nH;function Gpt(r){nH=r.wasm.cwrap(cl,null,["number","number","number","number","number","number","number"])}function Wpt(r){let{backend:t,inputs:e}=r,{inputIndices:n,inputShape:o,newShape:s}=e;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
| ${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
| ${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(n.dataId).id,a=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(s.dataId).id,l=n.shape[0],c=y.sizeFromShape(s.shape),p=t.makeOutput([l,c],n.dtype),m=t.dataIdMap.get(p.dataId).id,f=t.makeOutput([c],s.dtype),d=t.dataIdMap.get(f.dataId).id,h=t.makeOutput([3],"int32"),g=t.dataIdMap.get(h.dataId).id;nH(i,a,u,l,m,d,g);let x=t.readSync(h.dataId),b;switch(x[0]){case 0:{b=S.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(x[1],x[2]);break}case 1:{b=S.getSparseReshapeNegativeOutputDimErrorMessage(x[1],x[2]);break}case 2:b=S.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let w=Array.from(t.readSync(o.dataId)),I=Array.from(t.readSync(f.dataId));b=S.getSparseReshapeInputOutputMultipleErrorMessage(w,I);break}case 4:{let w=Array.from(t.readSync(o.dataId)),I=Array.from(t.readSync(f.dataId));b=S.getSparseReshapeInputOutputMismatchErrorMessage(w,I);break}default:b=""}if(t.disposeData(h.dataId),b)throw t.disposeData(p.dataId),t.disposeData(f.dataId),new Error(b);return[p,f]}var oH={kernelName:cl,backendName:"wasm",setupFunc:Gpt,kernelFunc:Wpt};var sH;function TC(r){sH=r.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function _C(r,t){let{backend:e,inputs:n}=r,{data:o,indices:s,segmentIds:i}=n,a=s.shape[0],u=e.readSync(i.dataId,a-1,a)[0],c=a>0?u+1:0;if(c<0)throw new Error(S.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=o.shape.slice();p[0]=c;let m=e.dataIdMap.get(o.dataId).id,f=e.dataIdMap.get(s.dataId).id,d=e.dataIdMap.get(i.dataId).id,h=e.makeOutput(p,o.dtype),g=e.dataIdMap.get(h.dataId).id,x=e.makeOutput([4],"int32"),b=e.dataIdMap.get(x.dataId).id;sH(m,Nt[o.dtype],o.shape[0],f,d,g,b,t,0);let w=e.readSync(x.dataId),I;switch(w[0]){case 0:{I=S.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{I=S.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:I=S.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(w[1],w[2]);break;case 3:I=S.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(w[1],w[2],w[3]);break;default:I=""}if(e.disposeData(x.dataId),I)throw e.disposeData(h.dataId),new Error(I);return h}function Upt(r){return _C(r,!0)}var iH={kernelName:pu,backendName:"wasm",setupFunc:TC,kernelFunc:Upt};function Hpt(r){return _C(r,!1)}var aH={kernelName:mu,backendName:"wasm",setupFunc:TC,kernelFunc:Hpt};var lH;function qpt(r){lH=r.wasm.cwrap(pl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Kpt(r){let{backend:t,inputs:e,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=e,{outputShape:a}=n,u=t.makeOutput(a,i.dtype);if(y.sizeFromShape(a)===0)return u;let{sliceRank:l,numUpdates:c,sliceSize:p,strides:m,outputSize:f}=S.calculateShapes(s,o,a),d=t.dataIdMap.get(o.dataId).id,h=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(i.dataId).id,x=new Uint8Array(new Int32Array(m).buffer),b=t.dataIdMap.get(u.dataId).id;return lH(d,h,s.shape.length,g,Nt[i.dtype],l,c,p,x,f,b),u}var uH={kernelName:pl,backendName:"wasm",setupFunc:qpt,kernelFunc:Kpt};function jpt(r){let{inputs:t,attrs:e,backend:n}=r,{x:o}=t,{numOrSizeSplits:s,axis:i}=e,a=y.parseAxisParam(i,o.shape)[0],u=S.prepareSplitSize(o,s,a),l=new Array(o.shape.length).fill(0),c=o.shape.slice();return u.map(p=>{let m=[...c];m[a]=p;let f=Go({inputs:{x:o},attrs:{begin:l,size:m},backend:n});return l[a]+=p,f})}var cH={kernelName:ji,backendName:"wasm",kernelFunc:jpt};var pH=yt(ei);var mH=yt(fu);var Xpt=!0,fH=ee(oi,Xpt);var dH;function Ypt(r){dH=r.wasm.cwrap(wo,null,["number","number","number","number"])}function Zpt(r){let{backend:t,inputs:e,attrs:n}=r,{alpha:o}=n,{x:s}=e,i=t.dataIdMap.get(s.dataId).id,a=t.makeOutput(s.shape,s.dtype),u=t.dataIdMap.get(a.dataId).id;return dH(i,o,Nt[s.dtype],u),a}var hH={kernelName:wo,backendName:"wasm",setupFunc:Ypt,kernelFunc:Zpt};var gH;function Jpt(r){gH=r.wasm.cwrap(ml,null,["number","array","number","array","array","array","array","array","number","number"])}function Qpt(r){let{backend:t,inputs:e,attrs:n}=r,{x:o}=e,{begin:s,end:i,strides:a,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n,{finalShapeSparse:f,finalShape:d,isIdentity:h,sliceDim0:g,isSimpleSlice:x,begin:b,end:w,strides:I}=ze.sliceInfo(o.shape,s,i,a,u,l,c,p,m),N;if(h)N=mr({inputs:{x:o},backend:t,attrs:{shape:d}});else if(g||x){y.assert(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);let E=ze.computeOutShape(b,w,I),A=Go({inputs:{x:o},backend:t,attrs:{begin:b,size:E}});N=mr({inputs:{x:A},backend:t,attrs:{shape:d}}),t.disposeData(A.dataId)}else{let E=t.makeOutput(f,"float32"),A=t.dataIdMap.get(o.dataId).id,D=new Uint8Array(new Int32Array(y.computeStrides(o.shape)).buffer),F=new Uint8Array(new Int32Array(b).buffer),P=new Uint8Array(new Int32Array(w).buffer),V=new Uint8Array(new Int32Array(I).buffer),G=new Uint8Array(new Int32Array(f).buffer),W=new Uint8Array(new Int32Array(y.computeStrides(f)).buffer),q=t.dataIdMap.get(E.dataId).id;gH(A,D,o.shape.length,F,P,V,G,W,f.length,q),N=mr({inputs:{x:E},backend:t,attrs:{shape:d}}),t.disposeData(E.dataId)}return N}var xH={kernelName:ml,backendName:"wasm",setupFunc:Jpt,kernelFunc:Qpt};function tmt(r){let{backend:t,inputs:e,attrs:n}=r,{data:o,dataSplits:s}=e,{separator:i,nGramWidths:a,leftPad:u,rightPad:l,padWidth:c,preserveShortSequences:p}=n,m=t.readSync(o.dataId),f=t.readSync(s.dataId),[d,h]=pp(m,f,i,a,u,l,c,p),g=t.makeOutput([d.length],"string"),x=t.dataIdMap.get(g.dataId);x.stringBytes=d;let b=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(b).set(h),[g,b]}var yH={kernelName:du,backendName:"wasm",kernelFunc:tmt};function emt(r){let{backend:t,inputs:e,attrs:n}=r,{input:o,delimiter:s}=e,{skipEmpty:i}=n,a=t.readSync(o.dataId),u=t.readSync(s.dataId),[l,c,p]=mp(a,u[0],i),m=c.length,f=t.makeOutput([m,2],"int32");t.typedArrayFromHeap(f).set(l);let h=t.makeOutput([m],"string"),g=t.dataIdMap.get(h.dataId);g.stringBytes=c;let x=t.makeOutput([2],"int32");return t.typedArrayFromHeap(x).set(p),[f,h,x]}var bH={kernelName:hu,backendName:"wasm",kernelFunc:emt};function rmt(r){let{backend:t,inputs:e,attrs:n}=r,{input:o}=e,{numBuckets:s}=n,i=t.readSync(o.dataId),a=fp(i,s),u=t.makeOutput(o.shape,"int32");return t.typedArrayFromHeap(u).set(a),u}var wH={kernelName:gu,backendName:"wasm",kernelFunc:rmt};var nmt=!0,IH=ee(si,nmt);var CH;function omt(r){CH=r.wasm.cwrap(ri,null,["number","number","number","number"])}function smt(r){let{backend:t,inputs:e,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=e,a=t.dataIdMap.get(i.dataId).id,u=a,l=i,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=Sn(i,o,t),d=p;if(f){let w=t.dataIdMap.get(c.dataId).id;w!==a&&(l=c,u=w,d=S.getInnerMostAxes(d.length,l.shape.length))}S.assertAxesAreInnerMostDims("sum",d,l.shape.length);let[h,g]=S.computeOutAndReduceShapes(l.shape,d),x=y.sizeFromShape(g),b=t.makeOutput(h,l.dtype);if(y.sizeFromShape(l.shape)!==0){let w=t.dataIdMap.get(b.dataId).id;CH(u,x,Nt[b.dtype],w)}if(f&&t.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var vH={kernelName:ri,backendName:"wasm",setupFunc:omt,kernelFunc:smt};var SH=yt(ii);var NH=yt(ai);var kH;function imt(r){kH=r.wasm.cwrap(ll,null,["number","number","number","number","number","number","array","number","number","number"])}function amt(r){let{backend:t,inputs:e,attrs:n}=r,{tensor:o,indices:s,updates:i}=e,{}=n,a=t.makeOutput(o.shape,o.dtype);if(y.sizeFromShape(o.shape)===0)return a;let{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:m}=Mu.calculateShapes(i,s,o.shape),d=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(i.dataId).id,b=t.dataIdMap.get(o.dataId).id,w=new Uint8Array(new Int32Array(p).buffer),I=t.dataIdMap.get(a.dataId).id;return kH(d,g,Nt[i.dtype],u,l,c,w,m,I,b),a}var TH={kernelName:ll,backendName:"wasm",setupFunc:imt,kernelFunc:amt};var _H;function lmt(r){_H=r.wasm.cwrap(lo,null,["number","array","number","array","number","number"])}function umt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,s=e.dataIdMap.get(o.dataId).id,{reps:i}=n,a=new Array(o.shape.length);for(let m=0;m<a.length;m++)a[m]=o.shape[m]*i[m];let u=new Uint8Array(new Int32Array(o.shape).buffer),l=new Uint8Array(new Int32Array(a).buffer),c=e.makeOutput(a,o.dtype),p=e.dataIdMap.get(c.dataId).id;return _H(s,u,o.shape.length,l,a.length,Nt[c.dtype],p),c}var EH={kernelName:lo,backendName:"wasm",setupFunc:lmt,kernelFunc:umt};var AH;function cmt(r){AH=r.wasm.cwrap(fl,null,["number","array","number","number","number","bool","number","number"])}var pmt=({inputs:r,backend:t,attrs:e})=>{let{x:n}=r,{k:o,sorted:s}=e,i=t.dataIdMap.get(n.dataId).id,a=new Uint8Array(new Int32Array(n.shape).buffer),u=n.shape.slice();u[u.length-1]=o;let l=t.makeOutput(u,n.dtype),c=t.dataIdMap.get(l.dataId).id,p=t.makeOutput(u,"int32"),m=t.dataIdMap.get(p.dataId).id;return AH(i,a,n.shape.length,Nt[n.dtype],o,s,c,m),[l,p]},DH={kernelName:fl,backendName:"wasm",setupFunc:cmt,kernelFunc:pmt};var $H;function mmt(r){$H=r.wasm.cwrap(dl,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function fmt(r){let{backend:t,inputs:e,attrs:n}=r,{image:o,transforms:s}=e,{interpolation:i,fillMode:a,fillValue:u,outputShape:l}=n,[c,p,m,f]=o.shape,[d,h]=l!=null?l:[p,m],g=[c,d,h,f],x=new Uint8Array(new Int32Array(y.computeStrides(o.shape)).buffer),b=new Uint8Array(new Int32Array(y.computeStrides(g)).buffer),w=t.makeOutput(g,o.dtype),I=t.dataIdMap.get(w.dataId).id,E=t.dataIdMap.get(o.dataId).id,D=t.dataIdMap.get(s.dataId).id,F=i==="nearest"?1:2,P;switch(a){case"constant":P=1;break;case"reflect":P=2;break;case"wrap":P=3;break;case"nearest":P=4;break;default:P=1;break}return $H(E,D,s.shape[0]>1,c,d,h,f,m,p,x,o.shape.length-1,b,g.length-1,F,P,u,I),w}var RH={kernelName:dl,backendName:"wasm",setupFunc:mmt,kernelFunc:fmt};function dmt(r){let{inputs:t,attrs:e,backend:n}=r,{axis:o}=e,{x:s}=t,{outputValues:i,outputShape:a,indices:u}=dp(n.readSync(s.dataId),o,s.shape,s.dtype);return[n.makeOutput(a,s.dtype,void 0,i),n.makeOutput([u.length],"int32",void 0,u)]}var FH={kernelName:xu,backendName:"wasm",kernelFunc:dmt};function hmt(r){let{inputs:t,backend:e,attrs:n}=r,{value:o}=t,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o.shape[s],a=o.shape.length,u=new Array(a-1),l=0;for(let f=0;f<a;f++)f!==s&&(u[l++]=o.shape[f]);let c=new Array(i),p=new Array(a).fill(0),m=o.shape.slice();m[s]=1;for(let f=0;f<c.length;f++)p[s]=f,c[f]=Go({inputs:{x:o},attrs:{begin:p,size:m},backend:e});return c.map(({dataId:f,dtype:d})=>({dataId:f,dtype:d,shape:u}))}var OH={kernelName:Xi,backendName:"wasm",kernelFunc:hmt};function gmt(r){let{inputs:{x:t},backend:e}=r,n=e.makeOutput(t.shape,t.dtype);return e.typedArrayFromHeap(n).fill(0),n}var PH={kernelName:Yi,backendName:"wasm",kernelFunc:gmt};var xmt=[IG,CG,vG,SG,NG,TG,$G,FG,OG,PG,MG,LG,zG,BG,VG,WG,XG,HG,KG,JG,tW,rW,nW,oW,sW,iW,lW,uW,pW,fW,hW,xW,bW,wW,IW,vW,NW,TW,EW,DW,RW,OW,MW,zW,VW,GW,UW,HW,qW,KW,jW,XW,YW,JW,QW,tU,rU,oU,iU,lU,cU,pU,mU,_G,fU,dU,hU,xU,yU,bU,IU,vU,CU,SU,NU,kU,TU,EU,DU,RU,FU,PU,LU,BU,GU,UU,qU,jU,XU,ZU,e4,r4,n4,o4,i4,l4,c4,p4,f4,d4,h4,kC,x4,b4,I4,C4,v4,S4,N4,k4,YG,_4,A4,$4,F4,P4,L4,z4,B4,G4,U4,q4,K4,X4,Y4,Z4,J4,QG,QU,Q4,tH,rH,oH,iH,aH,uH,cH,pH,mH,fH,hH,xH,yH,bH,wH,IH,vH,SH,NH,TH,EH,DH,RH,AG,FH,OH,PH];for(let r of xmt)pc(r);var j1=L();j1.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11]))}catch(r){return!1}});j1.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(j1.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(r){return!1}});var e_=Xl(BH()),qH=Xl(GH()),r_=Xl(WH());var UH=e_.default||e_,ymt=r_.default||r_,Ig=class extends Uo{constructor(t){super(),this.wasm=t,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(jH),t_=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Da(this,Wn())}write(t,e,n){let o={id:this.dataIdNextNumber++};return this.move(o,t,e,n,1),o}numDataIds(){return this.dataIdMap.numDataIds()}async time(t){let e=y.now();return t(),{kernelMs:y.now()-e}}move(t,e,n,o,s){let i=this.dataIdNextNumber++;if(o==="string"){let c=e;this.dataIdMap.set(t,{id:i,stringBytes:c,shape:n,dtype:o,memoryOffset:null,refCount:s});return}let a=y.sizeFromShape(n),u=a*y.bytesPerElement(o),l=this.wasm._malloc(u)>>>0;this.dataIdMap.set(t,{id:i,memoryOffset:l,shape:n,dtype:o,refCount:s}),this.wasm.tfjs.registerTensor(i,a,l),e!=null&&this.wasm.HEAPU8.set(new Uint8Array(e.buffer,e.byteOffset,u),l)}async read(t){return this.readSync(t)}readSync(t,e,n){let{memoryOffset:o,dtype:s,shape:i,stringBytes:a}=this.dataIdMap.get(t);if(s==="string")return(e==null||e===0)&&(n==null||n>=a.length)?a:a.slice(e,n);e=e||0,n=n||y.sizeFromShape(i);let u=y.bytesPerElement(s),l=this.wasm.HEAPU8.slice(o+e*u,o+n*u);return wmt(l.buffer,s)}disposeData(t,e=!1){if(this.dataIdMap.has(t)){let n=this.dataIdMap.get(t);if(n.refCount--,!e&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(t)}return!0}refCount(t){return this.dataIdMap.has(t)?this.dataIdMap.get(t).refCount:0}incRef(t){let e=this.dataIdMap.get(t);e!=null&&e.refCount++}floatPrecision(){return 32}getMemoryOffset(t){return this.dataIdMap.get(t).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(t,e,n,o){let s;if(n==null)s=this.write(o!=null?o:null,t,e);else{let i=this.dataIdNextNumber++;s={id:i},this.dataIdMap.set(s,{id:i,memoryOffset:n,shape:t,dtype:e,refCount:1});let a=y.sizeFromShape(t);this.wasm.tfjs.registerTensor(i,a,n)}return{dataId:s,shape:t,dtype:e}}typedArrayFromHeap({shape:t,dtype:e,dataId:n}){let o=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(n),i=y.sizeFromShape(t);switch(e){case"float32":return new Float32Array(o,s,i);case"int32":return new Int32Array(o,s,i);case"bool":return new Uint8Array(o,s,i);default:throw new Error(`Unknown dtype ${e}`)}}};function bmt(r){return(t,e)=>(y.fetch(r,{credentials:"same-origin"}).then(n=>{n.ok||t.env.a(`failed to load wasm binary file at '${r}'`),n.arrayBuffer().then(o=>{WebAssembly.instantiate(o,t).then(s=>{e(s.instance,s.module)})})}),{})}function HH(r,t,e){if(DC!=null)return DC;let n="tfjs-backend-wasm.wasm";return r&&t?n="tfjs-backend-wasm-threaded-simd.wasm":r&&(n="tfjs-backend-wasm-simd.wasm"),bg!=null&&bg[n]!=null?bg[n]:e+n}async function KH(){let[r,t]=await Promise.all([L().getAsync("WASM_HAS_SIMD_SUPPORT"),L().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((e,n)=>{let o={};o.locateFile=(a,u)=>{if(a.endsWith(".worker.js")){let l=qH.wasmWorkerContents.replace(/\n/g,"\\n"),c=new Blob([l],{type:"application/javascript"});return URL.createObjectURL(c)}return a.endsWith(".wasm")?HH(r,t,yg!=null?yg:u):u+a},n_&&(o.instantiateWasm=bmt(HH(r,t,yg!=null?yg:"")));let s=!1;o.onAbort=()=>{if(s||wg)return;wg=!0,n({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let i;t&&r&&DC==null?(o.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+UH.toString()],{type:"text/javascript"}),i=UH(o)):i=ymt(o),i.then(a=>{s=!0,wg=!1;let u=null;a.tfjs={init:a.cwrap("init",null,[]),initWithThreadsCount:a.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:a.cwrap("get_threads_count","number",[]),registerTensor:a.cwrap("register_tensor",null,["number","number","number"]),disposeData:a.cwrap("dispose_data",u,["number"]),dispose:a.cwrap("dispose",u,[])},e({wasm:a})}).catch(n)})}function wmt(r,t){switch(t){case"float32":return new Float32Array(r);case"int32":return new Int32Array(r);case"bool":return new Uint8Array(r);default:throw new Error(`Unknown dtype ${t}`)}}var Imt=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],DC=null,yg=null,bg={},wg=!1,n_=!1;function Cmt(r,t=!1){if(K0("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),wg)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");DC=r,n_=t}function vmt(r,t=!1){if(wg)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof r=="string")yg=r;else{bg=r;let e=Imt.filter(n=>bg[n]==null);if(e.length>0)throw new Error(`There were no entries found for the following binaries: ${e.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}n_=t}var jH=-1,t_=-1;function Smt(r){jH=r}function Nmt(){if(t_===-1)throw new Error("WASM backend not initialized.");return t_}var kmt="4.7.0";var Tmt=2;im("wasm",async()=>{let{wasm:r}=await KH();return new Ig(r)},Tmt);var XH="4.7.0",_mt="4.7.0",Emt="4.7.0",Amt="4.7.0",Dmt="4.7.0",$mt={tfjs:XH,"tfjs-core":XH,"tfjs-converter":_mt,"tfjs-backend-cpu":Emt,"tfjs-backend-webgl":Amt,"tfjs-backend-wasm":Dmt};export{$i as Abs,qo as Acos,Ko as Acosh,$c as AdadeltaOptimizer,Rc as AdagradOptimizer,Fc as AdamOptimizer,Oc as AdamaxOptimizer,ao as Add,jo as AddN,Ra as All,Fa as Any,Ri as ArgMax,Fi as ArgMin,Xo as Asin,Yo as Asinh,Zo as Atan,Qo as Atan2,Jo as Atanh,ts as AvgPool,Oi as AvgPool3D,Jl as AvgPool3DGrad,Zl as AvgPoolGrad,Ig as BackendWasm,es as BatchMatMul,Pi as BatchToSpaceND,Oa as Bincount,Pa as BitwiseAnd,Ql as BroadcastArgs,C_ as BroadcastTo,Mb as Callback,Yy as CallbackList,xo as Cast,rs as Ceil,yo as ClipByValue,zp as Complex,tu as ComplexAbs,Mi as Concat,ns as Conv2D,Bp as Conv2DBackpropFilter,os as Conv2DBackpropInput,ss as Conv3D,Ma as Conv3DBackpropFilterV2,La as Conv3DBackpropInputV2,is as Cos,as as Cosh,Ba as CropAndResize,za as Cumprod,ls as Cumsum,Jy as CustomCallback,Da as DataStorage,eu as DenseBincount,Va as DepthToSpace,us as DepthwiseConv2dNative,Vp as DepthwiseConv2dNativeBackpropFilter,Gp as DepthwiseConv2dNativeBackpropInput,ru as Diag,cs as Dilation2D,ou as Dilation2DBackpropFilter,nu as Dilation2DBackpropInput,Zg as Draw,g0 as ENV,Lb as EarlyStopping,Wp as Einsum,ms as Elu,Ga as EluGrad,rh as Environment,Wa as Equal,fs as Erf,ds as Exp,Li as ExpandDims,hs as Expm1,Up as FFT,su as Fill,Ua as FlipLeftRight,gs as Floor,xs as FloorDiv,oh as FromPixels,ys as FusedBatchNorm,Ji as FusedConv2D,Qi as FusedDepthwiseConv2D,wp as GPGPUContext,Ha as GatherNd,zi as GatherV2,jh as GraphModel,qa as Greater,bs as GreaterEqual,Zy as History,Hp as IFFT,bo as Identity,qp as Imag,Ie as InputSpec,ws as IsFinite,Is as IsInf,Cs as IsNan,Uo as KernelBackend,ks as LRN,Qa as LRNGrad,Dh as LayerVariable,jn as LayersModel,vs as LeakyRelu,Ka as Less,ja as LessEqual,Xa as LinSpace,Ss as Log,Ns as Log1p,S_ as LogSoftmax,Ya as LogicalAnd,Za as LogicalNot,Ja as LogicalOr,v_ as LogicalXor,Lmt as LowerBound,Xu as MathBackendCPU,Qu as MathBackendWebGL,zmt as MatrixBandPart,Ts as Max,Es as MaxPool,Bi as MaxPool3D,au as MaxPool3DGrad,iu as MaxPoolGrad,lu as MaxPoolWithArgmax,_s as Maximum,As as Mean,Ds as Min,$s as Minimum,Rs as MirrorPad,Fs as Mod,Pc as MomentumOptimizer,tl as Multinomial,Os as Multiply,Vi as Neg,rl as NonMaxSuppressionV3,nl as NonMaxSuppressionV4,ol as NonMaxSuppressionV5,el as NotEqual,M0 as OP_SCOPE_SUFFIX,Ps as OneHot,Gi as OnesLike,Kr as Optimizer,Nh as OptimizerConstructors,Wi as Pack,Ms as PadV2,Bmt as Pool,Ls as Pow,zs as Prelu,Bs as Prod,Mc as RMSPropOptimizer,Dn as RNN,Kp as RaggedGather,jp as RaggedRange,Xp as RaggedTensorToTensor,uu as Range,T0 as Rank,Yp as Real,ps as RealDiv,Vs as Reciprocal,Ze as Reduction,Gs as Relu,Hs as Relu6,Ui as Reshape,Us as ResizeBilinear,il as ResizeBilinearGrad,Ws as ResizeNearestNeighbor,sl as ResizeNearestNeighborGrad,qs as Reverse,hl as RotateWithOffset,Ks as Round,js as Rsqrt,Sl as SGDOptimizer,al as ScatterNd,ul as SearchSorted,Hi as Select,Xs as Selu,Ia as Sequential,Qs as Sigmoid,Js as Sign,Ys as Sin,Zs as Sinh,qi as Slice,ni as Softmax,ti as Softplus,Ki as SpaceToBatchND,cu as SparseFillEmptyRows,cl as SparseReshape,pu as SparseSegmentMean,mu as SparseSegmentSum,pl as SparseToDense,ji as SplitV,ei as Sqrt,fu as Square,oi as SquaredDifference,cc as StaticRegexReplace,wo as Step,ml as StridedSlice,du as StringNGrams,hu as StringSplit,gu as StringToHashBucketFast,si as Sub,ri as Sum,nn as SymbolicTensor,ii as Tan,ai as Tanh,Ot as Tensor,le as TensorBuffer,ll as TensorScatterUpdate,lo as Tile,fl as TopK,dl as Transform,uo as Transpose,xu as Unique,Xi as Unpack,yu as UnsortedSegmentSum,Vmt as UpperBound,gl as Variable,Yi as ZerosLike,Zi as _FusedMatMul,Ee as abs,hx as acos,gx as acosh,Y as add,IE as addN,lm as all,bc as any,oa as argMax,xx as argMin,yx as asin,bx as asinh,wx as atan,Ix as atan2,Cx as atanh,Su as avgPool,vx as avgPool3d,wE as backend,S as backend_util,SE as basicLSTMCell,aa as batchNorm,Sx as batchNorm2d,Nx as batchNorm3d,kx as batchNorm4d,Nu as batchToSpaceND,Tx as bincount,kE as bitwiseAnd,F5 as booleanMaskAsync,TE as broadcastArgs,la as broadcastTo,Hr as broadcast_util,Ay as browser,wt as buffer,J9 as callbacks,Q as cast,_x as ceil,Sr as clipByValue,cn as clone,kn as complex,ie as concat,Ex as concat1d,Ax as concat2d,Dx as concat3d,$x as concat4d,fR as constraints,cm as conv1d,Tn as conv2d,mm as conv2dTranspose,Rx as conv3d,Ox as conv3dTranspose,jmt as copyRegisteredKernels,ku as cos,fm as cosh,Ih as cosineWindow,Ic as cumprod,dm as cumsum,fn as customGrad,ZF as data,gh as denseBincount,K0 as deprecationWarn,Px as depthToSpace,ua as depthwiseConv2d,rQ as deregisterOp,Cu as device_util,_E as diag,Mx as dilation2d,uht as disableDeprecationWarnings,Tt as dispose,cht as disposeVariables,ct as div,Lx as divNoNan,zx as dot,cN as dropout,AE as einsum,ca as elu,lht as enableDebugMode,aht as enableProdMode,pN as enclosingPowerOfTwo,Wn as engine,DE as ensureShape,L as env,Fr as equal,Bx as erf,Vx as euclideanNorm,ir as exp,ar as expandDims,Gx as expm1,Cc as eye,Ou as fft,No as fill,ght as findBackend,xht as findBackendFactory,pa as floor,am as floorDiv,Wz as forceHalfFloat,Lu as fused,ma as gather,U5 as gatherND,Dy as gather_util,dht as getBackend,b0 as getGradient,ih as getKernel,Jg as getKernelsForBackend,Nmt as getThreadsCount,w1 as gpgpu_util,M6 as grad,L6 as grads,Fe as greater,mn as greaterEqual,vl as ifft,Tu as imag,hn as image,K5 as inTopKAsync,dR as initializers,KN as input,Lr as io,Tm as irfft,Wx as isFinite,Ux as isInf,Hx as isNaN,$e as keep,jr as kernel_impls,jR as layers,_u as leakyRelu,Il as less,Un as lessEqual,fN as linalg,FE as linspace,JQ as loadGraphModel,QQ as loadGraphModelSync,FR as loadLayersModel,qx as localResponseNormalization,kr as log,Eu as log1p,Xx as logSigmoid,hm as logSoftmax,gm as logSumExp,Pr as logicalAnd,Au as logicalNot,xm as logicalOr,Yx as logicalXor,j8 as losses,OE as lowerBound,Bt as matMul,k2 as math,Nr as max,Du as maxPool,Jx as maxPool3d,PE as maxPoolWithArgmax,_n as maximum,ke as mean,fh as memory,ME as meshgrid,XR as metrics,bl as min,mo as minimum,Qx as mirrorPad,ty as mod,JZ as model,YR as models,vc as moments,M5 as movingAverage,$ as mul,LE as multiRNNCell,zE as multinomial,Ut as neg,kh as nextFrame,wl as norm,mi as notEqual,fa as oneHot,dr as ones,Ir as onesLike,k as op,BE as outerProduct,dn as pad,VE as pad1d,GE as pad2d,WE as pad3d,UE as pad4d,ey as pool,pn as pow,Ru as prelu,dx as print,ry as prod,pht as profile,HE as raggedGather,qE as raggedRange,KE as raggedTensorToTensor,jE as rand,hA as randomGamma,kc as randomNormal,gA as randomStandardNormal,Hn as randomUniform,xA as randomUniformInt,da as range,fht as ready,Cl as real,ly as reciprocal,im as registerBackend,tJ as registerCallbackConstructor,k_ as registerGradient,pc as registerKernel,eQ as registerOp,ZR as regularizers,Mr as relu,ym as relu6,hht as removeBackend,R as reshape,hr as reverse,yA as reverse1d,bA as reverse2d,wA as reverse3d,IA as reverse4d,Pu as rfft,bm as round,wm as rsqrt,ft as scalar,z5 as scatterND,Mu as scatter_util,yh as searchSorted,Im as selu,Cm as separableConv2d,QZ as sequential,J as serialization,WK as setBackend,yht as setPlatform,Smt as setThreadsCount,Cmt as setWasmPath,vmt as setWasmPaths,FT as setWebGLContext,CA as setdiff1dAsync,Nw as shared,en as sigmoid,uy as sign,K8 as signal,vm as sin,Sm as sinh,Pt as slice,Nm as slice1d,wh as slice2d,km as slice3d,Tc as slice4d,ze as slice_util,Fu as softmax,pi as softplus,$u as spaceToBatchND,X8 as sparse,G5 as sparseToDense,q8 as spectral,gr as split,Ne as sqrt,Wt as square,_m as squaredDifference,qn as squeeze,qe as stack,To as step,cy as stridedSlice,Y8 as string,lt as sub,pt as sum,xc as sumOutType,py as tan,ia as tanh,sr as tensor,Ke as tensor1d,fi as tensor2d,my as tensor3d,vA as tensor4d,SA as tensor5d,NA as tensor6d,TA as tensorScatterUpdate,So as tensor_util,dA as test_util,B as tidy,Or as tile,mht as time,fy as topk,zc as train,Vt as transpose,Am as truncatedNormal,dy as unique,Kmt as unregisterGradient,qmt as unregisterKernel,Dm as unsortedSegmentSum,xr as unstack,ur as upcastType,_A as upperBound,y as util,z6 as valueAndGrad,B6 as valueAndGrads,hy as variable,Kx as variableGrads,$mt as version,DF as version_converter,B2 as version_core,MO as version_cpu,ef as version_layers,kmt as version_wasm,Gz as version_webgl,JDe as webgl,_d as webgl_util,be as where,xy as whereAsync,Te as zeros,vt as zerosLike};
|
|