chenyc
2025-05-29 92f69c57b920cf62ecc9f15f9ed196fa26dbf2ac
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>'
*/
 
"use strict";var faceapi=(()=>{var ux=Object.defineProperty;var YD=Object.getOwnPropertyDescriptor;var ZD=Object.getOwnPropertyNames;var JD=Object.prototype.hasOwnProperty;var QD=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var Dh=(e,t)=>{for(var n in t)ux(e,n,{get:t[n],enumerable:!0})},eR=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ZD(t))!JD.call(e,r)&&r!==n&&ux(e,r,{get:()=>t[r],enumerable:!(a=YD(t,r))||a.enumerable});return e};var tR=e=>eR(ux({},"__esModule",{value:!0}),e);var ige={};Dh(ige,{AgeGenderNet:()=>Kd,BoundingBox:()=>sl,Box:()=>ot,ComposableTask:()=>Sa,ComputeAllFaceDescriptorsTask:()=>Xr,ComputeFaceDescriptorsTaskBase:()=>Jd,ComputeSingleFaceDescriptorTask:()=>Yr,DetectAllFaceLandmarksTask:()=>eh,DetectAllFacesTask:()=>Up,DetectFaceLandmarksTaskBase:()=>Qd,DetectFacesTaskBase:()=>nh,DetectSingleFaceLandmarksTask:()=>th,DetectSingleFaceTask:()=>ah,Dimensions:()=>wn,FACE_EXPRESSION_LABELS:()=>Ok,FaceDetection:()=>vt,FaceDetectionNet:()=>Gk,FaceExpressionNet:()=>jd,FaceExpressions:()=>qr,FaceLandmark68Net:()=>ml,FaceLandmark68TinyNet:()=>Xd,FaceLandmarkNet:()=>Bk,FaceLandmarks:()=>ia,FaceLandmarks5:()=>Ik,FaceLandmarks68:()=>ol,FaceMatch:()=>Ep,FaceMatcher:()=>rh,FaceRecognitionNet:()=>fl,Gender:()=>vg,LabeledBox:()=>Ap,LabeledFaceDescriptors:()=>vr,NetInput:()=>kr,NeuralNetwork:()=>pn,ObjectDetection:()=>Ur,Point:()=>Re,PredictedBox:()=>Sk,Rect:()=>il,SsdMobilenetv1:()=>Ls,SsdMobilenetv1Options:()=>Ia,TinyFaceDetector:()=>vl,TinyFaceDetectorOptions:()=>Zd,TinyYolov2:()=>yl,TinyYolov2Options:()=>er,allFaces:()=>age,allFacesSsdMobilenetv1:()=>fD,allFacesTinyYolov2:()=>nge,awaitMediaLoaded:()=>Fk,bufferToImage:()=>$k,computeFaceDescriptor:()=>Vfe,createCanvas:()=>cl,createCanvasFromMedia:()=>Ud,createFaceDetectionNet:()=>Mfe,createFaceRecognitionNet:()=>Sfe,createSsdMobilenetv1:()=>eD,createTinyFaceDetector:()=>rge,createTinyYolov2:()=>Lfe,detectAllFaces:()=>Eg,detectFaceLandmarks:()=>hD,detectFaceLandmarksTiny:()=>Bfe,detectLandmarks:()=>ege,detectSingleFace:()=>tge,draw:()=>zk,env:()=>tt,euclideanDistance:()=>jk,extendWithAge:()=>Sg,extendWithFaceDescriptor:()=>Ig,extendWithFaceDetection:()=>ll,extendWithFaceExpressions:()=>gg,extendWithFaceLandmarks:()=>zp,extendWithGender:()=>Ng,extractFaceTensors:()=>Dp,extractFaces:()=>$p,fetchImage:()=>pfe,fetchJson:()=>Mk,fetchNetWeights:()=>cfe,fetchOrThrow:()=>Hr,fetchVideo:()=>dfe,getContext2dOrThrow:()=>Hn,getMediaDimensions:()=>pl,imageTensorToCanvas:()=>Dk,imageToSquare:()=>Rk,inverseSigmoid:()=>afe,iou:()=>xk,isMediaElement:()=>lg,isMediaLoaded:()=>Vd,isWithAge:()=>Nfe,isWithFaceDetection:()=>wr,isWithFaceExpressions:()=>Lk,isWithFaceLandmarks:()=>hl,isWithGender:()=>Tfe,loadAgeGenderModel:()=>Zfe,loadFaceDetectionModel:()=>Jfe,loadFaceExpressionModel:()=>Yfe,loadFaceLandmarkModel:()=>jfe,loadFaceLandmarkTinyModel:()=>Kfe,loadFaceRecognitionModel:()=>Xfe,loadSsdMobilenetv1Model:()=>mD,loadTinyFaceDetectorModel:()=>Hfe,loadTinyYolov2Model:()=>qfe,loadWeightMap:()=>Pk,locateFaces:()=>Qfe,matchDimensions:()=>hfe,minBbox:()=>vk,nets:()=>nt,nonMaxSuppression:()=>wk,normalize:()=>Ja,padToSquare:()=>kk,predictAgeAndGender:()=>Gfe,recognizeFaceExpressions:()=>Ufe,resizeResults:()=>gD,resolveInput:()=>ul,shuffleArray:()=>nfe,sigmoid:()=>zd,ssdMobilenetv1:()=>dD,tf:()=>Oe,tinyFaceDetector:()=>zfe,tinyYolov2:()=>Wfe,toNetInput:()=>wt,utils:()=>yk,validateConfig:()=>Hk,version:()=>sge});var Oe={};Dh(Oe,{Abs:()=>lu,Acos:()=>Ti,Acosh:()=>Ci,AdadeltaOptimizer:()=>Gw,AdagradOptimizer:()=>Hw,AdamOptimizer:()=>qw,AdamaxOptimizer:()=>jw,Add:()=>Is,AddN:()=>_i,All:()=>uu,Any:()=>pu,ArgMax:()=>cu,ArgMin:()=>du,Asin:()=>Ei,Asinh:()=>Ai,Atan:()=>Fi,Atan2:()=>Di,Atanh:()=>$i,AvgPool:()=>Ri,AvgPool3D:()=>hu,AvgPool3DGrad:()=>Lc,AvgPoolGrad:()=>Oc,BackendWasm:()=>E$,BatchMatMul:()=>Mi,BatchToSpaceND:()=>mu,Bincount:()=>fu,BitwiseAnd:()=>gu,BroadcastArgs:()=>zc,BroadcastTo:()=>aN,Callback:()=>DC,CallbackList:()=>M2,Cast:()=>Pi,Ceil:()=>Oi,ClipByValue:()=>Ss,Complex:()=>Om,ComplexAbs:()=>Wc,Concat:()=>bu,Conv2D:()=>Li,Conv2DBackpropFilter:()=>Lm,Conv2DBackpropInput:()=>zi,Conv3D:()=>Wi,Conv3DBackpropFilterV2:()=>yu,Conv3DBackpropInputV2:()=>xu,Cos:()=>Bi,Cosh:()=>Vi,CropAndResize:()=>wu,Cumprod:()=>vu,Cumsum:()=>Ui,CustomCallback:()=>O2,DataStorage:()=>Rm,DenseBincount:()=>Bc,DepthToSpace:()=>ku,DepthwiseConv2dNative:()=>Gi,DepthwiseConv2dNativeBackpropFilter:()=>zm,DepthwiseConv2dNativeBackpropInput:()=>Wm,Diag:()=>Vc,Dilation2D:()=>Hi,Dilation2DBackpropFilter:()=>Ul,Dilation2DBackpropInput:()=>Vl,Draw:()=>Av,ENV:()=>_v,EarlyStopping:()=>RC,Einsum:()=>Bm,Elu:()=>ji,EluGrad:()=>Iu,Environment:()=>tN,Equal:()=>Su,Erf:()=>Ki,Exp:()=>Xi,ExpandDims:()=>Nu,Expm1:()=>Yi,FFT:()=>Vm,Fill:()=>Uc,FlipLeftRight:()=>Tu,Floor:()=>Zi,FloorDiv:()=>Ji,FromPixels:()=>im,FusedBatchNorm:()=>Qi,FusedConv2D:()=>li,FusedDepthwiseConv2D:()=>ui,GPGPUContext:()=>tm,GatherNd:()=>_u,GatherV2:()=>Cu,GraphModel:()=>$1,Greater:()=>Eu,GreaterEqual:()=>eo,History:()=>P2,IFFT:()=>Um,Identity:()=>to,Imag:()=>Gm,InputSpec:()=>Bt,IsFinite:()=>no,IsInf:()=>ao,IsNan:()=>ro,KernelBackend:()=>Mc,LRN:()=>lo,LRNGrad:()=>Pu,LayerVariable:()=>_2,LayersModel:()=>Dr,LeakyRelu:()=>so,Less:()=>Au,LessEqual:()=>Fu,LinSpace:()=>$u,Log:()=>io,Log1p:()=>oo,LogSoftmax:()=>sN,LogicalAnd:()=>Du,LogicalNot:()=>Ru,LogicalOr:()=>Mu,LogicalXor:()=>rN,LowerBound:()=>qR,MathBackendCPU:()=>Yf,MathBackendWebGL:()=>Qf,MatrixBandPart:()=>jR,Max:()=>uo,MaxPool:()=>co,MaxPool3D:()=>Ou,MaxPool3DGrad:()=>Hc,MaxPoolGrad:()=>Gc,MaxPoolWithArgmax:()=>qc,Maximum:()=>po,Mean:()=>ho,Min:()=>mo,Minimum:()=>fo,MirrorPad:()=>go,Mod:()=>bo,MomentumOptimizer:()=>Kw,Multinomial:()=>Lu,Multiply:()=>yo,Neg:()=>zu,NonMaxSuppressionV3:()=>Bu,NonMaxSuppressionV4:()=>Vu,NonMaxSuppressionV5:()=>Uu,NotEqual:()=>Wu,OP_SCOPE_SUFFIX:()=>Dv,OneHot:()=>xo,OnesLike:()=>Gu,Optimizer:()=>zr,OptimizerConstructors:()=>c2,Pack:()=>Hu,PadV2:()=>vo,Pool:()=>KR,Pow:()=>wo,Prelu:()=>ko,Prod:()=>Io,RMSPropOptimizer:()=>Xw,RNN:()=>br,RaggedGather:()=>Hm,RaggedRange:()=>qm,RaggedTensorToTensor:()=>jm,Range:()=>jc,Rank:()=>_x,Real:()=>Km,RealDiv:()=>qi,Reciprocal:()=>So,Reduction:()=>In,Relu:()=>No,Relu6:()=>_o,Reshape:()=>qu,ResizeBilinear:()=>Co,ResizeBilinearGrad:()=>Ku,ResizeNearestNeighbor:()=>To,ResizeNearestNeighborGrad:()=>ju,Reverse:()=>Eo,RotateWithOffset:()=>up,Round:()=>Ao,Rsqrt:()=>Fo,SGDOptimizer:()=>Af,ScatterNd:()=>Xu,SearchSorted:()=>Zu,Select:()=>Ju,Selu:()=>$o,Sequential:()=>tu,Sigmoid:()=>Po,Sign:()=>Mo,Sin:()=>Do,Sinh:()=>Ro,Slice:()=>Qu,Softmax:()=>Wo,Softplus:()=>Oo,SpaceToBatchND:()=>ep,SparseFillEmptyRows:()=>Kc,SparseReshape:()=>np,SparseSegmentMean:()=>Xc,SparseSegmentSum:()=>Yc,SparseToDense:()=>ap,SplitV:()=>tp,Sqrt:()=>Lo,Square:()=>Zc,SquaredDifference:()=>Bo,StaticRegexReplace:()=>Jc,Step:()=>Ts,StridedSlice:()=>rp,StringNGrams:()=>Qc,StringSplit:()=>ed,StringToHashBucketFast:()=>td,Sub:()=>Vo,Sum:()=>zo,SymbolicTensor:()=>Va,Tan:()=>Uo,Tanh:()=>Go,Tensor:()=>Te,TensorBuffer:()=>Vt,TensorScatterUpdate:()=>Yu,Tile:()=>Ns,TopK:()=>sp,Transform:()=>ip,Transpose:()=>$r,Unique:()=>nd,Unpack:()=>op,UnsortedSegmentSum:()=>ad,UpperBound:()=>XR,Variable:()=>hs,ZerosLike:()=>lp,_FusedMatMul:()=>oi,abs:()=>Wt,acos:()=>Lv,acosh:()=>zv,add:()=>X,addN:()=>AN,all:()=>Qm,any:()=>kc,argMax:()=>di,argMin:()=>Wv,asin:()=>Bv,asinh:()=>Vv,atan:()=>Uv,atan2:()=>Gv,atanh:()=>Hv,avgPool:()=>xa,avgPool3d:()=>jv,backend:()=>EN,backend_util:()=>N,basicLSTMCell:()=>RN,batchNorm:()=>_s,batchNorm2d:()=>Kv,batchNorm3d:()=>Xv,batchNorm4d:()=>Yv,batchToSpaceND:()=>pd,bincount:()=>Zv,bitwiseAnd:()=>MN,booleanMaskAsync:()=>NT,broadcastArgs:()=>PN,broadcastTo:()=>ri,broadcast_util:()=>pp,browser:()=>Ko,buffer:()=>ze,callbacks:()=>Dq,cast:()=>se,ceil:()=>Jv,clipByValue:()=>sn,clone:()=>or,complex:()=>Rr,concat:()=>et,concat1d:()=>Qv,concat2d:()=>ew,concat3d:()=>tw,concat4d:()=>nw,constraints:()=>F2,conv1d:()=>ef,conv2d:()=>Rt,conv2dTranspose:()=>tf,conv3d:()=>rw,conv3dTranspose:()=>sw,copyRegisteredKernels:()=>QR,cos:()=>cd,cosh:()=>nf,cosineWindow:()=>Nf,cumprod:()=>Nc,cumsum:()=>af,customGrad:()=>cr,data:()=>a_,denseBincount:()=>dm,deprecationWarn:()=>Ov,depthToSpace:()=>iw,depthwiseConv2d:()=>Es,deregisterOp:()=>Pq,device_util:()=>od,diag:()=>LN,dilation2d:()=>ow,disableDeprecationWarnings:()=>cP,dispose:()=>_e,disposeVariables:()=>dP,div:()=>he,divNoNan:()=>lw,dot:()=>uw,dropout:()=>zw,einsum:()=>WN,elu:()=>cp,enableDebugMode:()=>pP,enableProdMode:()=>uP,enclosingPowerOfTwo:()=>Ww,engine:()=>Aa,ensureShape:()=>BN,env:()=>G,equal:()=>ta,erf:()=>pw,euclideanNorm:()=>hw,exp:()=>yn,expandDims:()=>nn,expm1:()=>mw,eye:()=>rf,fft:()=>vd,fill:()=>xn,findBackend:()=>xP,findBackendFactory:()=>vP,floor:()=>hp,floorDiv:()=>Jm,forceHalfFloat:()=>IA,fused:()=>Zl,gather:()=>mp,gatherND:()=>ET,gather_util:()=>Jw,getBackend:()=>bP,getGradient:()=>Tx,getKernel:()=>om,getKernelsForBackend:()=>lm,getThreadsCount:()=>jme,gpgpu_util:()=>tA,grad:()=>g3,grads:()=>b3,greater:()=>_n,greaterEqual:()=>Or,ifft:()=>Yl,imag:()=>dd,image:()=>ea,inTopKAsync:()=>AT,initializers:()=>$2,input:()=>Z2,io:()=>jt,irfft:()=>xf,isFinite:()=>fw,isInf:()=>gw,isNaN:()=>bw,keep:()=>qt,kernel_impls:()=>gr,layers:()=>D2,leakyRelu:()=>hd,less:()=>ql,lessEqual:()=>As,linalg:()=>Uw,linspace:()=>qN,loadGraphModel:()=>Vj,loadGraphModelSync:()=>Uj,loadLayersModel:()=>EH,localResponseNormalization:()=>yw,log:()=>na,log1p:()=>md,logSigmoid:()=>xw,logSoftmax:()=>of,logSumExp:()=>lf,logicalAnd:()=>Da,logicalNot:()=>fd,logicalOr:()=>uf,logicalXor:()=>vw,losses:()=>VT,lowerBound:()=>KN,matMul:()=>$e,math:()=>JT,max:()=>ga,maxPool:()=>Mt,maxPool3d:()=>ww,maxPoolWithArgmax:()=>XN,maximum:()=>fr,mean:()=>Et,memory:()=>cm,meshgrid:()=>YN,metrics:()=>AC,min:()=>Hl,minimum:()=>fs,mirrorPad:()=>kw,mod:()=>Iw,model:()=>$H,models:()=>FC,moments:()=>gd,movingAverage:()=>TT,mul:()=>z,multiRNNCell:()=>ZN,multinomial:()=>JN,neg:()=>yt,nextFrame:()=>Qw,norm:()=>dp,notEqual:()=>gi,oneHot:()=>jl,ones:()=>Qn,onesLike:()=>aa,op:()=>L,outerProduct:()=>QN,pad:()=>va,pad1d:()=>eT,pad2d:()=>tT,pad3d:()=>nT,pad4d:()=>aT,pool:()=>Sw,pow:()=>Mr,prelu:()=>yd,print:()=>Pv,prod:()=>Nw,profile:()=>hP,raggedGather:()=>rT,raggedRange:()=>sT,raggedTensorToTensor:()=>iT,rand:()=>oT,randomGamma:()=>cT,randomNormal:()=>cf,randomStandardNormal:()=>dT,randomUniform:()=>Fs,randomUniformInt:()=>hT,range:()=>bi,ready:()=>gP,real:()=>Kl,reciprocal:()=>Aw,registerBackend:()=>Zm,registerCallbackConstructor:()=>RH,registerGradient:()=>iN,registerKernel:()=>rd,registerOp:()=>Mq,regularizers:()=>$C,relu:()=>Ke,relu6:()=>df,removeBackend:()=>yP,reshape:()=>W,reverse:()=>ya,reverse1d:()=>mT,reverse2d:()=>fT,reverse3d:()=>gT,reverse4d:()=>bT,rfft:()=>wd,round:()=>hf,rsqrt:()=>mf,scalar:()=>ve,scatterND:()=>CT,scatter_util:()=>wf,searchSorted:()=>pf,selu:()=>ff,separableConv2d:()=>$s,sequential:()=>DH,serialization:()=>ne,setBackend:()=>fP,setPlatform:()=>wP,setThreadsCount:()=>qme,setWasmPath:()=>Gme,setWasmPaths:()=>Hme,setWebGLContext:()=>NE,setdiff1dAsync:()=>yT,shared:()=>P1,sigmoid:()=>fa,sign:()=>Fw,signal:()=>BT,sin:()=>gf,sinh:()=>bf,slice:()=>Ue,slice1d:()=>xd,slice2d:()=>yf,slice3d:()=>qo,slice4d:()=>Xl,slice_util:()=>Xt,softmax:()=>Xa,softplus:()=>Ho,spaceToBatchND:()=>bd,sparse:()=>UT,sparseToDense:()=>_T,spectral:()=>WT,split:()=>zn,sqrt:()=>mn,square:()=>ut,squaredDifference:()=>vf,squeeze:()=>Ds,stack:()=>Dt,step:()=>jo,stridedSlice:()=>$w,string:()=>GT,sub:()=>pe,sum:()=>fe,sumOutType:()=>Ym,tan:()=>Dw,tanh:()=>mi,tensor:()=>bn,tensor1d:()=>je,tensor2d:()=>$a,tensor3d:()=>kd,tensor4d:()=>Ma,tensor5d:()=>xT,tensor6d:()=>vT,tensorScatterUpdate:()=>kT,tensor_util:()=>Ua,test_util:()=>lT,tidy:()=>P,tile:()=>Ln,time:()=>mP,topk:()=>Mw,train:()=>Xs,transpose:()=>De,truncatedNormal:()=>If,unique:()=>Pw,unregisterGradient:()=>JR,unregisterKernel:()=>ZR,unsortedSegmentSum:()=>Sf,unstack:()=>ct,upcastType:()=>ba,upperBound:()=>IT,util:()=>w,valueAndGrad:()=>y3,valueAndGrads:()=>x3,variable:()=>Ow,variableGrads:()=>jN,version:()=>efe,version_converter:()=>Hj,version_core:()=>LB,version_cpu:()=>UK,version_layers:()=>w0,version_wasm:()=>Kme,version_webgl:()=>$Q,webgl:()=>DQ,webgl_util:()=>SE,where:()=>rn,whereAsync:()=>Lw,zeros:()=>Nt,zerosLike:()=>qe});var nR=Object.create,Sv=Object.defineProperty,aR=Object.getOwnPropertyDescriptor,rR=Object.getOwnPropertyNames,sR=Object.getPrototypeOf,iR=Object.prototype.hasOwnProperty,Gt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ee=(e,t)=>{for(var n in t)Sv(e,n,{get:t[n],enumerable:!0})},oR=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of rR(t))!iR.call(e,r)&&r!==n&&Sv(e,r,{get:()=>t[r],enumerable:!(a=aR(t,r))||a.enumerable});return e},ks=(e,t,n)=>(n=e!=null?nR(sR(e)):{},oR(t||!e||!e.__esModule?Sv(n,"default",{value:e,enumerable:!0}):n,e)),lR=Gt((e,t)=>{t.exports=a;var n=null;try{n=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(S){}function a(S,M,B){this.low=S|0,this.high=M|0,this.unsigned=!!B}a.prototype.__isLong__,Object.defineProperty(a.prototype,"__isLong__",{value:!0});function r(S){return(S&&S.__isLong__)===!0}a.isLong=r;var s={},i={};function o(S,M){var B,U,H;return M?(S>>>=0,(H=0<=S&&S<256)&&(U=i[S],U)?U:(B=u(S,(S|0)<0?-1:0,!0),H&&(i[S]=B),B)):(S|=0,(H=-128<=S&&S<128)&&(U=s[S],U)?U:(B=u(S,S<0?-1:0,!1),H&&(s[S]=B),B))}a.fromInt=o;function l(S,M){if(isNaN(S))return M?v:x;if(M){if(S<0)return v;if(S>=g)return F}else{if(S<=-b)return D;if(S+1>=b)return E}return S<0?l(-S,M).neg():u(S%f|0,S/f|0,M)}a.fromNumber=l;function u(S,M,B){return new a(S,M,B)}a.fromBits=u;var p=Math.pow;function d(S,M,B){if(S.length===0)throw Error("empty string");if(S==="NaN"||S==="Infinity"||S==="+Infinity"||S==="-Infinity")return x;if(typeof M=="number"?(B=M,M=!1):M=!!M,B=B||10,B<2||36<B)throw RangeError("radix");var U;if((U=S.indexOf("-"))>0)throw Error("interior hyphen");if(U===0)return d(S.substring(1),M,B).neg();for(var H=l(p(B,8)),j=x,K=0;K<S.length;K+=8){var Z=Math.min(8,S.length-K),J=parseInt(S.substring(K,K+Z),B);if(Z<8){var ee=l(p(B,Z));j=j.mul(ee).add(l(J))}else j=j.mul(H),j=j.add(l(J))}return j.unsigned=M,j}a.fromString=d;function c(S,M){return typeof S=="number"?l(S,M):typeof S=="string"?d(S,M):u(S.low,S.high,typeof M=="boolean"?M:S.unsigned)}a.fromValue=c;var h=65536,m=1<<24,f=h*h,g=f*f,b=g/2,y=o(m),x=o(0);a.ZERO=x;var v=o(0,!0);a.UZERO=v;var I=o(1);a.ONE=I;var T=o(1,!0);a.UONE=T;var C=o(-1);a.NEG_ONE=C;var E=u(-1,2147483647,!1);a.MAX_VALUE=E;var F=u(-1,-1,!0);a.MAX_UNSIGNED_VALUE=F;var D=u(0,-2147483648,!1);a.MIN_VALUE=D;var $=a.prototype;$.toInt=function(){return this.unsigned?this.low>>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},$.toString=function(S){if(S=S||10,S<2||36<S)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(D)){var M=l(S),B=this.div(M),U=B.mul(M).sub(this);return B.toString(S)+U.toInt().toString(S)}else return"-"+this.neg().toString(S);for(var H=l(p(S,6),this.unsigned),j=this,K="";;){var Z=j.div(H),J=j.sub(Z.mul(H)).toInt()>>>0,ee=J.toString(S);if(j=Z,j.isZero())return ee+K;for(;ee.length<6;)ee="0"+ee;K=""+ee+K}},$.getHighBits=function(){return this.high},$.getHighBitsUnsigned=function(){return this.high>>>0},$.getLowBits=function(){return this.low},$.getLowBitsUnsigned=function(){return this.low>>>0},$.getNumBitsAbs=function(){if(this.isNegative())return this.eq(D)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,M=31;M>0&&!(S&1<<M);M--);return this.high!=0?M+33:M+1},$.isZero=function(){return this.high===0&&this.low===0},$.eqz=$.isZero,$.isNegative=function(){return!this.unsigned&&this.high<0},$.isPositive=function(){return this.unsigned||this.high>=0},$.isOdd=function(){return(this.low&1)===1},$.isEven=function(){return(this.low&1)===0},$.equals=function(S){return r(S)||(S=c(S)),this.unsigned!==S.unsigned&&this.high>>>31===1&&S.high>>>31===1?!1:this.high===S.high&&this.low===S.low},$.eq=$.equals,$.notEquals=function(S){return!this.eq(S)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(S){return this.comp(S)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(S){return this.comp(S)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(S){return this.comp(S)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(S){return this.comp(S)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(S){if(r(S)||(S=c(S)),this.eq(S))return 0;var M=this.isNegative(),B=S.isNegative();return M&&!B?-1:!M&&B?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(D)?D:this.not().add(I)},$.neg=$.negate,$.add=function(S){r(S)||(S=c(S));var M=this.high>>>16,B=this.high&65535,U=this.low>>>16,H=this.low&65535,j=S.high>>>16,K=S.high&65535,Z=S.low>>>16,J=S.low&65535,ee=0,ae=0,te=0,re=0;return re+=H+J,te+=re>>>16,re&=65535,te+=U+Z,ae+=te>>>16,te&=65535,ae+=B+K,ee+=ae>>>16,ae&=65535,ee+=M+j,ee&=65535,u(te<<16|re,ee<<16|ae,this.unsigned)},$.subtract=function(S){return r(S)||(S=c(S)),this.add(S.neg())},$.sub=$.subtract,$.multiply=function(S){if(this.isZero())return x;if(r(S)||(S=c(S)),n){var M=n.mul(this.low,this.high,S.low,S.high);return u(M,n.get_high(),this.unsigned)}if(S.isZero())return x;if(this.eq(D))return S.isOdd()?D:x;if(S.eq(D))return this.isOdd()?D:x;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(y)&&S.lt(y))return l(this.toNumber()*S.toNumber(),this.unsigned);var B=this.high>>>16,U=this.high&65535,H=this.low>>>16,j=this.low&65535,K=S.high>>>16,Z=S.high&65535,J=S.low>>>16,ee=S.low&65535,ae=0,te=0,re=0,ie=0;return ie+=j*ee,re+=ie>>>16,ie&=65535,re+=H*ee,te+=re>>>16,re&=65535,re+=j*J,te+=re>>>16,re&=65535,te+=U*ee,ae+=te>>>16,te&=65535,te+=H*J,ae+=te>>>16,te&=65535,te+=j*Z,ae+=te>>>16,te&=65535,ae+=B*ee+U*J+H*Z+j*K,ae&=65535,u(re<<16|ie,ae<<16|te,this.unsigned)},$.mul=$.multiply,$.divide=function(S){if(r(S)||(S=c(S)),S.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var M=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,S.low,S.high);return u(M,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?v:x;var B,U,H;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return v;if(S.gt(this.shru(1)))return T;H=v}else{if(this.eq(D)){if(S.eq(I)||S.eq(C))return D;if(S.eq(D))return I;var j=this.shr(1);return B=j.div(S).shl(1),B.eq(x)?S.isNegative()?I:C:(U=this.sub(S.mul(B)),H=B.add(U.div(S)),H)}else if(S.eq(D))return this.unsigned?v:x;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();H=x}for(U=this;U.gte(S);){B=Math.max(1,Math.floor(U.toNumber()/S.toNumber()));for(var K=Math.ceil(Math.log(B)/Math.LN2),Z=K<=48?1:p(2,K-48),J=l(B),ee=J.mul(S);ee.isNegative()||ee.gt(U);)B-=Z,J=l(B,this.unsigned),ee=J.mul(S);J.isZero()&&(J=I),H=H.add(J),U=U.sub(ee)}return H},$.div=$.divide,$.modulo=function(S){if(r(S)||(S=c(S)),n){var M=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,S.low,S.high);return u(M,n.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return u(~this.low,~this.high,this.unsigned)},$.and=function(S){return r(S)||(S=c(S)),u(this.low&S.low,this.high&S.high,this.unsigned)},$.or=function(S){return r(S)||(S=c(S)),u(this.low|S.low,this.high|S.high,this.unsigned)},$.xor=function(S){return r(S)||(S=c(S)),u(this.low^S.low,this.high^S.high,this.unsigned)},$.shiftLeft=function(S){return r(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low<<S,this.high<<S|this.low>>>32-S,this.unsigned):u(0,this.low<<S-32,this.unsigned)},$.shl=$.shiftLeft,$.shiftRight=function(S){return r(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low>>>S|this.high<<32-S,this.high>>S,this.unsigned):u(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(S){if(r(S)&&(S=S.toInt()),S&=63,S===0)return this;var M=this.high;if(S<32){var B=this.low;return u(B>>>S|M<<32-S,M>>>S,this.unsigned)}else return S===32?u(M,0,this.unsigned):u(M>>>S-32,0,this.unsigned)},$.shru=$.shiftRightUnsigned,$.shr_u=$.shiftRightUnsigned,$.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},$.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},$.toBytes=function(S){return S?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var S=this.high,M=this.low;return[M&255,M>>>8&255,M>>>16&255,M>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},$.toBytesBE=function(){var S=this.high,M=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,M>>>24,M>>>16&255,M>>>8&255,M&255]},a.fromBytes=function(S,M,B){return B?a.fromBytesLE(S,M):a.fromBytesBE(S,M)},a.fromBytesLE=function(S,M){return new a(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,M)},a.fromBytesBE=function(S,M){return new a(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],M)}}),uR=Gt(()=>{}),pR=Gt(()=>{}),cR=Gt((e,t)=>{(function(n,a,r){function s(u){var p=this,d=l();p.next=function(){var c=2091639*p.s0+p.c*23283064365386963e-26;return p.s0=p.s1,p.s1=p.s2,p.s2=c-(p.c=c|0)},p.c=1,p.s0=d(" "),p.s1=d(" "),p.s2=d(" "),p.s0-=d(u),p.s0<0&&(p.s0+=1),p.s1-=d(u),p.s1<0&&(p.s1+=1),p.s2-=d(u),p.s2<0&&(p.s2+=1),d=null}function i(u,p){return p.c=u.c,p.s0=u.s0,p.s1=u.s1,p.s2=u.s2,p}function o(u,p){var d=new s(u),c=p&&p.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,c&&(typeof c=="object"&&i(c,d),h.state=function(){return i(d,{})}),h}function l(){var u=4022871197,p=function(d){d=String(d);for(var c=0;c<d.length;c++){u+=d.charCodeAt(c);var h=.02519603282416938*u;u=h>>>0,h-=u,h*=u,u=h>>>0,h-=u,u+=h*4294967296}return(u>>>0)*23283064365386963e-26};return p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),dR=Gt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var c=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^c^c>>>8},l===(l|0)?u.x=l:p+=l;for(var d=0;d<p.length+64;d++)u.x^=p.charCodeAt(d)|0,u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u}function o(l,u){var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),hR=Gt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.next=function(){var c=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(c^c<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:p+=l;for(var d=0;d<p.length+64;d++)u.x^=p.charCodeAt(d)|0,d==p.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),mR=Gt((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var d=u.x,c=u.i,h,m,f;return h=d[c],h^=h>>>7,m=h^h<<24,h=d[c+1&7],m^=h^h>>>10,h=d[c+3&7],m^=h^h>>>3,h=d[c+4&7],m^=h^h<<7,h=d[c+7&7],h=h^h<<13,m^=h^h<<9,d[c]=m,u.i=c+1&7,m};function p(d,c){var h,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,h=0;h<c.length;++h)f[h&7]=f[h&7]<<15^c.charCodeAt(h)+f[h+1&7]<<13;for(;f.length<8;)f.push(0);for(h=0;h<8&&f[h]===0;++h);for(h==8?m=f[7]=-1:m=f[h],d.x=f,d.i=0,h=256;h>0;--h)d.next()}p(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(d.x&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),fR=Gt((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var d=u.w,c=u.X,h=u.i,m,f;return u.w=d=d+1640531527|0,f=c[h+34&127],m=c[h=h+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[h]=f^m,u.i=h,f+(d^d>>>16)|0};function p(d,c){var h,m,f,g,b,y=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,g=-32;g<x;++g)c&&(m^=c.charCodeAt((g+32)%c.length)),g===0&&(b=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,g>=0&&(b=b+1640531527|0,h=y[g&127]^=m+b,f=h==0?f+1:0);for(f>=128&&(y[(c&&c.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=y[f+34&127],h=y[f=f+1&127],m^=m<<13,h^=h<<17,m^=m>>>15,h^=h>>>12,y[f]=m^h;d.w=b,d.X=y,d.i=f}p(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(d.X&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),gR=Gt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.next=function(){var c=u.b,h=u.c,m=u.d,f=u.a;return c=c<<25^c>>>7^h,h=h-m|0,m=m<<24^m>>>8^f,f=f-c|0,u.b=c=c<<20^c>>>12^h,u.c=h=h-m|0,u.d=m<<16^h>>>16^f,u.a=f-c|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):p+=l;for(var d=0;d<p.length+20;d++)u.b^=p.charCodeAt(d)|0,u.next()}function i(l,u){return u.a=l.a,u.b=l.b,u.c=l.c,u.d=l.d,u}function o(l,u){var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),bR=Gt(()=>{}),yR=Gt((e,t)=>{(function(n,a,r){var s=256,i=6,o=52,l="random",u=r.pow(s,i),p=r.pow(2,o),d=p*2,c=s-1,h;function m(I,T,C){var E=[];T=T==!0?{entropy:!0}:T||{};var F=y(b(T.entropy?[I,v(a)]:I==null?x():I,3),E),D=new f(E),$=function(){for(var S=D.g(i),M=u,B=0;S<p;)S=(S+B)*s,M*=s,B=D.g(1);for(;S>=d;)S/=2,M/=2,B>>>=1;return(S+B)/M};return $.int32=function(){return D.g(4)|0},$.quick=function(){return D.g(4)/4294967296},$.double=$,y(v(D.S),a),(T.pass||C||function(S,M,B,U){return U&&(U.S&&g(U,D),S.state=function(){return g(D,{})}),B?(r[l]=S,M):S})($,F,"global"in T?T.global:this==r,T.state)}function f(I){var T,C=I.length,E=this,F=0,D=E.i=E.j=0,$=E.S=[];for(C||(I=[C++]);F<s;)$[F]=F++;for(F=0;F<s;F++)$[F]=$[D=c&D+I[F%C]+(T=$[F])],$[D]=T;(E.g=function(S){for(var M,B=0,U=E.i,H=E.j,j=E.S;S--;)M=j[U=c&U+1],B=B*s+j[c&(j[U]=j[H=c&H+M])+(j[H]=M)];return E.i=U,E.j=H,B})(s)}function g(I,T){return T.i=I.i,T.j=I.j,T.S=I.S.slice(),T}function b(I,T){var C=[],E=typeof I,F;if(T&&E=="object")for(F in I)try{C.push(b(I[F],T-1))}catch(D){}return C.length?C:E=="string"?I:I+"\0"}function y(I,T){for(var C=I+"",E,F=0;F<C.length;)T[c&F]=c&(E^=T[c&F]*19)+C.charCodeAt(F++);return v(T)}function x(){try{var I;return h&&(I=h.randomBytes)?I=I(s):(I=new Uint8Array(s),(n.crypto||n.msCrypto).getRandomValues(I)),v(I)}catch(E){var T=n.navigator,C=T&&T.plugins;return[+new Date,n,C,n.screen,v(a)]}}function v(I){return String.fromCharCode.apply(0,I)}if(y(r.random(),a),typeof t=="object"&&t.exports){t.exports=m;try{h=bR()}catch(I){}}else typeof define=="function"&&define.amd?define(function(){return m}):r["seed"+l]=m})(typeof self!="undefined"?self:e,[],Math)}),Dm=Gt((e,t)=>{var n=cR(),a=dR(),r=hR(),s=mR(),i=fR(),o=gR(),l=yR();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),US=Gt(()=>{}),Nv=Gt(()=>{}),GS=Gt(()=>{}),xR=Gt(()=>{}),vR=Gt(()=>{}),wR=Gt(()=>{}),kR=Gt((e,t)=>{var n=(()=>{var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};function s(){return ue.buffer!=Me&&lt(ue.buffer),ft}function i(){return ue.buffer!=Me&&lt(ue.buffer),jn}function o(){return ue.buffer!=Me&&lt(ue.buffer),Lt}function l(){return ue.buffer!=Me&&lt(ue.buffer),cn}function u(){return ue.buffer!=Me&&lt(ue.buffer),$n}function p(){return ue.buffer!=Me&&lt(ue.buffer),ua}function d(){return ue.buffer!=Me&&lt(ue.buffer),Dn}var c=typeof r!="undefined"?r:{},h,m;c.ready=new Promise(function(R,q){h=R,m=q});var f;typeof process!="undefined"&&process.listeners&&(f={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},c),b=[],y="./this.program",x=(R,q)=>{throw q},v=typeof window=="object",I=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=c.ENVIRONMENT_IS_PTHREAD||!1,E="";function F(R){return c.locateFile?c.locateFile(R,E):E+R}var D,$,S,M;function B(R){R instanceof Gs||J("exiting due to exception: "+R)}if(T){var U=Nv(),H=GS();I?E=H.dirname(E)+"/":E=__dirname+"/",D=(q,le)=>(q=Cl(q)?new URL(q):H.normalize(q),U.readFileSync(q,le?void 0:"utf8")),S=q=>{var le=D(q,!0);return le.buffer||(le=new Uint8Array(le)),le},$=(q,le,Ne)=>{q=Cl(q)?new URL(q):H.normalize(q),U.readFile(q,function(Pe,Fe){Pe?Ne(Pe):le(Fe.buffer)})},process.argv.length>1&&(y=process.argv[1].replace(/\\/g,"/")),b=process.argv.slice(2),process.on("uncaughtException",function(q){if(!(q instanceof Gs))throw q}),process.on("unhandledRejection",function(q){throw q}),x=(q,le)=>{if(Na())throw process.exitCode=q,le;B(le),process.exit(q)},c.inspect=function(){return"[Emscripten Module object]"};let R;try{R=xR()}catch(q){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),q}global.Worker=R.Worker}else(v||I)&&(I?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof a!="undefined"&&a&&(E=a),E.indexOf("blob:")!==0?E=E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):E="",T||(D=R=>{var q=new XMLHttpRequest;return q.open("GET",R,!1),q.send(null),q.responseText},I&&(S=R=>{var q=new XMLHttpRequest;return q.open("GET",R,!1),q.responseType="arraybuffer",q.send(null),new Uint8Array(q.response)}),$=(R,q,le)=>{var Ne=new XMLHttpRequest;Ne.open("GET",R,!0),Ne.responseType="arraybuffer",Ne.onload=()=>{if(Ne.status==200||Ne.status==0&&Ne.response){q(Ne.response);return}le()},Ne.onerror=le,Ne.send(null)}),M=R=>document.title=R);T&&typeof performance=="undefined"&&(global.performance=vR().performance);var j=console.log.bind(console),K=console.warn.bind(console);T&&(j=R=>U.writeSync(1,R+`
`),K=R=>U.writeSync(2,R+`
`));var Z=c.print||j,J=c.printErr||K;Object.assign(c,g),g=null,c.arguments&&(b=c.arguments),c.thisProgram&&(y=c.thisProgram),c.quit&&(x=c.quit);var ee=4,ae=Atomics.load,te=Atomics.store,re=Atomics.compareExchange,ie;c.wasmBinary&&(ie=c.wasmBinary);var ye=c.noExitRuntime||!0;typeof WebAssembly!="object"&&Us("no native wasm support detected");var ue,be,ke=!1,Se;function We(R,q){R||Us(q)}var Ge=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function ht(R,q,le){q>>>=0;for(var Ne=q+le,Pe=q;R[Pe]&&!(Pe>=Ne);)++Pe;if(Pe-q>16&&R.buffer&&Ge)return Ge.decode(R.buffer instanceof SharedArrayBuffer?R.slice(q,Pe):R.subarray(q,Pe));for(var Fe="";q<Pe;){var me=R[q++];if(!(me&128)){Fe+=String.fromCharCode(me);continue}var we=R[q++]&63;if((me&224)==192){Fe+=String.fromCharCode((me&31)<<6|we);continue}var _t=R[q++]&63;if((me&240)==224?me=(me&15)<<12|we<<6|_t:me=(me&7)<<18|we<<12|_t<<6|R[q++]&63,me<65536)Fe+=String.fromCharCode(me);else{var ca=me-65536;Fe+=String.fromCharCode(55296|ca>>10,56320|ca&1023)}}return Fe}function st(R,q){return R>>>=0,R?ht(i(),R,q):""}function at(R,q,le,Ne){if(le>>>=0,!(Ne>0))return 0;for(var Pe=le,Fe=le+Ne-1,me=0;me<R.length;++me){var we=R.charCodeAt(me);if(we>=55296&&we<=57343){var _t=R.charCodeAt(++me);we=65536+((we&1023)<<10)|_t&1023}if(we<=127){if(le>=Fe)break;q[le++>>>0]=we}else if(we<=2047){if(le+1>=Fe)break;q[le++>>>0]=192|we>>6,q[le++>>>0]=128|we&63}else if(we<=65535){if(le+2>=Fe)break;q[le++>>>0]=224|we>>12,q[le++>>>0]=128|we>>6&63,q[le++>>>0]=128|we&63}else{if(le+3>=Fe)break;q[le++>>>0]=240|we>>18,q[le++>>>0]=128|we>>12&63,q[le++>>>0]=128|we>>6&63,q[le++>>>0]=128|we&63}}return q[le>>>0]=0,le-Pe}function rt(R,q,le){return at(R,i(),q,le)}var Me,ft,jn,Lt,la,cn,$n,ua,Dn;C&&(Me=c.buffer);function lt(R){Me=R,c.HEAP8=ft=new Int8Array(R),c.HEAP16=Lt=new Int16Array(R),c.HEAP32=cn=new Int32Array(R),c.HEAPU8=jn=new Uint8Array(R),c.HEAPU16=la=new Uint16Array(R),c.HEAPU32=$n=new Uint32Array(R),c.HEAPF32=ua=new Float32Array(R),c.HEAPF64=Dn=new Float64Array(R)}var Rn=c.INITIAL_MEMORY||16777216;if(C)ue=c.wasmMemory,Me=c.buffer;else if(c.wasmMemory)ue=c.wasmMemory;else if(ue=new WebAssembly.Memory({initial:Rn/65536,maximum:65536,shared:!0}),!(ue.buffer instanceof SharedArrayBuffer))throw J("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"),T&&J("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");ue&&(Me=ue.buffer),Rn=Me.byteLength,lt(Me);var Kn,Ir=[],Nl=[],tr=[],Gp=!1;function Na(){return ye}function Zr(){if(c.preRun)for(typeof c.preRun=="function"&&(c.preRun=[c.preRun]);c.preRun.length;)Ag(c.preRun.shift());qp(Ir)}function Qt(){Gp=!0,!C&&qp(Nl)}function sh(){if(!C){if(c.postRun)for(typeof c.postRun=="function"&&(c.postRun=[c.postRun]);c.postRun.length;)Kk(c.postRun.shift());qp(tr)}}function Ag(R){Ir.unshift(R)}function Fg(R){Nl.unshift(R)}function Kk(R){tr.unshift(R)}var Jr=0,Tl=null,Sr=null;function $g(R){Jr++,c.monitorRunDependencies&&c.monitorRunDependencies(Jr)}function ih(R){if(Jr--,c.monitorRunDependencies&&c.monitorRunDependencies(Jr),Jr==0&&(Tl!==null&&(clearInterval(Tl),Tl=null),Sr)){var q=Sr;Sr=null,q()}}function Us(R){c.onAbort&&c.onAbort(R),R="Aborted("+R+")",J(R),ke=!0,Se=1,R+=". Build with -sASSERTIONS for more info.";var q=new WebAssembly.RuntimeError(R);throw m(q),q}var Dg="data:application/octet-stream;base64,";function oh(R){return R.startsWith(Dg)}function Cl(R){return R.startsWith("file://")}var gn;gn="tfjs-backend-wasm-threaded-simd.wasm",oh(gn)||(gn=F(gn));function lh(R){try{if(R==gn&&ie)return new Uint8Array(ie);if(S)return S(R);throw"both async and sync fetching of the wasm failed"}catch(q){Us(q)}}function Rg(){if(!ie&&(v||I)){if(typeof fetch=="function"&&!Cl(gn))return fetch(gn,{credentials:"same-origin"}).then(function(R){if(!R.ok)throw"failed to load wasm binary file at '"+gn+"'";return R.arrayBuffer()}).catch(function(){return lh(gn)});if($)return new Promise(function(R,q){$(gn,function(le){R(new Uint8Array(le))},q)})}return Promise.resolve().then(function(){return lh(gn)})}function Mg(){var R={env:wh,wasi_snapshot_preview1:wh};function q(me,we){var _t=me.exports;if(c.asm=_t,Gg(c.asm._emscripten_tls_init),Kn=c.asm.__indirect_function_table,Fg(c.asm.__wasm_call_ctors),be=we,!C){var ca=Ae.unusedWorkers.length;Ae.unusedWorkers.forEach(function(Tr){Ae.loadWasmModuleToWorker(Tr,function(){--ca||ih("wasm-instantiate")})})}}C||$g("wasm-instantiate");function le(me){q(me.instance,me.module)}function Ne(me){return Rg().then(function(we){return WebAssembly.instantiate(we,R)}).then(function(we){return we}).then(me,function(we){J("failed to asynchronously prepare wasm: "+we),Us(we)})}function Pe(){return!ie&&typeof WebAssembly.instantiateStreaming=="function"&&!oh(gn)&&!Cl(gn)&&!T&&typeof fetch=="function"?fetch(gn,{credentials:"same-origin"}).then(function(me){var we=WebAssembly.instantiateStreaming(me,R);return we.then(le,function(_t){return J("wasm streaming compile failed: "+_t),J("falling back to ArrayBuffer instantiation"),Ne(le)})}):Ne(le)}if(c.instantiateWasm)try{var Fe=c.instantiateWasm(R,q);return Fe}catch(me){J("Module.instantiateWasm callback failed with error: "+me),m(me)}return Pe().catch(m),{}}var Xk,Yk,uh={};function Gs(R){this.name="ExitStatus",this.message="Program terminated with exit("+R+")",this.status=R}function Pg(R){var q=Ae.pthreads[R];delete Ae.pthreads[R],q.terminate(),ix(R),Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(q),1),q.pthread_ptr=0}function Og(R){var q=Ae.pthreads[R];q.postMessage({cmd:"cancel"})}function Hp(R){var q=Ae.pthreads[R];We(q),Ae.returnWorkerToPool(q)}function Lg(R){var q=Ae.getNewWorker();if(!q)return 6;Ae.runningWorkers.push(q),Ae.pthreads[R.pthread_ptr]=q,q.pthread_ptr=R.pthread_ptr;var le={cmd:"run",start_routine:R.startRoutine,arg:R.arg,pthread_ptr:R.pthread_ptr};return q.runPthread=()=>{T&&q.ref(),q.postMessage(le,R.transferList),delete q.runPthread},q.loaded&&q.runPthread(),0}var ph={varargs:void 0,get:function(){ph.varargs+=4;var R=l()[ph.varargs-4>>>2];return R},getStr:function(R){var q=st(R);return q}};function ch(R){if(C)return Qr(1,1,R);Se=R,Na()||(Ae.terminateAllThreads(),c.onExit&&c.onExit(R),ke=!0),x(R,new Gs(R))}function zg(R,q){if(Se=R,!q&&C)throw hh(R),"unwind";ch(R)}var dh=zg;function Wg(R){if(R instanceof Gs||R=="unwind")return Se;x(1,R)}var Ae={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){C?Ae.initWorker():Ae.initMainThread()},initMainThread:function(){for(var R=8;R--;)Ae.allocateUnusedWorker()},initWorker:function(){ye=!1},setExitStatus:function(R){Se=R},terminateAllThreads:function(){for(var R of Object.values(Ae.pthreads))Ae.returnWorkerToPool(R);for(var R of Ae.unusedWorkers)R.terminate();Ae.unusedWorkers=[]},returnWorkerToPool:function(R){var q=R.pthread_ptr;delete Ae.pthreads[q],Ae.unusedWorkers.push(R),Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(R),1),R.pthread_ptr=0,T&&R.unref(),ix(q)},receiveObjectTransfer:function(R){},threadInitTLS:function(){Ae.tlsInitFunctions.forEach(R=>R())},loadWasmModuleToWorker:function(R,q){R.onmessage=Fe=>{var me=Fe.data,we=me.cmd;if(R.pthread_ptr&&(Ae.currentProxiedOperationCallerThread=R.pthread_ptr),me.targetThread&&me.targetThread!=Ch()){var _t=Ae.pthreads[me.targetThread];_t?_t.postMessage(me,me.transferList):J('Internal error! Worker sent a message "'+we+'" to target pthread '+me.targetThread+", but that thread no longer exists!"),Ae.currentProxiedOperationCallerThread=void 0;return}we==="processProxyingQueue"?jp(me.queue):we==="spawnThread"?Lg(me):we==="cleanupThread"?Hp(me.thread):we==="killThread"?Pg(me.thread):we==="cancelThread"?Og(me.thread):we==="loaded"?(R.loaded=!0,T&&R.unref(),q&&q(R),R.runPthread&&R.runPthread()):we==="print"?Z("Thread "+me.threadId+": "+me.text):we==="printErr"?J("Thread "+me.threadId+": "+me.text):we==="alert"?alert("Thread "+me.threadId+": "+me.text):me.target==="setimmediate"?R.postMessage(me):we==="callHandler"?c[me.handler](...me.args):we&&J("worker sent an unknown command "+we),Ae.currentProxiedOperationCallerThread=void 0},R.onerror=Fe=>{var me="worker sent an error!";throw J(me+" "+Fe.filename+":"+Fe.lineno+": "+Fe.message),Fe},T&&(R.on("message",function(Fe){R.onmessage({data:Fe})}),R.on("error",function(Fe){R.onerror(Fe)}),R.on("detachedExit",function(){}));var le=[],Ne=["onExit","onAbort","print","printErr"];for(var Pe of Ne)c.hasOwnProperty(Pe)&&le.push(Pe);R.postMessage({cmd:"load",handlers:le,urlOrBlob:c.mainScriptUrlOrBlob||a,wasmMemory:ue,wasmModule:be})},allocateUnusedWorker:function(){var R,q=F("tfjs-backend-wasm-threaded-simd.worker.js");R=new Worker(q),Ae.unusedWorkers.push(R)},getNewWorker:function(){return Ae.unusedWorkers.length==0&&(Ae.allocateUnusedWorker(),Ae.loadWasmModuleToWorker(Ae.unusedWorkers[0])),Ae.unusedWorkers.pop()}};c.PThread=Ae;function qp(R){for(;R.length>0;)R.shift()(c)}function Bg(){var R=Ch(),q=l()[R+52>>>2],le=l()[R+56>>>2],Ne=q-le;nI(q,Ne),_h(q)}c.establishStackSpace=Bg;function hh(R){if(C)return Qr(2,0,R);try{dh(R)}catch(q){Wg(q)}}var _l=[];function Vg(R){var q=_l[R];return q||(R>=_l.length&&(_l.length=R+1),_l[R]=q=Kn.get(R)),q}function Ug(R,q){var le=Vg(R)(q);Na()?Ae.setExitStatus(le):tI(le)}c.invokeEntryPoint=Ug;function Gg(R){Ae.tlsInitFunctions.push(R)}function Hg(R){Jk(R,!I,1,!v),Ae.threadInitTLS()}function qg(R){C?postMessage({cmd:"cleanupThread",thread:R}):Hp(R)}function mh(R,q,le,Ne){return C?Qr(3,1,R,q,le,Ne):fh(R,q,le,Ne)}function fh(R,q,le,Ne){if(typeof SharedArrayBuffer=="undefined")return J("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Pe=[],Fe=0;if(C&&(Pe.length===0||Fe))return mh(R,q,le,Ne);if(Fe)return Fe;var me={startRoutine:le,pthread_ptr:R,arg:Ne,transferList:Pe};return C?(me.cmd="spawnThread",postMessage(me,Pe),0):Lg(me)}function jg(){return 65536}var Kg=!0;function Xg(){return Kg}function jp(R){Atomics.store(l(),R>>2,1),Ch()&&eI(R),Atomics.compareExchange(l(),R>>2,1,0)}c.executeNotifiedProxyingQueue=jp;function Yg(R,q,le,Ne){if(R==q)setTimeout(()=>jp(Ne));else if(C)postMessage({targetThread:R,cmd:"processProxyingQueue",queue:Ne});else{var Pe=Ae.pthreads[R];if(!Pe)return;Pe.postMessage({cmd:"processProxyingQueue",queue:Ne})}return 1}function Zg(R,q,le){return-1}function Jg(){Us("")}function Hs(R){Hs.shown||(Hs.shown={}),Hs.shown[R]||(Hs.shown[R]=1,T&&(R="warning: "+R),J(R))}function Qg(){T||I||Hs("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function eb(){return Date.now()}function gh(){return 4294901760}function tb(){return gh()}var Kp;T?Kp=()=>{var R=process.hrtime();return R[0]*1e3+R[1]/1e6}:Kp=()=>performance.timeOrigin+performance.now();function nb(R,q,le){i().copyWithin(R>>>0,q>>>0,q+le>>>0)}function ab(){return T?wR().cpus().length:navigator.hardwareConcurrency}function rb(R){var q=ox(),le=R();return _h(q),le}function Qr(R,q){var le=arguments.length-2,Ne=arguments;return rb(()=>{for(var Pe=le,Fe=Eh(Pe*8),me=Fe>>3,we=0;we<le;we++){var _t=Ne[2+we];d()[me+we>>>0]=_t}return Qk(R,Pe,Fe,q)})}var Xp=[];function sb(R,q,le){Xp.length=q;for(var Ne=le>>3,Pe=0;Pe<q;Pe++)Xp[Pe]=d()[Ne+Pe>>>0];var Fe=R<0,me=Fe?uh[-R-1]:mb[R];return me.apply(null,Xp)}function ib(R){try{return ue.grow(R-Me.byteLength+65535>>>16),lt(ue.buffer),1}catch(q){}}function ob(R){var q=i().length;if(R=R>>>0,R<=q)return!1;var le=gh();if(R>le)return!1;let Ne=(_t,ca)=>_t+(ca-_t%ca)%ca;for(var Pe=1;Pe<=4;Pe*=2){var Fe=q*(1+.2/Pe);Fe=Math.min(Fe,R+100663296);var me=Math.min(le,Ne(Math.max(R,Fe),65536)),we=ib(me);if(we)return!0}return!1}function lb(){throw"unwind"}function bh(R){return C?Qr(4,1,R):52}function yh(R,q,le,Ne,Pe){return C?Qr(5,1,R,q,le,Ne,Pe):70}var ub=[null,[],[]];function pb(R,q){var le=ub[R];q===0||q===10?((R===1?Z:J)(ht(le,0)),le.length=0):le.push(q)}function xh(R,q,le,Ne){if(C)return Qr(6,1,R,q,le,Ne);for(var Pe=0,Fe=0;Fe<le;Fe++){var me=u()[q>>>2],we=u()[q+4>>>2];q+=8;for(var _t=0;_t<we;_t++)pb(R,i()[me+_t>>>0]);Pe+=we}return u()[Ne>>>2]=Pe,0}function vh(R){var q=c["_"+R];return q}function cb(R,q){s().set(R,q>>>0)}function db(R,q,le,Ne,Pe){var Fe={string:da=>{var $l=0;if(da!=null&&da!==0){var sI=(da.length<<2)+1;$l=Eh(sI),rt(da,$l,sI)}return $l},array:da=>{var $l=Eh(da.length);return cb(da,$l),$l}};function me(da){return q==="string"?st(da):q==="boolean"?!!da:da}var we=vh(R),_t=[],ca=0;if(Ne)for(var Tr=0;Tr<Ne.length;Tr++){var rI=Fe[le[Tr]];rI?(ca===0&&(ca=ox()),_t[Tr]=rI(Ne[Tr])):_t[Tr]=Ne[Tr]}var lx=we.apply(null,_t);function XD(da){return ca!==0&&_h(ca),me(da)}return lx=XD(lx),lx}function hb(R,q,le,Ne){le=le||[];var Pe=le.every(me=>me==="number"||me==="boolean"),Fe=q!=="string";return Fe&&Pe&&!Ne?vh(R):function(){return db(R,q,le,arguments,Ne)}}Ae.init();var mb=[null,ch,hh,mh,bh,yh,xh],wh={__emscripten_init_main_thread_js:Hg,__emscripten_thread_cleanup:qg,__pthread_create_js:fh,_emscripten_default_pthread_stack_size:jg,_emscripten_get_now_is_monotonic:Xg,_emscripten_notify_task_queue:Yg,_emscripten_set_offscreencanvas_size:Zg,abort:Jg,emscripten_check_blocking_allowed:Qg,emscripten_date_now:eb,emscripten_get_heap_max:tb,emscripten_get_now:Kp,emscripten_memcpy_big:nb,emscripten_num_logical_cores:ab,emscripten_receive_on_main_thread_js:sb,emscripten_resize_heap:ob,emscripten_unwind_to_js_event_loop:lb,exit:dh,fd_close:bh,fd_seek:yh,fd_write:xh,memory:ue||c.wasmMemory},Zk=Mg(),fb=c.___wasm_call_ctors=function(){return(fb=c.___wasm_call_ctors=c.asm.__wasm_call_ctors).apply(null,arguments)},gb=c._init=function(){return(gb=c._init=c.asm.init).apply(null,arguments)},bb=c._init_with_threads_count=function(){return(bb=c._init_with_threads_count=c.asm.init_with_threads_count).apply(null,arguments)},yb=c._get_threads_count=function(){return(yb=c._get_threads_count=c.asm.get_threads_count).apply(null,arguments)},xb=c._register_tensor=function(){return(xb=c._register_tensor=c.asm.register_tensor).apply(null,arguments)},vb=c._dispose_data=function(){return(vb=c._dispose_data=c.asm.dispose_data).apply(null,arguments)},wb=c._dispose=function(){return(wb=c._dispose=c.asm.dispose).apply(null,arguments)},kb=c._Abs=function(){return(kb=c._Abs=c.asm.Abs).apply(null,arguments)},Ib=c._Acos=function(){return(Ib=c._Acos=c.asm.Acos).apply(null,arguments)},Sb=c._Acosh=function(){return(Sb=c._Acosh=c.asm.Acosh).apply(null,arguments)},Nb=c._Add=function(){return(Nb=c._Add=c.asm.Add).apply(null,arguments)},Tb=c._AddN=function(){return(Tb=c._AddN=c.asm.AddN).apply(null,arguments)},Cb=c._All=function(){return(Cb=c._All=c.asm.All).apply(null,arguments)},_b=c._Any=function(){return(_b=c._Any=c.asm.Any).apply(null,arguments)},Eb=c._ArgMax=function(){return(Eb=c._ArgMax=c.asm.ArgMax).apply(null,arguments)},Ab=c._ArgMin=function(){return(Ab=c._ArgMin=c.asm.ArgMin).apply(null,arguments)},Fb=c._Asin=function(){return(Fb=c._Asin=c.asm.Asin).apply(null,arguments)},$b=c._Asinh=function(){return($b=c._Asinh=c.asm.Asinh).apply(null,arguments)},Db=c._Atan=function(){return(Db=c._Atan=c.asm.Atan).apply(null,arguments)},Rb=c._Atan2=function(){return(Rb=c._Atan2=c.asm.Atan2).apply(null,arguments)},Mb=c._Atanh=function(){return(Mb=c._Atanh=c.asm.Atanh).apply(null,arguments)},Pb=c._AvgPool=function(){return(Pb=c._AvgPool=c.asm.AvgPool).apply(null,arguments)},Ob=c._AvgPool3D=function(){return(Ob=c._AvgPool3D=c.asm.AvgPool3D).apply(null,arguments)},Lb=c._AvgPool3DGrad=function(){return(Lb=c._AvgPool3DGrad=c.asm.AvgPool3DGrad).apply(null,arguments)},zb=c._AvgPoolGrad=function(){return(zb=c._AvgPoolGrad=c.asm.AvgPoolGrad).apply(null,arguments)},Wb=c._BatchMatMul=function(){return(Wb=c._BatchMatMul=c.asm.BatchMatMul).apply(null,arguments)},Bb=c._Bincount=function(){return(Bb=c._Bincount=c.asm.Bincount).apply(null,arguments)},Vb=c._BitwiseAnd=function(){return(Vb=c._BitwiseAnd=c.asm.BitwiseAnd).apply(null,arguments)},Ub=c._Ceil=function(){return(Ub=c._Ceil=c.asm.Ceil).apply(null,arguments)},Gb=c._ClipByValue=function(){return(Gb=c._ClipByValue=c.asm.ClipByValue).apply(null,arguments)},Hb=c._Conv2D=function(){return(Hb=c._Conv2D=c.asm.Conv2D).apply(null,arguments)},qb=c._Conv2DBackpropInput=function(){return(qb=c._Conv2DBackpropInput=c.asm.Conv2DBackpropInput).apply(null,arguments)},jb=c._Conv3D=function(){return(jb=c._Conv3D=c.asm.Conv3D).apply(null,arguments)},Kb=c._Conv3DBackpropFilterV2=function(){return(Kb=c._Conv3DBackpropFilterV2=c.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Xb=c._Conv3DBackpropInputV2=function(){return(Xb=c._Conv3DBackpropInputV2=c.asm.Conv3DBackpropInputV2).apply(null,arguments)},Yb=c._Cos=function(){return(Yb=c._Cos=c.asm.Cos).apply(null,arguments)},Zb=c._Cosh=function(){return(Zb=c._Cosh=c.asm.Cosh).apply(null,arguments)},Jb=c._CropAndResize=function(){return(Jb=c._CropAndResize=c.asm.CropAndResize).apply(null,arguments)},Qb=c._Cumprod=function(){return(Qb=c._Cumprod=c.asm.Cumprod).apply(null,arguments)},ey=c._Cumsum=function(){return(ey=c._Cumsum=c.asm.Cumsum).apply(null,arguments)},ty=c._DenseBincount=function(){return(ty=c._DenseBincount=c.asm.DenseBincount).apply(null,arguments)},ny=c._DepthToSpace=function(){return(ny=c._DepthToSpace=c.asm.DepthToSpace).apply(null,arguments)},ay=c._DepthwiseConv2dNative=function(){return(ay=c._DepthwiseConv2dNative=c.asm.DepthwiseConv2dNative).apply(null,arguments)},ry=c._Diag=function(){return(ry=c._Diag=c.asm.Diag).apply(null,arguments)},sy=c._Dilation2D=function(){return(sy=c._Dilation2D=c.asm.Dilation2D).apply(null,arguments)},iy=c._Dilation2DBackpropFilter=function(){return(iy=c._Dilation2DBackpropFilter=c.asm.Dilation2DBackpropFilter).apply(null,arguments)},oy=c._Dilation2DBackpropInput=function(){return(oy=c._Dilation2DBackpropInput=c.asm.Dilation2DBackpropInput).apply(null,arguments)},ly=c._Elu=function(){return(ly=c._Elu=c.asm.Elu).apply(null,arguments)},uy=c._EluGrad=function(){return(uy=c._EluGrad=c.asm.EluGrad).apply(null,arguments)},py=c._Equal=function(){return(py=c._Equal=c.asm.Equal).apply(null,arguments)},cy=c._Erf=function(){return(cy=c._Erf=c.asm.Erf).apply(null,arguments)},dy=c._Exp=function(){return(dy=c._Exp=c.asm.Exp).apply(null,arguments)},hy=c._Expm1=function(){return(hy=c._Expm1=c.asm.Expm1).apply(null,arguments)},my=c._FlipLeftRight=function(){return(my=c._FlipLeftRight=c.asm.FlipLeftRight).apply(null,arguments)},fy=c._Floor=function(){return(fy=c._Floor=c.asm.Floor).apply(null,arguments)},gy=c._FloorDiv=function(){return(gy=c._FloorDiv=c.asm.FloorDiv).apply(null,arguments)},by=c._FusedBatchNorm=function(){return(by=c._FusedBatchNorm=c.asm.FusedBatchNorm).apply(null,arguments)},yy=c._FusedConv2D=function(){return(yy=c._FusedConv2D=c.asm.FusedConv2D).apply(null,arguments)},xy=c._FusedDepthwiseConv2D=function(){return(xy=c._FusedDepthwiseConv2D=c.asm.FusedDepthwiseConv2D).apply(null,arguments)},vy=c._Gather=function(){return(vy=c._Gather=c.asm.Gather).apply(null,arguments)},wy=c._GatherNd=function(){return(wy=c._GatherNd=c.asm.GatherNd).apply(null,arguments)},ky=c._Greater=function(){return(ky=c._Greater=c.asm.Greater).apply(null,arguments)},Iy=c._GreaterEqual=function(){return(Iy=c._GreaterEqual=c.asm.GreaterEqual).apply(null,arguments)},Sy=c._IsFinite=function(){return(Sy=c._IsFinite=c.asm.IsFinite).apply(null,arguments)},Ny=c._IsInf=function(){return(Ny=c._IsInf=c.asm.IsInf).apply(null,arguments)},Ty=c._IsNan=function(){return(Ty=c._IsNan=c.asm.IsNan).apply(null,arguments)},Cy=c._LRN=function(){return(Cy=c._LRN=c.asm.LRN).apply(null,arguments)},_y=c._LRNGrad=function(){return(_y=c._LRNGrad=c.asm.LRNGrad).apply(null,arguments)},Ey=c._LeakyRelu=function(){return(Ey=c._LeakyRelu=c.asm.LeakyRelu).apply(null,arguments)},Ay=c._Less=function(){return(Ay=c._Less=c.asm.Less).apply(null,arguments)},Fy=c._LessEqual=function(){return(Fy=c._LessEqual=c.asm.LessEqual).apply(null,arguments)},$y=c._LinSpace=function(){return($y=c._LinSpace=c.asm.LinSpace).apply(null,arguments)},Dy=c._Log=function(){return(Dy=c._Log=c.asm.Log).apply(null,arguments)},Ry=c._Log1p=function(){return(Ry=c._Log1p=c.asm.Log1p).apply(null,arguments)},My=c._LogicalAnd=function(){return(My=c._LogicalAnd=c.asm.LogicalAnd).apply(null,arguments)},Py=c._LogicalNot=function(){return(Py=c._LogicalNot=c.asm.LogicalNot).apply(null,arguments)},Oy=c._LogicalOr=function(){return(Oy=c._LogicalOr=c.asm.LogicalOr).apply(null,arguments)},Ly=c._LogicalXor=function(){return(Ly=c._LogicalXor=c.asm.LogicalXor).apply(null,arguments)},zy=c._Max=function(){return(zy=c._Max=c.asm.Max).apply(null,arguments)},Wy=c._MaxPool=function(){return(Wy=c._MaxPool=c.asm.MaxPool).apply(null,arguments)},By=c._MaxPool3D=function(){return(By=c._MaxPool3D=c.asm.MaxPool3D).apply(null,arguments)},Vy=c._MaxPool3DGrad=function(){return(Vy=c._MaxPool3DGrad=c.asm.MaxPool3DGrad).apply(null,arguments)},Uy=c._MaxPoolGrad=function(){return(Uy=c._MaxPoolGrad=c.asm.MaxPoolGrad).apply(null,arguments)},Gy=c._MaxPoolWithArgmax=function(){return(Gy=c._MaxPoolWithArgmax=c.asm.MaxPoolWithArgmax).apply(null,arguments)},Hy=c._Maximum=function(){return(Hy=c._Maximum=c.asm.Maximum).apply(null,arguments)},qy=c._Mean=function(){return(qy=c._Mean=c.asm.Mean).apply(null,arguments)},jy=c._Min=function(){return(jy=c._Min=c.asm.Min).apply(null,arguments)},Ky=c._Minimum=function(){return(Ky=c._Minimum=c.asm.Minimum).apply(null,arguments)},Xy=c._MirrorPad=function(){return(Xy=c._MirrorPad=c.asm.MirrorPad).apply(null,arguments)},Yy=c._Mod=function(){return(Yy=c._Mod=c.asm.Mod).apply(null,arguments)},Zy=c._Multinomial=function(){return(Zy=c._Multinomial=c.asm.Multinomial).apply(null,arguments)},Jy=c._Multiply=function(){return(Jy=c._Multiply=c.asm.Multiply).apply(null,arguments)},Qy=c._Neg=function(){return(Qy=c._Neg=c.asm.Neg).apply(null,arguments)},ex=c._NonMaxSuppressionV3=function(){return(ex=c._NonMaxSuppressionV3=c.asm.NonMaxSuppressionV3).apply(null,arguments)},tx=c._NonMaxSuppressionV4=function(){return(tx=c._NonMaxSuppressionV4=c.asm.NonMaxSuppressionV4).apply(null,arguments)},kh=c._NonMaxSuppressionV5=function(){return(kh=c._NonMaxSuppressionV5=c.asm.NonMaxSuppressionV5).apply(null,arguments)},Ih=c._NotEqual=function(){return(Ih=c._NotEqual=c.asm.NotEqual).apply(null,arguments)},Yp=c._OneHot=function(){return(Yp=c._OneHot=c.asm.OneHot).apply(null,arguments)},nx=c._PadV2=function(){return(nx=c._PadV2=c.asm.PadV2).apply(null,arguments)},ax=c._Pow=function(){return(ax=c._Pow=c.asm.Pow).apply(null,arguments)},El=c._Prelu=function(){return(El=c._Prelu=c.asm.Prelu).apply(null,arguments)},Sh=c._Prod=function(){return(Sh=c._Prod=c.asm.Prod).apply(null,arguments)},Al=c._RealDiv=function(){return(Al=c._RealDiv=c.asm.RealDiv).apply(null,arguments)},Fl=c._Reciprocal=function(){return(Fl=c._Reciprocal=c.asm.Reciprocal).apply(null,arguments)},rx=c._Relu=function(){return(rx=c._Relu=c.asm.Relu).apply(null,arguments)},Y=c._Relu6=function(){return(Y=c._Relu6=c.asm.Relu6).apply(null,arguments)},oe=c._ResizeBilinear=function(){return(oe=c._ResizeBilinear=c.asm.ResizeBilinear).apply(null,arguments)},Ie=c._ResizeBilinearGrad=function(){return(Ie=c._ResizeBilinearGrad=c.asm.ResizeBilinearGrad).apply(null,arguments)},Ye=c._ResizeNearestNeighbor=function(){return(Ye=c._ResizeNearestNeighbor=c.asm.ResizeNearestNeighbor).apply(null,arguments)},It=c._ResizeNearestNeighborGrad=function(){return(It=c._ResizeNearestNeighborGrad=c.asm.ResizeNearestNeighborGrad).apply(null,arguments)},St=c._Reverse=function(){return(St=c._Reverse=c.asm.Reverse).apply(null,arguments)},He=c._RotateWithOffset=function(){return(He=c._RotateWithOffset=c.asm.RotateWithOffset).apply(null,arguments)},Ve=c._Round=function(){return(Ve=c._Round=c.asm.Round).apply(null,arguments)},zt=c._Rsqrt=function(){return(zt=c._Rsqrt=c.asm.Rsqrt).apply(null,arguments)},pa=c._ScatterNd=function(){return(pa=c._ScatterNd=c.asm.ScatterNd).apply(null,arguments)},Nr=c._SearchSorted=function(){return(Nr=c._SearchSorted=c.asm.SearchSorted).apply(null,arguments)},Nh=c._SelectV2=function(){return(Nh=c._SelectV2=c.asm.SelectV2).apply(null,arguments)},Zp=c._Selu=function(){return(Zp=c._Selu=c.asm.Selu).apply(null,arguments)},sx=c._Sigmoid=function(){return(sx=c._Sigmoid=c.asm.Sigmoid).apply(null,arguments)},Mn=c._Sign=function(){return(Mn=c._Sign=c.asm.Sign).apply(null,arguments)},es=c._Sin=function(){return(es=c._Sin=c.asm.Sin).apply(null,arguments)},Th=c._Sinh=function(){return(Th=c._Sinh=c.asm.Sinh).apply(null,arguments)},bD=c._Softmax=function(){return(bD=c._Softmax=c.asm.Softmax).apply(null,arguments)},yD=c._Softplus=function(){return(yD=c._Softplus=c.asm.Softplus).apply(null,arguments)},xD=c._SparseFillEmptyRows=function(){return(xD=c._SparseFillEmptyRows=c.asm.SparseFillEmptyRows).apply(null,arguments)},vD=c._SparseReshape=function(){return(vD=c._SparseReshape=c.asm.SparseReshape).apply(null,arguments)},wD=c._SparseSegmentReduction=function(){return(wD=c._SparseSegmentReduction=c.asm.SparseSegmentReduction).apply(null,arguments)},kD=c._SparseToDense=function(){return(kD=c._SparseToDense=c.asm.SparseToDense).apply(null,arguments)},ID=c._Sqrt=function(){return(ID=c._Sqrt=c.asm.Sqrt).apply(null,arguments)},SD=c._Square=function(){return(SD=c._Square=c.asm.Square).apply(null,arguments)},ND=c._SquaredDifference=function(){return(ND=c._SquaredDifference=c.asm.SquaredDifference).apply(null,arguments)},TD=c._Step=function(){return(TD=c._Step=c.asm.Step).apply(null,arguments)},CD=c._StridedSlice=function(){return(CD=c._StridedSlice=c.asm.StridedSlice).apply(null,arguments)},_D=c._Sub=function(){return(_D=c._Sub=c.asm.Sub).apply(null,arguments)},ED=c._Sum=function(){return(ED=c._Sum=c.asm.Sum).apply(null,arguments)},AD=c._Tan=function(){return(AD=c._Tan=c.asm.Tan).apply(null,arguments)},FD=c._Tanh=function(){return(FD=c._Tanh=c.asm.Tanh).apply(null,arguments)},$D=c._TensorScatterUpdate=function(){return($D=c._TensorScatterUpdate=c.asm.TensorScatterUpdate).apply(null,arguments)},DD=c._Tile=function(){return(DD=c._Tile=c.asm.Tile).apply(null,arguments)},RD=c._TopK=function(){return(RD=c._TopK=c.asm.TopK).apply(null,arguments)},MD=c._Transform=function(){return(MD=c._Transform=c.asm.Transform).apply(null,arguments)},PD=c._Transpose=function(){return(PD=c._Transpose=c.asm.Transpose).apply(null,arguments)},OD=c.__FusedMatMul=function(){return(OD=c.__FusedMatMul=c.asm._FusedMatMul).apply(null,arguments)},LD=c._malloc=function(){return(LD=c._malloc=c.asm.malloc).apply(null,arguments)},zD=c._free=function(){return(zD=c._free=c.asm.free).apply(null,arguments)},WD=c.__emscripten_tls_init=function(){return(WD=c.__emscripten_tls_init=c.asm._emscripten_tls_init).apply(null,arguments)},Ch=c._pthread_self=function(){return(Ch=c._pthread_self=c.asm.pthread_self).apply(null,arguments)},BD=c.___errno_location=function(){return(BD=c.___errno_location=c.asm.__errno_location).apply(null,arguments)},Jk=c.__emscripten_thread_init=function(){return(Jk=c.__emscripten_thread_init=c.asm._emscripten_thread_init).apply(null,arguments)},VD=c.__emscripten_thread_crashed=function(){return(VD=c.__emscripten_thread_crashed=c.asm._emscripten_thread_crashed).apply(null,arguments)},UD=c._emscripten_main_thread_process_queued_calls=function(){return(UD=c._emscripten_main_thread_process_queued_calls=c.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},GD=c._emscripten_main_browser_thread_id=function(){return(GD=c._emscripten_main_browser_thread_id=c.asm.emscripten_main_browser_thread_id).apply(null,arguments)},Qk=c._emscripten_run_in_main_runtime_thread_js=function(){return(Qk=c._emscripten_run_in_main_runtime_thread_js=c.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},HD=c._emscripten_dispatch_to_thread_=function(){return(HD=c._emscripten_dispatch_to_thread_=c.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},eI=c.__emscripten_proxy_execute_task_queue=function(){return(eI=c.__emscripten_proxy_execute_task_queue=c.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},ix=c.__emscripten_thread_free_data=function(){return(ix=c.__emscripten_thread_free_data=c.asm._emscripten_thread_free_data).apply(null,arguments)},tI=c.__emscripten_thread_exit=function(){return(tI=c.__emscripten_thread_exit=c.asm._emscripten_thread_exit).apply(null,arguments)},nI=c._emscripten_stack_set_limits=function(){return(nI=c._emscripten_stack_set_limits=c.asm.emscripten_stack_set_limits).apply(null,arguments)},ox=c.stackSave=function(){return(ox=c.stackSave=c.asm.stackSave).apply(null,arguments)},_h=c.stackRestore=function(){return(_h=c.stackRestore=c.asm.stackRestore).apply(null,arguments)},Eh=c.stackAlloc=function(){return(Eh=c.stackAlloc=c.asm.stackAlloc).apply(null,arguments)},qD=c.dynCall_iijjiiii=function(){return(qD=c.dynCall_iijjiiii=c.asm.dynCall_iijjiiii).apply(null,arguments)},jD=c.dynCall_jiji=function(){return(jD=c.dynCall_jiji=c.asm.dynCall_jiji).apply(null,arguments)};c.keepRuntimeAlive=Na,c.wasmMemory=ue,c.cwrap=hb,c.ExitStatus=Gs,c.PThread=Ae;var Ah;Sr=function R(){Ah||aI(),Ah||(Sr=R)};function aI(R){if(R=R||b,Jr>0)return;if(C){h(c),Qt(),startWorker(c);return}if(Zr(),Jr>0)return;function q(){Ah||(Ah=!0,c.calledRun=!0,!ke&&(Qt(),h(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),sh()))}c.setStatus?(c.setStatus("Running..."),setTimeout(function(){setTimeout(function(){c.setStatus("")},1),q()},1)):q()}if(c.preInit)for(typeof c.preInit=="function"&&(c.preInit=[c.preInit]);c.preInit.length>0;)c.preInit.pop()();aI();var Fh;f&&(Fh={uncaughtException:process.listeners("uncaughtException").filter(function(R){return!f.uncaughtException.indexOf(R)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(R){return!f.unhandledRejection.indexOf(R)>-1})});var $h;if(typeof WasmBackendModule!="undefined")$h=WasmBackendModule;else if(typeof r!="undefined")$h=r;else throw new Error("Could not find wasm module in post.js");if(Fh){var KD=$h._dispose;$h._dispose=function(){KD(),Fh.uncaughtException.forEach(function(R){process.removeListener("uncaughtException",R)}),Fh.unhandledRejection.forEach(function(R){process.removeListener("unhandledRejection",R)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}),IR=Gt((e,t)=>{t.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}};`}),SR=Gt((e,t)=>{var n=(()=>{var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};var s=typeof r!="undefined"?r:{},i,o;s.ready=new Promise(function(Y,oe){i=Y,o=oe});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),p=[],d="./this.program",c=(Y,oe)=>{throw oe},h=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function b(Y){return s.locateFile?s.locateFile(Y,g):g+Y}var y,x,v,I;function T(Y){Y instanceof Tl||D("exiting due to exception: "+Y)}if(f){var C=Nv(),E=GS();m?g=E.dirname(g)+"/":g=__dirname+"/",y=(Y,oe)=>(Y=Zr(Y)?new URL(Y):E.normalize(Y),C.readFileSync(Y,oe?void 0:"utf8")),v=Y=>{var oe=y(Y,!0);return oe.buffer||(oe=new Uint8Array(oe)),oe},x=(Y,oe,Ie)=>{Y=Zr(Y)?new URL(Y):E.normalize(Y),C.readFile(Y,function(Ye,It){Ye?Ie(Ye):oe(It.buffer)})},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),p=process.argv.slice(2),process.on("uncaughtException",function(Y){if(!(Y instanceof Tl))throw Y}),process.on("unhandledRejection",function(Y){throw Y}),c=(Y,oe)=>{if(jn())throw process.exitCode=Y,oe;T(oe),process.exit(Y)},s.inspect=function(){return"[Emscripten Module object]"}}else(h||m)&&(m?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),a&&(g=a),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",y=Y=>{var oe=new XMLHttpRequest;return oe.open("GET",Y,!1),oe.send(null),oe.responseText},m&&(v=Y=>{var oe=new XMLHttpRequest;return oe.open("GET",Y,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),x=(Y,oe,Ie)=>{var Ye=new XMLHttpRequest;Ye.open("GET",Y,!0),Ye.responseType="arraybuffer",Ye.onload=()=>{if(Ye.status==200||Ye.status==0&&Ye.response){oe(Ye.response);return}Ie()},Ye.onerror=Ie,Ye.send(null)},I=Y=>document.title=Y);var F=s.print||console.log.bind(console),D=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(p=s.arguments),s.thisProgram&&(d=s.thisProgram),s.quit&&(c=s.quit);var $=4,S;s.wasmBinary&&(S=s.wasmBinary);var M=s.noExitRuntime||!0;typeof WebAssembly!="object"&&tr("no native wasm support detected");var B,U=!1,H;function j(Y,oe){Y||tr(oe)}var K=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Z(Y,oe,Ie){oe>>>=0;for(var Ye=oe+Ie,It=oe;Y[It]&&!(It>=Ye);)++It;if(It-oe>16&&Y.buffer&&K)return K.decode(Y.subarray(oe,It));for(var St="";oe<It;){var He=Y[oe++];if(!(He&128)){St+=String.fromCharCode(He);continue}var Ve=Y[oe++]&63;if((He&224)==192){St+=String.fromCharCode((He&31)<<6|Ve);continue}var zt=Y[oe++]&63;if((He&240)==224?He=(He&15)<<12|Ve<<6|zt:He=(He&7)<<18|Ve<<12|zt<<6|Y[oe++]&63,He<65536)St+=String.fromCharCode(He);else{var pa=He-65536;St+=String.fromCharCode(55296|pa>>10,56320|pa&1023)}}return St}function J(Y,oe){return Y>>>=0,Y?Z(ie,Y,oe):""}function ee(Y,oe,Ie,Ye){if(Ie>>>=0,!(Ye>0))return 0;for(var It=Ie,St=Ie+Ye-1,He=0;He<Y.length;++He){var Ve=Y.charCodeAt(He);if(Ve>=55296&&Ve<=57343){var zt=Y.charCodeAt(++He);Ve=65536+((Ve&1023)<<10)|zt&1023}if(Ve<=127){if(Ie>=St)break;oe[Ie++>>>0]=Ve}else if(Ve<=2047){if(Ie+1>=St)break;oe[Ie++>>>0]=192|Ve>>6,oe[Ie++>>>0]=128|Ve&63}else if(Ve<=65535){if(Ie+2>=St)break;oe[Ie++>>>0]=224|Ve>>12,oe[Ie++>>>0]=128|Ve>>6&63,oe[Ie++>>>0]=128|Ve&63}else{if(Ie+3>=St)break;oe[Ie++>>>0]=240|Ve>>18,oe[Ie++>>>0]=128|Ve>>12&63,oe[Ie++>>>0]=128|Ve>>6&63,oe[Ie++>>>0]=128|Ve&63}}return oe[Ie>>>0]=0,Ie-It}function ae(Y,oe,Ie){return ee(Y,ie,oe,Ie)}var te,re,ie,ye,ue,be,ke,Se,We;function Ge(Y){te=Y,s.HEAP8=re=new Int8Array(Y),s.HEAP16=ye=new Int16Array(Y),s.HEAP32=be=new Int32Array(Y),s.HEAPU8=ie=new Uint8Array(Y),s.HEAPU16=ue=new Uint16Array(Y),s.HEAPU32=ke=new Uint32Array(Y),s.HEAPF32=Se=new Float32Array(Y),s.HEAPF64=We=new Float64Array(Y)}var ht=s.INITIAL_MEMORY||16777216,st,at=[],rt=[],Me=[],ft=!1;function jn(){return M}function Lt(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)$n(s.preRun.shift());Sr(at)}function la(){ft=!0,Sr(rt)}function cn(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Dn(s.postRun.shift());Sr(Me)}function $n(Y){at.unshift(Y)}function ua(Y){rt.unshift(Y)}function Dn(Y){Me.unshift(Y)}var lt=0,Rn=null,Kn=null;function Ir(Y){lt++,s.monitorRunDependencies&&s.monitorRunDependencies(lt)}function Nl(Y){if(lt--,s.monitorRunDependencies&&s.monitorRunDependencies(lt),lt==0&&(Rn!==null&&(clearInterval(Rn),Rn=null),Kn)){var oe=Kn;Kn=null,oe()}}function tr(Y){s.onAbort&&s.onAbort(Y),Y="Aborted("+Y+")",D(Y),U=!0,H=1,Y+=". Build with -sASSERTIONS for more info.";var oe=new WebAssembly.RuntimeError(Y);throw o(oe),oe}var Gp="data:application/octet-stream;base64,";function Na(Y){return Y.startsWith(Gp)}function Zr(Y){return Y.startsWith("file://")}var Qt;Qt="tfjs-backend-wasm.wasm",Na(Qt)||(Qt=b(Qt));function sh(Y){try{if(Y==Qt&&S)return new Uint8Array(S);if(v)return v(Y);throw"both async and sync fetching of the wasm failed"}catch(oe){tr(oe)}}function Ag(){if(!S&&(h||m)){if(typeof fetch=="function"&&!Zr(Qt))return fetch(Qt,{credentials:"same-origin"}).then(function(Y){if(!Y.ok)throw"failed to load wasm binary file at '"+Qt+"'";return Y.arrayBuffer()}).catch(function(){return sh(Qt)});if(x)return new Promise(function(Y,oe){x(Qt,function(Ie){Y(new Uint8Array(Ie))},oe)})}return Promise.resolve().then(function(){return sh(Qt)})}function Fg(){var Y={env:Hp,wasi_snapshot_preview1:Hp};function oe(He,Ve){var zt=He.exports;s.asm=zt,B=s.asm.memory,Ge(B.buffer),st=s.asm.__indirect_function_table,ua(s.asm.__wasm_call_ctors),Nl("wasm-instantiate")}Ir("wasm-instantiate");function Ie(He){oe(He.instance)}function Ye(He){return Ag().then(function(Ve){return WebAssembly.instantiate(Ve,Y)}).then(function(Ve){return Ve}).then(He,function(Ve){D("failed to asynchronously prepare wasm: "+Ve),tr(Ve)})}function It(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!Na(Qt)&&!Zr(Qt)&&!f&&typeof fetch=="function"?fetch(Qt,{credentials:"same-origin"}).then(function(He){var Ve=WebAssembly.instantiateStreaming(He,Y);return Ve.then(Ie,function(zt){return D("wasm streaming compile failed: "+zt),D("falling back to ArrayBuffer instantiation"),Ye(Ie)})}):Ye(Ie)}if(s.instantiateWasm)try{var St=s.instantiateWasm(Y,oe);return St}catch(He){D("Module.instantiateWasm callback failed with error: "+He),o(He)}return It().catch(o),{}}var Kk,Jr;function Tl(Y){this.name="ExitStatus",this.message="Program terminated with exit("+Y+")",this.status=Y}function Sr(Y){for(;Y.length>0;)Y.shift()(s)}function $g(){tr("")}function ih(){return 4294901760}function Us(){return ih()}function Dg(Y,oe,Ie){ie.copyWithin(Y>>>0,oe>>>0,oe+Ie>>>0)}function oh(Y){try{return B.grow(Y-te.byteLength+65535>>>16),Ge(B.buffer),1}catch(oe){}}function Cl(Y){var oe=ie.length;Y=Y>>>0;var Ie=ih();if(Y>Ie)return!1;let Ye=(zt,pa)=>zt+(pa-zt%pa)%pa;for(var It=1;It<=4;It*=2){var St=oe*(1+.2/It);St=Math.min(St,Y+100663296);var He=Math.min(Ie,Ye(Math.max(Y,St),65536)),Ve=oh(He);if(Ve)return!0}return!1}var gn={varargs:void 0,get:function(){gn.varargs+=4;var Y=be[gn.varargs-4>>>2];return Y},getStr:function(Y){var oe=J(Y);return oe}};function lh(Y){return 52}function Rg(Y,oe,Ie,Ye,It){return 70}var Mg=[null,[],[]];function Xk(Y,oe){var Ie=Mg[Y];oe===0||oe===10?((Y===1?F:D)(Z(Ie,0)),Ie.length=0):Ie.push(oe)}function Yk(Y,oe,Ie,Ye){for(var It=0,St=0;St<Ie;St++){var He=ke[oe>>>2],Ve=ke[oe+4>>>2];oe+=8;for(var zt=0;zt<Ve;zt++)Xk(Y,ie[He+zt>>>0]);It+=Ve}return ke[Ye>>>2]=It,0}function uh(Y){var oe=s["_"+Y];return oe}function Gs(Y,oe){re.set(Y,oe>>>0)}function Pg(Y,oe,Ie,Ye,It){var St={string:Mn=>{var es=0;if(Mn!=null&&Mn!==0){var Th=(Mn.length<<2)+1;es=Yp(Th),ae(Mn,es,Th)}return es},array:Mn=>{var es=Yp(Mn.length);return Gs(Mn,es),es}};function He(Mn){return oe==="string"?J(Mn):oe==="boolean"?!!Mn:Mn}var Ve=uh(Y),zt=[],pa=0;if(Ye)for(var Nr=0;Nr<Ye.length;Nr++){var Nh=St[Ie[Nr]];Nh?(pa===0&&(pa=kh()),zt[Nr]=Nh(Ye[Nr])):zt[Nr]=Ye[Nr]}var Zp=Ve.apply(null,zt);function sx(Mn){return pa!==0&&Ih(pa),He(Mn)}return Zp=sx(Zp),Zp}function Og(Y,oe,Ie,Ye){Ie=Ie||[];var It=Ie.every(He=>He==="number"||He==="boolean"),St=oe!=="string";return St&&It&&!Ye?uh(Y):function(){return Pg(Y,oe,Ie,arguments,Ye)}}var Hp={abort:$g,emscripten_get_heap_max:Us,emscripten_memcpy_big:Dg,emscripten_resize_heap:Cl,fd_close:lh,fd_seek:Rg,fd_write:Yk},Lg=Fg(),ph=s.___wasm_call_ctors=function(){return(ph=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},ch=s._init=function(){return(ch=s._init=s.asm.init).apply(null,arguments)},zg=s._init_with_threads_count=function(){return(zg=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},dh=s._get_threads_count=function(){return(dh=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},Wg=s._register_tensor=function(){return(Wg=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},Ae=s._dispose_data=function(){return(Ae=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},qp=s._dispose=function(){return(qp=s._dispose=s.asm.dispose).apply(null,arguments)},Bg=s._Abs=function(){return(Bg=s._Abs=s.asm.Abs).apply(null,arguments)},hh=s._Acos=function(){return(hh=s._Acos=s.asm.Acos).apply(null,arguments)},_l=s._Acosh=function(){return(_l=s._Acosh=s.asm.Acosh).apply(null,arguments)},Vg=s._Add=function(){return(Vg=s._Add=s.asm.Add).apply(null,arguments)},Ug=s._AddN=function(){return(Ug=s._AddN=s.asm.AddN).apply(null,arguments)},Gg=s._All=function(){return(Gg=s._All=s.asm.All).apply(null,arguments)},Hg=s._Any=function(){return(Hg=s._Any=s.asm.Any).apply(null,arguments)},qg=s._ArgMax=function(){return(qg=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},mh=s._ArgMin=function(){return(mh=s._ArgMin=s.asm.ArgMin).apply(null,arguments)},fh=s._Asin=function(){return(fh=s._Asin=s.asm.Asin).apply(null,arguments)},jg=s._Asinh=function(){return(jg=s._Asinh=s.asm.Asinh).apply(null,arguments)},Kg=s._Atan=function(){return(Kg=s._Atan=s.asm.Atan).apply(null,arguments)},Xg=s._Atan2=function(){return(Xg=s._Atan2=s.asm.Atan2).apply(null,arguments)},jp=s._Atanh=function(){return(jp=s._Atanh=s.asm.Atanh).apply(null,arguments)},Yg=s._AvgPool=function(){return(Yg=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},Zg=s._AvgPool3D=function(){return(Zg=s._AvgPool3D=s.asm.AvgPool3D).apply(null,arguments)},Jg=s._AvgPool3DGrad=function(){return(Jg=s._AvgPool3DGrad=s.asm.AvgPool3DGrad).apply(null,arguments)},Hs=s._AvgPoolGrad=function(){return(Hs=s._AvgPoolGrad=s.asm.AvgPoolGrad).apply(null,arguments)},Qg=s._BatchMatMul=function(){return(Qg=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},eb=s._Bincount=function(){return(eb=s._Bincount=s.asm.Bincount).apply(null,arguments)},gh=s._BitwiseAnd=function(){return(gh=s._BitwiseAnd=s.asm.BitwiseAnd).apply(null,arguments)},tb=s._Ceil=function(){return(tb=s._Ceil=s.asm.Ceil).apply(null,arguments)},Kp=s._ClipByValue=function(){return(Kp=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},nb=s._Conv2D=function(){return(nb=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},ab=s._Conv2DBackpropInput=function(){return(ab=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},rb=s._Conv3D=function(){return(rb=s._Conv3D=s.asm.Conv3D).apply(null,arguments)},Qr=s._Conv3DBackpropFilterV2=function(){return(Qr=s._Conv3DBackpropFilterV2=s.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Xp=s._Conv3DBackpropInputV2=function(){return(Xp=s._Conv3DBackpropInputV2=s.asm.Conv3DBackpropInputV2).apply(null,arguments)},sb=s._Cos=function(){return(sb=s._Cos=s.asm.Cos).apply(null,arguments)},ib=s._Cosh=function(){return(ib=s._Cosh=s.asm.Cosh).apply(null,arguments)},ob=s._CropAndResize=function(){return(ob=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},lb=s._Cumprod=function(){return(lb=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},bh=s._Cumsum=function(){return(bh=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},yh=s._DenseBincount=function(){return(yh=s._DenseBincount=s.asm.DenseBincount).apply(null,arguments)},ub=s._DepthToSpace=function(){return(ub=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},pb=s._DepthwiseConv2dNative=function(){return(pb=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},xh=s._Diag=function(){return(xh=s._Diag=s.asm.Diag).apply(null,arguments)},vh=s._Dilation2D=function(){return(vh=s._Dilation2D=s.asm.Dilation2D).apply(null,arguments)},cb=s._Dilation2DBackpropFilter=function(){return(cb=s._Dilation2DBackpropFilter=s.asm.Dilation2DBackpropFilter).apply(null,arguments)},db=s._Dilation2DBackpropInput=function(){return(db=s._Dilation2DBackpropInput=s.asm.Dilation2DBackpropInput).apply(null,arguments)},hb=s._Elu=function(){return(hb=s._Elu=s.asm.Elu).apply(null,arguments)},mb=s._EluGrad=function(){return(mb=s._EluGrad=s.asm.EluGrad).apply(null,arguments)},wh=s._Equal=function(){return(wh=s._Equal=s.asm.Equal).apply(null,arguments)},Zk=s._Erf=function(){return(Zk=s._Erf=s.asm.Erf).apply(null,arguments)},fb=s._Exp=function(){return(fb=s._Exp=s.asm.Exp).apply(null,arguments)},gb=s._Expm1=function(){return(gb=s._Expm1=s.asm.Expm1).apply(null,arguments)},bb=s._FlipLeftRight=function(){return(bb=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},yb=s._Floor=function(){return(yb=s._Floor=s.asm.Floor).apply(null,arguments)},xb=s._FloorDiv=function(){return(xb=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},vb=s._FusedBatchNorm=function(){return(vb=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},wb=s._FusedConv2D=function(){return(wb=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},kb=s._FusedDepthwiseConv2D=function(){return(kb=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},Ib=s._Gather=function(){return(Ib=s._Gather=s.asm.Gather).apply(null,arguments)},Sb=s._GatherNd=function(){return(Sb=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},Nb=s._Greater=function(){return(Nb=s._Greater=s.asm.Greater).apply(null,arguments)},Tb=s._GreaterEqual=function(){return(Tb=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},Cb=s._IsFinite=function(){return(Cb=s._IsFinite=s.asm.IsFinite).apply(null,arguments)},_b=s._IsInf=function(){return(_b=s._IsInf=s.asm.IsInf).apply(null,arguments)},Eb=s._IsNan=function(){return(Eb=s._IsNan=s.asm.IsNan).apply(null,arguments)},Ab=s._LRN=function(){return(Ab=s._LRN=s.asm.LRN).apply(null,arguments)},Fb=s._LRNGrad=function(){return(Fb=s._LRNGrad=s.asm.LRNGrad).apply(null,arguments)},$b=s._LeakyRelu=function(){return($b=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},Db=s._Less=function(){return(Db=s._Less=s.asm.Less).apply(null,arguments)},Rb=s._LessEqual=function(){return(Rb=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},Mb=s._LinSpace=function(){return(Mb=s._LinSpace=s.asm.LinSpace).apply(null,arguments)},Pb=s._Log=function(){return(Pb=s._Log=s.asm.Log).apply(null,arguments)},Ob=s._Log1p=function(){return(Ob=s._Log1p=s.asm.Log1p).apply(null,arguments)},Lb=s._LogicalAnd=function(){return(Lb=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},zb=s._LogicalNot=function(){return(zb=s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},Wb=s._LogicalOr=function(){return(Wb=s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},Bb=s._LogicalXor=function(){return(Bb=s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},Vb=s._Max=function(){return(Vb=s._Max=s.asm.Max).apply(null,arguments)},Ub=s._MaxPool=function(){return(Ub=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},Gb=s._MaxPool3D=function(){return(Gb=s._MaxPool3D=s.asm.MaxPool3D).apply(null,arguments)},Hb=s._MaxPool3DGrad=function(){return(Hb=s._MaxPool3DGrad=s.asm.MaxPool3DGrad).apply(null,arguments)},qb=s._MaxPoolGrad=function(){return(qb=s._MaxPoolGrad=s.asm.MaxPoolGrad).apply(null,arguments)},jb=s._MaxPoolWithArgmax=function(){return(jb=s._MaxPoolWithArgmax=s.asm.MaxPoolWithArgmax).apply(null,arguments)},Kb=s._Maximum=function(){return(Kb=s._Maximum=s.asm.Maximum).apply(null,arguments)},Xb=s._Mean=function(){return(Xb=s._Mean=s.asm.Mean).apply(null,arguments)},Yb=s._Min=function(){return(Yb=s._Min=s.asm.Min).apply(null,arguments)},Zb=s._Minimum=function(){return(Zb=s._Minimum=s.asm.Minimum).apply(null,arguments)},Jb=s._MirrorPad=function(){return(Jb=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},Qb=s._Mod=function(){return(Qb=s._Mod=s.asm.Mod).apply(null,arguments)},ey=s._Multinomial=function(){return(ey=s._Multinomial=s.asm.Multinomial).apply(null,arguments)},ty=s._Multiply=function(){return(ty=s._Multiply=s.asm.Multiply).apply(null,arguments)},ny=s._Neg=function(){return(ny=s._Neg=s.asm.Neg).apply(null,arguments)},ay=s._NonMaxSuppressionV3=function(){return(ay=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},ry=s._NonMaxSuppressionV4=function(){return(ry=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},sy=s._NonMaxSuppressionV5=function(){return(sy=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},iy=s._NotEqual=function(){return(iy=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},oy=s._OneHot=function(){return(oy=s._OneHot=s.asm.OneHot).apply(null,arguments)},ly=s._PadV2=function(){return(ly=s._PadV2=s.asm.PadV2).apply(null,arguments)},uy=s._Pow=function(){return(uy=s._Pow=s.asm.Pow).apply(null,arguments)},py=s._Prelu=function(){return(py=s._Prelu=s.asm.Prelu).apply(null,arguments)},cy=s._Prod=function(){return(cy=s._Prod=s.asm.Prod).apply(null,arguments)},dy=s._RealDiv=function(){return(dy=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},hy=s._Reciprocal=function(){return(hy=s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},my=s._Relu=function(){return(my=s._Relu=s.asm.Relu).apply(null,arguments)},fy=s._Relu6=function(){return(fy=s._Relu6=s.asm.Relu6).apply(null,arguments)},gy=s._ResizeBilinear=function(){return(gy=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},by=s._ResizeBilinearGrad=function(){return(by=s._ResizeBilinearGrad=s.asm.ResizeBilinearGrad).apply(null,arguments)},yy=s._ResizeNearestNeighbor=function(){return(yy=s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},xy=s._ResizeNearestNeighborGrad=function(){return(xy=s._ResizeNearestNeighborGrad=s.asm.ResizeNearestNeighborGrad).apply(null,arguments)},vy=s._Reverse=function(){return(vy=s._Reverse=s.asm.Reverse).apply(null,arguments)},wy=s._RotateWithOffset=function(){return(wy=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},ky=s._Round=function(){return(ky=s._Round=s.asm.Round).apply(null,arguments)},Iy=s._Rsqrt=function(){return(Iy=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},Sy=s._ScatterNd=function(){return(Sy=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},Ny=s._SearchSorted=function(){return(Ny=s._SearchSorted=s.asm.SearchSorted).apply(null,arguments)},Ty=s._SelectV2=function(){return(Ty=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},Cy=s._Selu=function(){return(Cy=s._Selu=s.asm.Selu).apply(null,arguments)},_y=s._Sigmoid=function(){return(_y=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},Ey=s._Sign=function(){return(Ey=s._Sign=s.asm.Sign).apply(null,arguments)},Ay=s._Sin=function(){return(Ay=s._Sin=s.asm.Sin).apply(null,arguments)},Fy=s._Sinh=function(){return(Fy=s._Sinh=s.asm.Sinh).apply(null,arguments)},$y=s._Softmax=function(){return($y=s._Softmax=s.asm.Softmax).apply(null,arguments)},Dy=s._Softplus=function(){return(Dy=s._Softplus=s.asm.Softplus).apply(null,arguments)},Ry=s._SparseFillEmptyRows=function(){return(Ry=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},My=s._SparseReshape=function(){return(My=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},Py=s._SparseSegmentReduction=function(){return(Py=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},Oy=s._SparseToDense=function(){return(Oy=s._SparseToDense=s.asm.SparseToDense).apply(null,arguments)},Ly=s._Sqrt=function(){return(Ly=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},zy=s._Square=function(){return(zy=s._Square=s.asm.Square).apply(null,arguments)},Wy=s._SquaredDifference=function(){return(Wy=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},By=s._Step=function(){return(By=s._Step=s.asm.Step).apply(null,arguments)},Vy=s._StridedSlice=function(){return(Vy=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},Uy=s._Sub=function(){return(Uy=s._Sub=s.asm.Sub).apply(null,arguments)},Gy=s._Sum=function(){return(Gy=s._Sum=s.asm.Sum).apply(null,arguments)},Hy=s._Tan=function(){return(Hy=s._Tan=s.asm.Tan).apply(null,arguments)},qy=s._Tanh=function(){return(qy=s._Tanh=s.asm.Tanh).apply(null,arguments)},jy=s._TensorScatterUpdate=function(){return(jy=s._TensorScatterUpdate=s.asm.TensorScatterUpdate).apply(null,arguments)},Ky=s._Tile=function(){return(Ky=s._Tile=s.asm.Tile).apply(null,arguments)},Xy=s._TopK=function(){return(Xy=s._TopK=s.asm.TopK).apply(null,arguments)},Yy=s._Transform=function(){return(Yy=s._Transform=s.asm.Transform).apply(null,arguments)},Zy=s._Transpose=function(){return(Zy=s._Transpose=s.asm.Transpose).apply(null,arguments)},Jy=s.__FusedMatMul=function(){return(Jy=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},Qy=s._malloc=function(){return(Qy=s._malloc=s.asm.malloc).apply(null,arguments)},ex=s._free=function(){return(ex=s._free=s.asm.free).apply(null,arguments)},tx=s.___errno_location=function(){return(tx=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},kh=s.stackSave=function(){return(kh=s.stackSave=s.asm.stackSave).apply(null,arguments)},Ih=s.stackRestore=function(){return(Ih=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},Yp=s.stackAlloc=function(){return(Yp=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},nx=s.dynCall_iijjiiii=function(){return(nx=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},ax=s.dynCall_jiji=function(){return(ax=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=Og;var El;Kn=function Y(){El||Sh(),El||(Kn=Y)};function Sh(Y){if(Y=Y||p,lt>0||(Lt(),lt>0))return;function oe(){El||(El=!0,s.calledRun=!0,!U&&(la(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),cn()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),oe()},1)):oe()}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();Sh();var Al;l&&(Al={uncaughtException:process.listeners("uncaughtException").filter(function(Y){return!l.uncaughtException.indexOf(Y)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(Y){return!l.unhandledRejection.indexOf(Y)>-1})});var Fl;if(typeof r!="undefined")Fl=r;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Fl=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(Al){var rx=Fl._dispose;Fl._dispose=function(){rx(),Al.uncaughtException.forEach(function(Y){process.removeListener("uncaughtException",Y)}),Al.unhandledRejection.forEach(function(Y){process.removeListener("unhandledRejection",Y)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}),Rm=class{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}},Mc=class{refCount(e){return Xn("refCount")}incRef(e){return Xn("incRef")}timerAvailable(){return!0}time(e){return Xn("time")}read(e){return Xn("read")}readSync(e){return Xn("readSync")}readToGPU(e,t){return Xn("readToGPU")}numDataIds(){return Xn("numDataIds")}disposeData(e,t){return Xn("disposeData")}write(e,t,n){return Xn("write")}move(e,t,n,a,r){return Xn("move")}createTensorFromGPUData(e,t,n){return Xn("createTensorFromGPUData")}memory(){return Xn("memory")}floatPrecision(){return Xn("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return Xn("dispose")}};function Xn(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function HS(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,am(e,t,n)}function NR(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,a=0;for(;n>0;)a=Math.random()*n|0,n--,am(e,n,a),am(t,n,a)}function bc(e,t,n){return Math.max(e,Math.min(t,n))}function TR(e){return e%2===0?e:e+1}function am(e,t,n){let a=e[t];e[t]=e[n],e[n]=a}function CR(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function _R(e,t){let n=Math.random();return t*n+(1-n)*e}function ER(e,t){let n=0;for(let a=0;a<e.length;a++){let r=Number(e[a])-Number(t[a]);n+=r*r}return n}function A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Tn(e,t,n=""){A(Pr(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function Ni(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function bt(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function AR(e){return e.length===0}function qS(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==null&&t[n]!==null&&e[n]!==t[n])return!1;return!0}function Pr(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Bl(e){return e%1===0}function FR(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{let t=Math.exp(2*e);return(t-1)/(t+1)}}function $R(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function DR(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return HS(t),t}function hc(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function RR(e,t=r=>0,n,a){return new Promise((r,s)=>{let i=0,o=()=>{if(e()){r();return}i++;let l=t(i);if(n!=null&&i>=n){s();return}a!=null?a(o,l):setTimeout(o,l)};o()})}function MR(e,t){let n=1,a=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)n*=e[s];else if(e[s]===-1){if(a!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${a} and dim ${s}`);a=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(a===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let r=e.slice();return r[a]=t/n,r}function Ra(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),A(e.every(a=>a>=-n&&a<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),A(e.every(a=>Bl(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function jS(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:Ra(t,e).sort(),i=0;for(let o=0;o<e.length;++o){if(s!=null){if(s[i]===o&&e[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(s[i]==null||s[i]>o)&&e[o]===1&&(n.push(e[o]),a.push(o)),s[i]<=o&&i++}e[o]!==1&&(n.push(e[o]),a.push(o))}return{newShape:n,keptDims:a}}function KS(e,t){return Tv(e,t)}function Tv(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function XS(e,t){for(let n=0;n<e.length;n++){let a=e[n];if(isNaN(a)||!isFinite(a))throw Error(`A tensor of type ${t} being uploaded contains ${a}.`)}}function YS(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function PR(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function rm(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function ZS(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function rs(e){return typeof e=="string"||e instanceof String}function JS(e){return typeof e=="boolean"}function QS(e){return typeof e=="number"}function Pc(e){return Array.isArray(e)?Pc(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":QS(e)?"float32":rs(e)?"string":JS(e)?"bool":"float32"}function cs(e){return!!(e&&e.constructor&&e.call&&e.apply)}function sm(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function ou(e){let t=e.length;if(t<2)return[];let n=new Array(t-1);n[t-2]=e[t-1];for(let a=t-3;a>=0;--a)n[a]=n[a+1]*e[a+1];return n}function eN(e,t,n,a=!1){let r=new Array;if(t.length===1){let s=t[0]*(a?2:1);for(let i=0;i<s;i++)r[i]=n[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,u)=>l*u)*(a?2:1);for(let l=0;l<s;l++)r[l]=eN(e+l*o,i,n,a)}return r}function Ol(e,t,n=!1){if(e.length===0)return t[0];let a=e.reduce((r,s)=>r*s)*(n?2:1);if(a===0)return[];if(a!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return eN(0,e,t,n)}function OR(e,t){if(Array.isArray(e))return e;if(t==="float32")return e instanceof Float32Array?e:new Float32Array(e);if(t==="int32")return e instanceof Int32Array?e:new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Cv(e,t){let n=Mm(e,t);for(let a=0;a<n.length;a++)n[a]=1;return n}function Mm(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function LR(e,t){let n=e.reduce((a,r)=>a*r,1);if(t==null||t==="float32")return Ol(e,new Float32Array(n));if(t==="int32")return Ol(e,new Int32Array(n));if(t==="bool")return Ol(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function sa(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function zR(e,t,n){if(t===0)return 0;if(t===1)return e[0];let a=e[e.length-1];for(let r=0;r<e.length-1;++r)a+=n[r]*e[r];return a}function WR(e,t,n){if(t===0)return[];if(t===1)return[e];let a=new Array(t);for(let r=0;r<a.length-1;++r)a[r]=Math.floor(e/n[r]),e-=a[r]*n[r];return a[a.length-1]=e,a}function Pm(e){return e&&e.then&&typeof e.then=="function"}var iI="tfjsflags",tN=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=BR,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(G().getBool("IS_TEST")||G().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let a=this.urlFlags[e];G().getBool("IS_TEST")||G().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${a}.`),this.set(e,a)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(Pm(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}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 e=this.getQueryParams(this.global.location.search);iI in e&&e[iI].split(",").forEach(t=>{let[n,a]=t.split(":");this.urlFlags[n]=UR(n,a)})}};function BR(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(VR(t,a[0],a[1]),a.join("="))),t}function VR(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function UR(e,t){let n=t.toLowerCase();return n==="true"||n==="false"?n==="true":`${+n}`===n?+n:t}function G(){return _v}var _v=null;function GR(e){_v=e}var px;function nN(){if(px==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");px=e}return px}function HR(){let e=nN();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ev(e,t){let n=HR();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var lu="Abs",Ti="Acos",Ci="Acosh",Is="Add",_i="AddN",uu="All",pu="Any",cu="ArgMax",du="ArgMin",Ei="Asin",Ai="Asinh",Fi="Atan",$i="Atanh",Di="Atan2",Ri="AvgPool",Oc="AvgPoolGrad",hu="AvgPool3D",Lc="AvgPool3DGrad",Mi="BatchMatMul",mu="BatchToSpaceND",fu="Bincount",gu="BitwiseAnd",aN="BroadcastTo",zc="BroadcastArgs",Pi="Cast",Oi="Ceil",Ss="ClipByValue",Om="Complex",Wc="ComplexAbs",bu="Concat",Li="Conv2D",Lm="Conv2DBackpropFilter",zi="Conv2DBackpropInput",Wi="Conv3D",yu="Conv3DBackpropFilterV2",xu="Conv3DBackpropInputV2",Bi="Cos",Vi="Cosh",vu="Cumprod",Ui="Cumsum",wu="CropAndResize",Bc="DenseBincount",ku="DepthToSpace",Gi="DepthwiseConv2dNative",zm="DepthwiseConv2dNativeBackpropFilter",Wm="DepthwiseConv2dNativeBackpropInput",Vc="Diag",Hi="Dilation2D",Vl="Dilation2DBackpropInput",Ul="Dilation2DBackpropFilter",Av="Draw",qi="RealDiv",Bm="Einsum",ji="Elu",Iu="EluGrad",Ki="Erf",Su="Equal",Xi="Exp",Nu="ExpandDims",Yi="Expm1",Vm="FFT",Uc="Fill",Tu="FlipLeftRight",Zi="Floor",Ji="FloorDiv",Qi="FusedBatchNorm",Cu="GatherV2",_u="GatherNd",Eu="Greater",eo="GreaterEqual",to="Identity",Um="IFFT",Gm="Imag",no="IsFinite",ao="IsInf",ro="IsNan",so="LeakyRelu",Au="Less",Fu="LessEqual",$u="LinSpace",io="Log",oo="Log1p",Du="LogicalAnd",Ru="LogicalNot",Mu="LogicalOr",rN="LogicalXor",sN="LogSoftmax",qR="LowerBound",lo="LRN",Pu="LRNGrad",jR="MatrixBandPart",uo="Max",po="Maximum",co="MaxPool",Gc="MaxPoolGrad",Ou="MaxPool3D",Hc="MaxPool3DGrad",qc="MaxPoolWithArgmax",ho="Mean",mo="Min",fo="Minimum",go="MirrorPad",bo="Mod",Lu="Multinomial",yo="Multiply",zu="Neg",Wu="NotEqual",Bu="NonMaxSuppressionV3",Vu="NonMaxSuppressionV4",Uu="NonMaxSuppressionV5",Gu="OnesLike",xo="OneHot",Hu="Pack",vo="PadV2",KR="Pool",wo="Pow",ko="Prelu",Io="Prod",Hm="RaggedGather",qm="RaggedRange",jm="RaggedTensorToTensor",jc="Range",Km="Real",So="Reciprocal",No="Relu",qu="Reshape",To="ResizeNearestNeighbor",ju="ResizeNearestNeighborGrad",Co="ResizeBilinear",Ku="ResizeBilinearGrad",_o="Relu6",Eo="Reverse",Ao="Round",Fo="Rsqrt",Xu="ScatterNd",Yu="TensorScatterUpdate",Zu="SearchSorted",Ju="Select",$o="Selu",Qu="Slice",Do="Sin",Ro="Sinh",Mo="Sign",Po="Sigmoid",Oo="Softplus",Lo="Sqrt",zo="Sum",ep="SpaceToBatchND",tp="SplitV",Wo="Softmax",Kc="SparseFillEmptyRows",np="SparseReshape",Xc="SparseSegmentMean",Yc="SparseSegmentSum",ap="SparseToDense",Bo="SquaredDifference",Zc="Square",Jc="StaticRegexReplace",rp="StridedSlice",Qc="StringNGrams",ed="StringSplit",td="StringToHashBucketFast",Vo="Sub",Uo="Tan",Go="Tanh",Ns="Tile",sp="TopK",ip="Transform",$r="Transpose",nd="Unique",op="Unpack",ad="UnsortedSegmentSum",XR="UpperBound",lp="ZerosLike",Ts="Step",im="FromPixels",up="RotateWithOffset",oi="_FusedMatMul",li="FusedConv2D",ui="FusedDepthwiseConv2D";function as(...e){G().getBool("IS_TEST")||G().getBool("PROD")||console.warn(...e)}function YR(...e){G().getBool("IS_TEST")||G().getBool("PROD")||console.log(...e)}var Gl=Ev("kernelRegistry",()=>new Map),yc=Ev("gradRegistry",()=>new Map);function om(e,t){let n=Fv(e,t);return Gl.get(n)}function Tx(e){return yc.get(e)}function lm(e){let t=Gl.entries(),n=[];for(;;){let{done:a,value:r}=t.next();if(a)break;let[s,i]=r,[o]=s.split("_");o===e&&n.push(i)}return n}function rd(e){let{kernelName:t,backendName:n}=e,a=Fv(t,n);Gl.has(a)&&as(`The kernel '${t}' for backend '${n}' is already registered`),Gl.set(a,e)}function iN(e){let{kernelName:t}=e;yc.has(t)&&G().getBool("DEBUG")&&as(`Overriding the gradient for '${t}'`),yc.set(t,e)}function ZR(e,t){let n=Fv(e,t);if(!Gl.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Gl.delete(n)}function JR(e){if(!yc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);yc.delete(e)}function QR(e,t){lm(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});rd(a)})}function Fv(e,t){return`${t}_${e}`}var w={};Ee(w,{arraysEqual:()=>Pr,arraysEqualWithNull:()=>qS,assert:()=>A,assertNonNegativeIntegerDimensions:()=>sa,assertNonNull:()=>Ni,assertShapesMatch:()=>Tn,bytesFromStringArray:()=>ZS,bytesPerElement:()=>rm,checkConversionForErrors:()=>XS,clamp:()=>bc,computeStrides:()=>ou,convertBackendValuesAndArrayBuffer:()=>OR,createScalarValue:()=>sM,createShuffledIndices:()=>DR,decodeString:()=>um,distSquared:()=>ER,encodeString:()=>id,fetch:()=>oM,fingerPrint64:()=>rM,flatten:()=>ds,getArrayFromDType:()=>Tv,getTypedArrayFromDType:()=>KS,hasEncodingLoss:()=>PR,hexToLong:()=>sd,indexToLoc:()=>WR,inferDtype:()=>Pc,inferFromImplicitShape:()=>MR,isBoolean:()=>JS,isFunction:()=>cs,isInt:()=>Bl,isNumber:()=>QS,isPromise:()=>Pm,isScalarShape:()=>AR,isString:()=>rs,isTypedArray:()=>tn,isValidDtype:()=>YS,locToIndex:()=>zR,makeOnesTypedArray:()=>Cv,makeZerosNestedTypedArray:()=>LR,makeZerosTypedArray:()=>Mm,nearestDivisor:()=>sm,nearestLargerEven:()=>TR,now:()=>xc,parseAxisParam:()=>Ra,randUniform:()=>_R,repeatedTry:()=>RR,rightPad:()=>hc,shuffle:()=>HS,shuffleCombo:()=>NR,sizeFromShape:()=>bt,sizeToSquarishShape:()=>$R,squeezeShape:()=>jS,sum:()=>CR,swap:()=>am,tanh:()=>FR,toNestedArray:()=>Ol,toTypedArray:()=>Xm});function oN(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var oI=ks(lR()),Ys=oI.default||oI;function sd(e){return Ys.fromString(e,!0,16)}var lN=sd("c3a5c85c97cb3127"),Ks=sd("b492b66fbe98f273"),kn=sd("9ae16a3b2f90404f");function Cx(e){return e.xor(e.shru(47))}function uN(e,t,n){let a=e.slice(t,t+n);return Ys.fromBytes(Array.from(a),!0,!0)}function gt(e,t){return uN(e,t,8)}function lI(e,t){return uN(e,t,4)}function en(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function ls(e,t,n=sd("9ddfea08eb382d69")){let a=e.xor(t).mul(n);a=a.xor(a.shru(47));let r=t.xor(a).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function eM(e,t,n,a,r,s){r=r.add(e),s=en(s.add(r).add(a),21);let i=r;return r=r.add(t),r=r.add(n),s=s.add(en(r,44)),[r.add(a),s.add(i)]}function Rh(e,t,n,a){return eM(gt(e,t),gt(e,t+8),gt(e,t+16),gt(e,t+24),n,a)}function tM(e,t=e.length){if(t>=8){let n=kn.add(t*2),a=gt(e,0).add(kn),r=gt(e,t-8),s=en(r,37).mul(n).add(a),i=en(a,25).add(r).mul(n);return ls(s,i,n)}if(t>=4){let n=kn.add(t*2),a=lI(e,0);return ls(a.shl(3).add(t),lI(e,t-4),n)}if(t>0){let n=e[0],a=e[t>>1],r=e[t-1],s=n+(a<<8),i=t+(r<<2);return Cx(kn.mul(s).xor(lN.mul(i))).mul(kn)}return kn}function nM(e,t=e.length){let n=kn.add(t*2),a=gt(e,0).mul(Ks),r=gt(e,8),s=gt(e,t-8).mul(n),i=gt(e,t-16).mul(kn);return ls(en(a.add(r),43).add(en(s,30)).add(i),a.add(en(r.add(kn),18)).add(s),n)}function aM(e,t=e.length){let n=kn.add(t*2),a=gt(e,0).mul(kn),r=gt(e,8),s=gt(e,t-8).mul(n),i=gt(e,t-16).mul(kn),o=en(a.add(r),43).add(en(s,30)).add(i),l=ls(o,a.add(en(r.add(kn),18)).add(s),n),u=gt(e,16).mul(n),p=gt(e,24),d=o.add(gt(e,t-32)).mul(n),c=l.add(gt(e,t-24)).mul(n);return ls(en(u.add(p),43).add(en(d,30)).add(c),u.add(en(p.add(a),18)).add(d),n)}function rM(e,t=e.length){let n=Ys.fromNumber(81,!0);if(t<=32)return t<=16?tM(e,t):nM(e,t);if(t<=64)return aM(e,t);let a=n,r=n.mul(Ks).add(113),s=Cx(r.mul(kn).add(113)).mul(kn),i=[Ys.UZERO,Ys.UZERO],o=[Ys.UZERO,Ys.UZERO];a=a.mul(kn).add(gt(e,0));let l=0,u=(t-1>>6)*64,p=u+(t-1&63)-63;do a=en(a.add(r).add(i[0]).add(gt(e,l+8)),37).mul(Ks),r=en(r.add(i[1]).add(gt(e,l+48)),42).mul(Ks),a=a.xor(o[1]),r=r.add(i[0]).add(gt(e,l+40)),s=en(s.add(o[0]),33).mul(Ks),i=Rh(e,l,i[1].mul(Ks),a.add(o[0])),o=Rh(e,l+32,s.add(o[1]),r.add(gt(e,l+16))),[s,a]=[a,s],l+=64;while(l!==u);let d=Ks.add(s.and(255).shl(1));return l=p,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),a=en(a.add(r).add(i[0]).add(gt(e,l+8)),37).mul(d),r=en(r.add(i[1]).add(gt(e,l+48)),42).mul(d),a=a.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(gt(e,l+40))),s=en(s.add(o[0]),33).mul(d),i=Rh(e,l,i[1].mul(d),a.add(o[0])),o=Rh(e,l+32,s.add(o[1]),r.add(gt(e,l+16))),[s,a]=[a,s],ls(ls(i[0],o[0],d).add(Cx(r).mul(lN)).add(s),ls(i[1],o[1],d).add(a),d)}function sM(e,t){return t==="string"?id(e):Xm([e],t)}function iM(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Xm(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ds(e)),G().getBool("DEBUG")&&XS(e,t),iM(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let a=0;a<n.length;++a)Math.round(e[a])!==0&&(n[a]=1);return n}else throw new Error(`Unknown data type ${t}`)}function xc(){return G().platform.now()}function oM(e,t){return G().platform.fetch(e,t)}function id(e,t="utf-8"){return t=t||"utf-8",G().platform.encode(e,t)}function um(e,t="utf-8"){return t=t||"utf-8",G().platform.decode(e,t)}function tn(e){return G().platform.isTypedArray!=null?G().platform.isTypedArray(e):oN(e)}function ds(e,t=[],n=!1){if(t==null&&(t=[]),typeof e=="boolean"||typeof e=="number"||typeof e=="string"||Pm(e)||e==null||tn(e)&&n)t.push(e);else if(Array.isArray(e)||tn(e))for(let a=0;a<e.length;++a)ds(e[a],t,n);else{let a=-1;for(let r of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(r)&&(a=Math.max(a,Number(r)));for(let r=0;r<=a;r++)ds(e[r],t,n)}return t}var lM=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new pM)}profileKernel(e,t,n){let a,r=()=>{a=n()},s,i=xc();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:xc()-i})}if(G().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<a.length;o++){let l=a[o];l.data().then(u=>{uM(u,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:a,inputs:r,extraInfo:s}=e;n.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function uM(e,t,n){if(t!=="float32")return!1;for(let a=0;a<e.length;a++){let r=e[a];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}var pM=class{logKernelProfile(e,t,n,a,r,s){let i=typeof a=="number"?hc(`${a}ms`,9):a.error,o=hc(e,25),l=t.rank,u=t.size,p=hc(t.shape.toString(),14),d="";for(let c in r){let h=r[c];if(h!=null){let m=h.shape||t.shape,f=m.length;d+=`${c}: ${f}D ${f>0?m:""} `}}console.log(`%c${o}    %c${i}    %c${l}D ${p}    %c${u}    %c${d}    %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function cM(e,t,n){let a={},r={};for(let l=0;l<t.length;l++)a[t[l].id]=!0;for(let l=0;l<e.length;l++){let u=e[l],p=u.inputs;for(let d in p){let c=p[d],h=!1;for(let m=0;m<t.length;m++)if(a[c.id]){u.outputs.forEach(f=>a[f.id]=!0),h=!0,r[u.id]=!0;break}if(h)break}}let s={};s[n.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],p=u.inputs;for(let d=0;d<u.outputs.length;d++)if(s[u.outputs[d].id]){for(let c in p)s[p[c].id]=!0,i[u.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let u=e[l];if(r[u.id]&&i[u.id]){let p={};for(let c in u.inputs){let h=u.inputs[c];a[h.id]&&(p[c]=h)}let d=Object.assign({},u);d.inputs=p,d.outputs=u.outputs,o.push(d)}}return o}function dM(e,t,n,a){for(let r=t.length-1;r>=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=n(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let p=s.inputs[l];if(!Pr(u.shape,p.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${p.shape}'`);if(e[p.id]==null)e[p.id]=u;else{let d=e[p.id];e[p.id]=a(d,u),d.dispose()}}}}var uI=20,Jp=3,cx=7;function hM(e,t,n,a){let r=ou(t),s=mM(e,t,n,r),i=t.length,o=Kh(e,t,n,r,s),l=["Tensor"];return a&&(l.push(`  dtype: ${n}`),l.push(`  rank: ${i}`),l.push(`  shape: [${t}]`),l.push("  values:")),l.push(o.map(u=>"    "+u).join(`
`)),l.join(`
`)}function mM(e,t,n,a){let r=bt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?rc(e):e;if(o>1)for(let u=0;u<r/s;u++){let p=u*s;for(let d=0;d<s;d++)i[d]=Math.max(i[d],ac(l[p+d],0,n).length)}return i}function ac(e,t,n){let a;return Array.isArray(e)?a=`${parseFloat(e[0].toFixed(cx))} + ${parseFloat(e[1].toFixed(cx))}j`:rs(e)?a=`'${e}'`:n==="bool"?a=pN(e):a=parseFloat(e.toFixed(cx)).toString(),hc(a,t)}function pN(e){return e===0?"false":"true"}function Kh(e,t,n,a,r,s=!0){let i=n==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(n==="complex64"){let f=rc(e);return[ac(f[0],0,n)]}return n==="bool"?[pN(e[0])]:[e[0].toString()]}if(l===1){if(o>uI){let f=Jp*i,g=Array.from(e.slice(0,f)),b=Array.from(e.slice((o-Jp)*i,o*i));return n==="complex64"&&(g=rc(g),b=rc(b)),["["+g.map((y,x)=>ac(y,r[x],n)).join(", ")+", ..., "+b.map((y,x)=>ac(y,r[o-Jp+x],n)).join(", ")+"]"]}return["["+(n==="complex64"?rc(e):Array.from(e)).map((f,g)=>ac(f,r[g],n)).join(", ")+"]"]}let u=t.slice(1),p=a.slice(1),d=a[0]*i,c=[];if(o>uI){for(let f=0;f<Jp;f++){let g=f*d,b=g+d;c.push(...Kh(e.slice(g,b),u,n,p,r,!1))}c.push("...");for(let f=o-Jp;f<o;f++){let g=f*d,b=g+d;c.push(...Kh(e.slice(g,b),u,n,p,r,f===o-1))}}else for(let f=0;f<o;f++){let g=f*d,b=g+d;c.push(...Kh(e.slice(g,b),u,n,p,r,f===o-1))}let h=l===2?",":"";c[0]="["+(o>0?c[0]+h:"");for(let f=1;f<c.length-1;f++)c[f]=" "+c[f]+h;let m=`,
`;for(let f=2;f<l;f++)m+=`
`;return c[c.length-1]=" "+c[c.length-1]+"]"+(s?"":m),c}function rc(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Vt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=bt(e),n!=null){let a=n.length;A(a===this.size,()=>`Length of values '${a}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="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||Tv(t,this.size),this.strides=ou(e)}set(e,...t){t.length===0&&(t=[0]),A(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let r=`Requested out of range element at ${e}.   Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=this.strides[a]*e[a];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Wa().makeTensor(this.values,this.shape,this.dtype)}},Wa=null,Ml=null,fM=null;function gM(e){Wa=e}function bM(e){Ml=e}function yM(e){fM=e}var Te=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=bt(e),this.strides=ou(e),this.dataId=n,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Ml.buffer(this.shape,this.dtype,e)}bufferSync(){return Ml.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Ol(this.shape,e,this.dtype==="complex64")}arraySync(){return Ol(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Wa().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>um(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Wa().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Wa().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>um(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Wa().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Wa().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ml.print(this,e)}clone(){return this.throwIfDisposed(),Ml.clone(this)}toString(e=!1){let t=this.dataSync();return hM(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ml.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Wa().makeVariable(this,e,t,n)}};Object.defineProperty(Te,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Q(){return Ev("Tensor",()=>Te)}Q();var hs=class extends Te{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Pr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Wa().disposeTensor(this),this.dataId=e.dataId,Wa().incRef(this,null)}dispose(){Wa().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(hs,Symbol.hasInstance,{value:e=>e instanceof Te&&e.assign!=null&&e.assign instanceof Function});var Ua={};Ee(Ua,{assertTypesMatch:()=>hN,getTensorsInContainer:()=>$v,isTensorInList:()=>vM,makeTypesMatch:()=>Ft});var _x;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(_x||(_x={}));var Ex;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Ex||(Ex={}));var Ax;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Ax||(Ax={}));var Fx;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Fx||(Fx={}));var $x;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})($x||($x={}));var xM={float32:Fx,int32:Ex,bool:Ax,complex64:$x};function ba(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return xM[e][t]}function Ym(e){return ba(e,"int32")}function cN(e){return e!=null&&typeof e=="object"&&"texture"in e&&e.texture instanceof WebGLTexture}function dN(e){return typeof GPUBuffer!="undefined"&&e!=null&&typeof e=="object"&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Ft(e,t){if(e.dtype===t.dtype)return[e,t];let n=ba(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function hN(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function vM(e,t){return t.some(n=>n.id===e.id)}function $v(e){let t=[];return mN(e,t,new Set),t}function mN(e,t,n){if(e==null)return;if(e instanceof Te){t.push(e);return}if(!wM(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),mN(s,t,n))}}function wM(e){return Array.isArray(e)||typeof e=="object"}function dx(e){return e.kernelName!=null}var pI=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(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},vc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new pI}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t];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:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(as(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new lM(this.backendInstance),!0}setupRegisteredKernels(){lm(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){lm(e).forEach(t=>{t.disposeFunc!=null&&t.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Mc)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,r=n.then(s=>a<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(a<this.pendingBackendInitId||(this.pendingBackendInit=null,as(`Initialization of backend ${e} failed`),as(s.stack||s.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return as(`Initialization of backend ${e} failed`),as(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(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((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:a,asyncInit:r}=this.initializeBackend(n);if(r||a)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),a=n.backend,r=this.readSync(t),s=a.refCount(t);a.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let a;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(a),()=>(a=t(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(e,t,n){e();try{let a=n();return t(),a}catch(a){throw t(),a}}nextTensorId(){return vc.nextTensorId++}nextVariableId(){return vc.nextVariableId++}clone(e){let t=O.runKernel(to,{x:e}),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return O.runKernel(Pi,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,om(e,this.backendName)==null)throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let a=this.backend.numDataIds(),r=0;n.forEach(o=>{r+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=a-t-r-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],a=this.isTapeOn(),r=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=dx(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(dx(e)){let{kernelName:h,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=om(h,this.backendName);A(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),i=()=>{let b=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let y=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,b,y);let x=y.map(v=>v.rank!=null?v:this.makeTensorFromTensorInfo(v));if(a){let v=this.getTensorsForGradient(h,m,x);n=this.saveTensorsForBackwardMode(v)}return x}}else{let{forwardFunc:h}=e,m=f=>{a&&(n=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>h(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:u,attrs:p}=e,d=dx(e)?null:e.backwardsFunc,c;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(c=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(c),t=c.outputs)}),a&&this.addTapeNode(l,u,t,d,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(h=>u[h]!=null?u[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:c.timeMs,extraInfo:c.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=Tx(e);if(a!=null){let r=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?(A(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=r.map(l=>t[l]);let o=n.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,n,a){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",a=a||this.backend;let r=e;n==="string"&&rs(e[0])&&(r=e.map(o=>id(o)));let s=a.write(r,t,n),i=new Te(t,n,s,this.nextTensorId());if(this.trackTensor(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=ZS(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r={dataId:e,shape:t,dtype:n};return this.makeTensorFromTensorInfo(r,a)}makeTensorFromTensorInfo(e,t){let{dataId:n,shape:a,dtype:r}=e,s=new Te(a,r,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,a){n=n||this.nextVariableId().toString(),a!=null&&a!==e.dtype&&(e=e.cast(a));let r=new hs(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*rm(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof hs||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*rm(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,a,r,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=Tx(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((u,p)=>{if(u==null){let d=n[p],c=Mm(d.size,d.dtype);return this.makeTensor(c,d.shape,d.dtype)}return u}),a(l.length>1?l:l[0],r,s))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=$v(e),n=new Set(t.map(r=>r.id));for(let r=0;r<this.state.activeScope.track.length;r++){let s=this.state.activeScope.track[r];!s.kept&&!n.has(s.id)&&s.dispose()}let a=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(r=>{!r.kept&&r.scopeId===a.id&&this.track(r)})}gradients(e,t,n,a=!1){if(A(t.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 r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));A(r instanceof Te,()=>"The result y returned by f() must be a tensor.");let s=cM(this.state.activeTape,t,r);if(!a&&s.length===0&&t.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 i={};i[r.id]=n==null?kM(r.shape):n,dM(i,s,l=>this.tidy(l),IM);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:o}})}customGrad(e){return A(cs(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(t.every(i=>i instanceof Te),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};t.forEach((i,o)=>{a[o]=i});let r=(i,o)=>(n=e(...t,o),A(n.value instanceof Te,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(cs(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s=(i,o)=>{let l=n.gradFunc(i,o),u=Array.isArray(l)?l:[l];A(u.length===t.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(...)."),A(u.every(d=>d instanceof Te),()=>"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 u.forEach((d,c)=>{p[c]=()=>d}),p};return this.runKernelFunc({forwardFunc:r,backwardsFunc:s,inputs:a})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=xc(),n=await this.backend.time(e);return n.wallMs=xc()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new pI;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};vc.nextTensorId=0;vc.nextVariableId=0;function kM(e){let t=Cv(bt(e),"float32");return O.makeTensor(t,e,"float32")}function fN(){let e=nN();if(e._tfengine==null){let t=new tN(e);e._tfengine=new vc(t)}return GR(e._tfengine.ENV),gM(()=>e._tfengine),e._tfengine}var O=fN();function IM(e,t){let n={a:e,b:t};return O.runKernel(Is,n)}var od={};Ee(od,{isBrowser:()=>gN,isMobile:()=>TM,mockIsMobile:()=>NM});function SM(){return typeof navigator!="undefined"&&navigator!=null}var Dx;function NM(e){Dx=e}function TM(e){if(Dx!==void 0)return Dx;if(e||SM()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.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 gN(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Bn=G();Bn.registerFlag("DEBUG",()=>!1,e=>{e&&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.")});Bn.registerFlag("IS_BROWSER",()=>gN());Bn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Bn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Bn.registerFlag("IS_SAFARI",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));Bn.registerFlag("PROD",()=>!1);Bn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Bn.getBool("DEBUG"));Bn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Bn.registerFlag("IS_TEST",()=>!1);Bn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Bn.getBool("DEBUG"));Bn.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Bn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Bn.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function pr(e,t){let n=e;if(tn(e))return t==="string"?[]:[e.length];if(cN(e)){let r=e.channels||"RGBA";return[e.height,e.width*r.length]}else if(dN(e))return[e.buffer.size/(t==null?4:rm(t))];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||tn(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&G().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&bN(e,a,[]),a}function bN(e,t,n){if(n=n||[],!Array.isArray(e)&&!tn(e)){A(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let a=t.slice(1);for(let r=0;r<e.length;++r)bN(e[r],a,n.concat(r))}function cI(e,t,n,a){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${a}' must be ${e} tensor, but got ${t} tensor`)}}function _(e,t,n,a="numeric"){if(e instanceof Te)return cI(a,e.dtype,t,n),e;let r=Pc(e);if(r!=="string"&&["bool","int32","float32"].indexOf(a)>=0&&(r=a),cI(a,r,t,n),e==null||!tn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${o}'`)}let s=pr(e,r);!tn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Xm(e,r):ds(e,[],!0);return O.makeTensor(i,s,r)}function wc(e,t,n,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>_(r,`${t}[${s}]`,n,a))}var Dv="__op";function L(e){let t=Object.keys(e);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 n=t[0],a=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+Dv;let r=(...s)=>{O.startScope(n);try{let i=a(...s);return Pm(i)&&console.error("Cannot return a Promise inside of tidy."),O.endScope(i),i}catch(i){throw O.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function CM(e,t){let n=_(e,"real","complex"),a=_(t,"imag","complex");Tn(n.shape,a.shape,`real and imag shapes, ${n.shape} and ${a.shape}, must match in call to tf.complex().`);let r={real:n,imag:a};return O.runKernel(Om,r)}var Rr=L({complex_:CM});function Cs(e,t,n,a){if(a==null)a=Pc(e);else if(a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(dN(e)||cN(e)){if(a!=="float32"&&a!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${a}.`);return O.backend.createTensorFromGPUData(e,t||n,a)}if(!tn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="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){sa(t);let r=bt(t),s=bt(n);A(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i<n.length;++i){let o=n[i],l=i===n.length-1?o!==bt(t.slice(i)):!0;A(n[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!tn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?Xm(e,a):ds(e,[],!0),O.makeTensor(e,t,a)}function bn(e,t,n){let a=pr(e,n);return Cs(e,t,a,n)}var Rx={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},hr=class{static join(e){return new hr(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,e==null||(e instanceof Array||(e=[e]),e=e.map(n=>tn(n)?n.buffer:n),e.length===0))return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){let a=e[n];n!==e.length-1&&a.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);let r=t+a.byteLength;this.shards.push({buffer:a,start:t,end:r}),t=r}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),t=Math.min(this.byteLength,t),t<=e)return new ArrayBuffer(0);let n=this.findShardForByte(e);if(n===-1)throw new Error(`Could not find start shard for byte ${e}`);let a=t-e,r=new ArrayBuffer(a),s=new Uint8Array(r),i=0;for(let o=n;o<this.shards.length;o++){let l=this.shards[o],u=e+i-l.start,p=i,d=Math.min(t,l.end)-l.start,c=new Uint8Array(l.buffer,u,d-u);if(s.set(c,p),i+=c.length,t<l.end)break}return r}findShardForByte(e){if(this.shards.length===0||e<0||e>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(a){return e<a.start?-1:e>=a.end?1:0}if(t(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;let n=_M(this.shards,t);return n===-1?-1:(this.previousShardIndex=n,this.previousShardIndex)}};function _M(e,t){let n=0,a=e.length;for(;n<=a;){let r=Math.floor((a-n)/2)+n,s=t(e[r]);if(s===0)return r;s<0?a=r:n=r+1}return-1}var pm=4;async function EM(e,t){let n=[],a=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<r.length;++i){let o=r[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let u={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let p=new Promise(async d=>{let c=await l.bytes(),h=c.reduce((g,b)=>g+b.length,0)+pm*c.length,m=new Uint8Array(h),f=0;for(let g=0;g<c.length;g++){let b=c[g],y=new Uint8Array(new Uint32Array([b.length]).buffer);m.set(y,f),f+=pm,m.set(b,f),f+=b.length}d(m)});a.push(p)}else a.push(l.data());t!=null&&(u.group=t),n.push(u)}let s=await Promise.all(a);return{data:AM(s),specs:n}}function yN(e,t){let n=new hr(e),a={},r,s=0;for(let i of t){let o=i.name,l=i.dtype,u=i.shape,p=bt(u),d;if("quantization"in i){let c=i.quantization;if(c.dtype==="uint8"||c.dtype==="uint16"){if(!("min"in c&&"scale"in c))throw new Error(`Weight ${i.name} with quantization ${c.dtype} doesn't have corresponding metadata min and scale.`)}else if(c.dtype==="float16"){if(l!=="float32")throw new Error(`Weight ${i.name} is quantized with ${c.dtype} which only supports weights of type float32 not ${l}.`)}else throw new Error(`Weight ${i.name} has unknown quantization dtype ${c.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let h=Rx[c.dtype],m=n.slice(s,s+p*h),f=c.dtype==="uint8"?new Uint8Array(m):new Uint16Array(m);if(l==="float32")if(c.dtype==="uint8"||c.dtype==="uint16"){d=new Float32Array(f.length);for(let g=0;g<f.length;g++){let b=f[g];d[g]=b*c.scale+c.min}}else if(c.dtype==="float16")r===void 0&&(r=OM()),d=r(f);else throw new Error(`Unsupported quantization type ${c.dtype} for weight type float32.`);else if(l==="int32"){if(c.dtype!=="uint8"&&c.dtype!=="uint16")throw new Error(`Unsupported quantization type ${c.dtype} for weight type int32.`);d=new Int32Array(f.length);for(let g=0;g<f.length;g++){let b=f[g];d[g]=Math.round(b*c.scale+c.min)}}else throw new Error(`Unsupported dtype in weight '${o}': ${l}`);s+=p*h}else if(l==="string"){let c=bt(i.shape);d=[];for(let h=0;h<c;h++){let m=new Uint32Array(n.slice(s,s+pm))[0];s+=pm;let f=new Uint8Array(n.slice(s,s+m));d.push(f),s+=m}}else{let c=Rx[l],h=n.slice(s,s+p*c);if(l==="float32")d=new Float32Array(h);else if(l==="int32")d=new Int32Array(h);else if(l==="bool")d=new Uint8Array(h);else if(l==="complex64"){d=new Float32Array(h);let m=new Float32Array(d.length/2),f=new Float32Array(d.length/2);for(let y=0;y<m.length;y++)m[y]=d[y*2],f[y]=d[y*2+1];let g=bn(m,u,"float32"),b=bn(f,u,"float32");a[o]=Rr(g,b),g.dispose(),b.dispose()}else throw new Error(`Unsupported dtype in weight '${o}': ${l}`);s+=p*c}l!=="complex64"&&(a[o]=bn(d,u,l))}return a}function AM(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,n=[];e.forEach(s=>{if(t+=s.byteLength,n.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 a=new Uint8Array(t),r=0;return n.forEach(s=>{a.set(new Uint8Array(s.buffer),r),r+=s.byteLength}),a.buffer}var Rv=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function dI(e){return Rv?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function FM(e){if(Rv)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let a=0,r=t.length;a<r;a++)n+=String.fromCharCode(t[a]);return btoa(n)}function $M(e){if(Rv){let a=Buffer.from(e,"base64");return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;++a)n.set([t.charCodeAt(a)],a);return n.buffer}function DM(e){return hr.join(e)}function hI(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function xN(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(n.initializerSignature=e.initializerSignature),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}function vN(e,t,n){let a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(a.trainingConfig=e.trainingConfig),e.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");a.weightSpecs=t,a.weightData=n}return e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(a.initializerSignature=e.initializerSignature),a}async function Mv(e,t){let n,a;return e.weightsManifest!=null&&([n,a]=await t(e.weightsManifest)),vN(e,n,a)}function ld(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:dI(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:dI(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:new hr(e.weightData).byteLength}}function wN(e){let t=[];for(let n of e)t.push(...n.weights);return t}function RM(){let e=n=>{let a=n<<13,r=0;for(;!(a&8388608);)r-=8388608,a<<=1;return a&=-8388609,r+=947912704,a|r},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function MM(){let e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function PM(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function OM(){let e=RM(),t=MM(),n=PM();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i<a.length;i++){let o=a[i],l=e[n[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var $t=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return $t.instance==null&&($t.instance=new $t),$t.instance}static registerSaveRouter(e){$t.getInstance().saveRouters.push(e)}static registerLoadRouter(e){$t.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return $t.getHandlers(e,"save")}static getLoadHandlers(e,t){return $t.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?$t.getInstance().loadRouters:$t.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},LM=e=>$t.registerSaveRouter(e),zM=e=>$t.registerLoadRouter(e),WM=e=>$t.getSaveHandlers(e),BM=(e,t)=>$t.getLoadHandlers(e,t),Mx="tensorflowjs",Px=1,ti="models_store",ss="model_info_store";function kN(){if(!G().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Ox(e){let t=e.result;t.createObjectStore(ti,{keyPath:"modelPath"}),t.createObjectStore(ss,{keyPath:"modelPath"})}var pi=class{constructor(e){if(this.indexedDB=kN(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,a)=>{let r=this.indexedDB.open(Mx,Px);r.onupgradeneeded=()=>Ox(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(ti,"readonly"),o=i.objectStore(ti).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),a(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(o.result.modelArtifacts)},o.onerror=l=>(s.close(),a(o.error)),i.oncomplete=()=>s.close()}else{t.weightData=hr.join(t.weightData);let i=ld(t),o=s.transaction(ss,"readwrite"),l=o.objectStore(ss),u;try{u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(d){return a(d)}let p;u.onsuccess=()=>{p=s.transaction(ti,"readwrite");let d=p.objectStore(ti),c;try{c=d.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(h){return a(h)}c.onsuccess=()=>n({modelArtifactsInfo:i}),c.onerror=h=>{l=o.objectStore(ss);let m=l.delete(this.modelPath);m.onsuccess=()=>(s.close(),a(c.error)),m.onerror=f=>(s.close(),a(c.error))}},u.onerror=d=>(s.close(),a(u.error)),o.oncomplete=()=>{p==null?s.close():p.oncomplete=()=>s.close()}}},r.onerror=s=>a(r.error)})}};pi.URL_SCHEME="indexeddb://";var IN=e=>G().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(pi.URL_SCHEME)?VM(e.slice(pi.URL_SCHEME.length)):null;$t.registerSaveRouter(IN);$t.registerLoadRouter(IN);function VM(e){return new pi(e)}function UM(e){return e.startsWith(pi.URL_SCHEME)?e.slice(pi.URL_SCHEME.length):e}var GM=class{constructor(){this.indexedDB=kN()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(Mx,Px);n.onupgradeneeded=()=>Ox(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(ss,"readonly"),s=r.objectStore(ss).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(a.close(),t(s.error)),r.oncomplete=()=>a.close()},n.onerror=a=>t(n.error)})}async removeModel(e){return e=UM(e),new Promise((t,n)=>{let a=this.indexedDB.open(Mx,Px);a.onupgradeneeded=()=>Ox(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(ss,"readwrite"),i=s.objectStore(ss),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),p=()=>{l=r.transaction(ti,"readwrite");let d=l.objectStore(ti).delete(e);d.onsuccess=()=>t(o.result.modelArtifactsInfo),d.onerror=c=>n(o.error)};u.onsuccess=p,u.onerror=d=>(p(),r.close(),n(o.error))}},o.onerror=u=>(r.close(),n(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},a.onerror=r=>n(a.error)})}},Fr="/",Pl="tensorflowjs_models",SN="info",HM="model_topology",qM="weight_specs",jM="weight_data",KM="model_metadata";function NN(e){return{info:[Pl,e,SN].join(Fr),topology:[Pl,e,HM].join(Fr),weightSpecs:[Pl,e,qM].join(Fr),weightData:[Pl,e,jM].join(Fr),modelMetadata:[Pl,e,KM].join(Fr)}}function TN(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function XM(e){let t=e.split(Fr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Fr)}function YM(e){return e.startsWith(ci.URL_SCHEME)?e.slice(ci.URL_SCHEME.length):e}var ci=class{constructor(e){if(!G().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,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=NN(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),a=ld(e),r=hr.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,FM(r));let s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:a}}catch(s){throw TN(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=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},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.`);t.modelTopology=n;let a=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(a==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=a;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let i=JSON.parse(r);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=$M(s),t}};ci.URL_SCHEME="localstorage://";var CN=e=>G().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ci.URL_SCHEME)?ZM(e.slice(ci.URL_SCHEME.length)):null;$t.registerSaveRouter(CN);$t.registerLoadRouter(CN);function ZM(e){return new ci(e)}var JM=class{constructor(){A(G().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Pl+Fr,n=Fr+SN;for(let a=0;a<this.LS.length;++a){let r=this.LS.key(a);if(r.startsWith(t)&&r.endsWith(n)){let s=XM(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=YM(e);let t=NN(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let n=JSON.parse(this.LS.getItem(t.info));return TN(t),n}},Ll="://",Pn=class{constructor(){this.managers={}}static getInstance(){return Pn.instance==null&&(Pn.instance=new Pn),Pn.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Ll)&&(e=e.slice(0,e.indexOf(Ll))),A(e.length>0,()=>"scheme must not be an empty string.");let n=Pn.getInstance();A(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=Pn.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Pn.getInstance().managers)}};function Xh(e){if(e.indexOf(Ll)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Pn.getSchemes().join(",")}`);return{scheme:e.split(Ll)[0],path:e.split(Ll)[1]}}async function _N(e,t,n=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=$t.getLoadHandlers(e);A(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),A(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=$t.getSaveHandlers(t);A(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),A(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=Xh(e).scheme,l=Xh(e).path,u=o===Xh(e).scheme,p=await r.load();n&&u&&await Pn.getManager(o).removeModel(l);let d=await i.save(p);return n&&!u&&await Pn.getManager(o).removeModel(l),d.modelArtifactsInfo}async function QM(){let e=Pn.getSchemes(),t={};for(let n of e){let a=await Pn.getManager(n).listModels();for(let r in a){let s=n+Ll+r;t[s]=a[r]}}return t}async function eP(e){let t=Xh(e);return Pn.getManager(t.scheme).removeModel(t.path)}async function tP(e,t){return _N(e,t,!1)}async function nP(e,t){return _N(e,t,!0)}var aP=class{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){if(typeof window=="undefined"||!G().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",n=>{if(n.source===window&&n.data.name===this.messageName){n.stopPropagation();let a=this.functionRefs[n.data.index];a(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(e){return oN(e)}};if(G().get("IS_BROWSER")){G().setPlatform("browser",new aP);try{Pn.registerManager(ci.URL_SCHEME,new JM)}catch(e){}try{Pn.registerManager(pi.URL_SCHEME,new GM)}catch(e){}}var rP={importFetch:()=>uR()},hx,sP=class{constructor(){this.util=pR(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return G().global.fetch!=null?G().global.fetch(e,t):(hx==null&&(hx=rP.importFetch()),hx(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}};G().get("IS_NODE")&&!G().get("IS_BROWSER")&&G().setPlatform("node",new sP);function ze(e,t="float32",n){return t=t||"float32",sa(e),new Vt(e,t,n)}function iP(e,t){let n=_(e,"x","cast");if(!YS(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let a={x:n},r={dtype:t};return O.runKernel(Pi,a,r)}var se=L({cast_:iP});function oP(e){let t={x:_(e,"x","clone","string_or_numeric")};return O.runKernel(to,t)}var or=L({clone_:oP});function Pv(e,t=!1){console.log(e.toString(t))}fN();var lP={buffer:ze,cast:se,clone:or,print:Pv};bM(lP);function uP(){G().set("PROD",!0)}function pP(){G().set("DEBUG",!0)}function cP(){G().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Ov(e){G().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}yM(Ov);function dP(){O.disposeVariables()}function Aa(){return O}function cm(){return O.memory()}function hP(e){return O.profile(e)}function P(e,t){return O.tidy(e,t)}function _e(e){$v(e).forEach(t=>t.dispose())}function qt(e){return O.keep(e)}function mP(e){return O.time(e)}function fP(e){return O.setBackend(e)}function gP(){return O.ready()}function bP(){return O.backendName}function yP(e){O.removeBackend(e)}function xP(e){return O.findBackend(e)}function vP(e){return O.findBackendFactory(e)}function Zm(e,t,n=1){return O.registerBackend(e,t,n)}function EN(){return O.backend}function wP(e,t){G().setPlatform(e,t)}function kP(e,t){let n=_(e,"a","add"),a=_(t,"b","add");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(Is,r)}var X=L({add_:kP});function IP(e,t){let n=_(e,"a","floorDiv"),a=_(t,"b","floorDiv");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(Ji,r)}var Jm=L({floorDiv_:IP});function SP(e,t){let n=_(e,"a","div"),a=_(t,"b","div");if([n,a]=Ft(n,a),n.dtype==="int32"&&a.dtype==="int32")return Jm(n,a);let r={a:n,b:a},s={};return O.runKernel(qi,r,s)}var he=L({div_:SP});function NP(e,t){let n=_(e,"a","mul"),a=_(t,"b","mul");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(yo,r)}var z=L({mul_:NP});function TP(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return O.runKernel(Wc,n)}else{let n={x:t};return O.runKernel(lu,n)}}var Wt=L({abs_:TP});function CP(e){let t={x:_(e,"x","acos")};return O.runKernel(Ti,t)}var Lv=L({acos_:CP});function _P(e){let t={x:_(e,"x","acosh")};return O.runKernel(Ci,t)}var zv=L({acosh_:_P});function EP(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>_(r,`tensors${s}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Pr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return O.runKernel(_i,a)}var AN=L({addN_:EP});function AP(e,t=null,n=!1){let a={x:_(e,"x","all","bool")},r={axis:t,keepDims:n};return O.runKernel(uu,a,r)}var Qm=L({all_:AP});function FP(e,t=null,n=!1){let a={x:_(e,"x","any","bool")},r={axis:t,keepDims:n};return O.runKernel(pu,a,r)}var kc=L({any_:FP});function $P(e,t=0){let n={x:_(e,"x","argMax")},a={axis:t};return O.runKernel(cu,n,a)}var di=L({argMax_:$P});function DP(e,t=0){let n={x:_(e,"x","argMin")},a={axis:t};return O.runKernel(du,n,a)}var Wv=L({argMin_:DP});function RP(e){let t={x:_(e,"x","asin")};return O.runKernel(Ei,t)}var Bv=L({asin_:RP});function MP(e){let t={x:_(e,"x","asinh")};return O.runKernel(Ai,t)}var Vv=L({asinh_:MP});function PP(e){let t={x:_(e,"x","atan")};return O.runKernel(Fi,t)}var Uv=L({atan_:PP});function OP(e,t){let n=_(e,"a","atan2"),a=_(t,"b","atan2");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(Di,r)}var Gv=L({atan2_:OP});function LP(e){let t={x:_(e,"x","atanh")};return O.runKernel($i,t)}var Hv=L({atanh_:LP});function zP(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=DN(r);return ud(e,o,n,s,a,null,null,l)}function FN(e,t,n,a,r,s,i="channelsLast"){let[o,l]=Ic(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return ud(e,u,n,a,r,s,!1,i)}function WP(e,t,n,a,r,s,i="NDHWC"){let[o,l,u]=Lx(t),p,d;if(i==="NDHWC")d="channelsLast",p=[o,l,u,e[4],e[4]];else if(i==="NCDHW")d="channelsFirst",p=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return $N(e,p,n,a,r,!1,d,s)}function ud(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,u,p,d]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,p,d]=e;else if(o==="channelsFirst")[l,d,u,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[c,h,,m]=t,[f,g]=Ic(n),[b,y]=Ic(a),x=zl(c,b),v=zl(h,y),{padInfo:I,outHeight:T,outWidth:C}=UP(r,u,p,f,g,x,v,s,o),E=i?m*d:m,F;return o==="channelsFirst"?F=[l,E,T,C]:o==="channelsLast"&&(F=[l,T,C,E]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:p,inChannels:d,outHeight:T,outWidth:C,outChannels:E,padInfo:I,strideHeight:f,strideWidth:g,filterHeight:c,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:b,dilationWidth:y,inShape:e,outShape:F,filterShape:t}}function $N(e,t,n,a,r,s=!1,i="channelsLast",o){let[l,u,p,d,c]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,p,d,c]=e;else if(i==="channelsFirst")[l,c,u,p,d]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,m,f,,g]=t,[b,y,x]=Lx(n),[v,I,T]=Lx(a),C=zl(h,v),E=zl(m,I),F=zl(f,T),{padInfo:D,outDepth:$,outHeight:S,outWidth:M}=GP(r,u,p,d,b,y,x,C,E,F,o),B=s?g*c:g,U;return i==="channelsFirst"?U=[l,B,$,S,M]:i==="channelsLast"&&(U=[l,$,S,M,B]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:p,inWidth:d,inChannels:c,outDepth:$,outHeight:S,outWidth:M,outChannels:B,padInfo:D,strideDepth:b,strideHeight:y,strideWidth:x,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:C,effectiveFilterHeight:E,effectiveFilterWidth:F,dilationDepth:v,dilationHeight:I,dilationWidth:T,inShape:e,outShape:U,filterShape:t}}function BP(e,t,n,a,r){a==null&&(a=qv(e,t,n));let s=e[0],i=e[1],o=Sc((s-t+2*a)/n+1,r),l=Sc((i-t+2*a)/n+1,r);return[o,l]}function VP(e,t,n,a,r,s){r==null&&(r=qv(e,t[0],a[0]));let i=[0,0,0,n];for(let o=0;o<3;o++)e[o]+2*r>=t[o]&&(i[o]=Sc((e[o]-t[o]+2*r)/a[o]+1,s));return i}function qv(e,t,n,a=1){let r=zl(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function Ic(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Lx(e){return typeof e=="number"?[e,e,e]:e}function zl(e,t){return t<=1?e:e+(e-1)*(t-1)}function UP(e,t,n,a,r,s,i,o,l){let u,p,d;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let c=BP([t,n],s,a,e,o);p=c[0],d=c[1]}else if(e==="same"){p=Math.ceil(t/a),d=Math.ceil(n/r);let c=Math.max(0,(p-1)*a+s-t),h=Math.max(0,(d-1)*r+i-n),m=Math.floor(c/2),f=c-m,g=Math.floor(h/2),b=h-g;u={top:m,bottom:f,left:g,right:b,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-s+1)/a),d=Math.ceil((n-i+1)/r);else if(typeof e=="object"){let c=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:c,bottom:h,left:m,right:f,type:c===0&&h===0&&m===0&&f===0?"VALID":"EXPLICIT"},p=Sc((t-s+c+h)/a+1,o),d=Sc((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:p,outWidth:d}}function GP(e,t,n,a,r,s,i,o,l,u,p){let d,c,h,m;if(e==="valid"&&(e=0),typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=VP([t,n,a,1],[o,l,u],1,[r,s,i],e,p);c=f[0],h=f[1],m=f[2]}else if(e==="same"){c=Math.ceil(t/r),h=Math.ceil(n/s),m=Math.ceil(a/i);let f=(c-1)*r+o-t,g=(h-1)*s+l-n,b=(m-1)*i+u-a,y=Math.floor(f/2),x=f-y,v=Math.floor(g/2),I=g-v,T=Math.floor(b/2),C=b-T;d={top:v,bottom:I,left:T,right:C,front:y,back:x,type:"SAME"}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:c,outHeight:h,outWidth:m}}function Sc(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ms(e){let[t,n,a]=Ic(e);return t===1&&n===1&&a===1}function mr(e,t){return ms(e)||ms(t)}function hi(e){return Ic(e).every(t=>t>0)}function DN(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Cn(e,t,n){if(n!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if(typeof t=="number")A(Bl(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else if(typeof t=="object")t.forEach(a=>{a.forEach(r=>{A(Bl(r),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${r}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function HP(e,t){let n={x:_(e,"x","reshape","string_or_numeric")},a={shape:t};return O.runKernel(qu,n,a)}var W=L({reshape_:HP});function qP(e,t,n,a,r){let s=_(e,"x","avgPool","float32"),i=1;A(mr(n,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),Cn("avgPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=O.runKernel(Ri,u,p);return d=se(d,s.dtype),l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var xa=L({avgPool_:qP});function jP(e,t,n,a,r,s="NDHWC"){let i=_(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),A(typeof n=="number"&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`),Cn("avgPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=O.runKernel(hu,u,p);return d=se(d,o.dtype),l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var jv=L({avgPool3d_:jP});function KP(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let n=wc(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
          with dtype ${s.dtype}. `)}),n.length===1)return or(n[0]);let a=n,r={axis:t};return O.runKernel(bu,a,r)}var et=L({concat_:KP});function XP(e,t,n=!1,a=!1){let r=_(e,"a","matMul"),s=_(t,"b","matMul");[r,s]=Ft(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return O.runKernel(Mi,i,o)}var $e=L({matMul_:XP});function YP(e){let t={x:_(e,"x","sigmoid","float32")};return O.runKernel(Po,t)}var fa=L({sigmoid_:YP});function ZP(e,t,n){let a=_(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return O.runKernel(Qu,r,s)}var Ue=L({slice_:ZP});function JP(e){let t={x:_(e,"x","tanh","float32")};return O.runKernel(Go,t)}var mi=L({tanh_:JP});function QP(e,t,n,a,r,s){let i=_(e,"forgetBias","basicLSTMCell"),o=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),u=_(a,"data","basicLSTMCell"),p=_(r,"c","basicLSTMCell"),d=_(s,"h","basicLSTMCell"),c=et([u,d],1),h=$e(c,o),m=X(h,l),f=m.shape[0],g=m.shape[1]/4,b=[f,g],y=Ue(m,[0,0],b),x=Ue(m,[0,g],b),v=Ue(m,[0,g*2],b),I=Ue(m,[0,g*3],b),T=X(z(fa(y),mi(x)),z(p,fa(X(i,v)))),C=z(mi(T),fa(I));return[T,C]}var RN=L({basicLSTMCell_:QP});function eO(e,t,n){let a=_(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);A(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length  ${t.length}`),A(a.shape[0]%r===0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:a},i={blockShape:t,crops:n};return O.runKernel(mu,s,i)}var pd=L({batchToSpaceND_:eO});function tO(e){let t;return e.rank===0||e.rank===1?t=W(e,[1,1,1,e.size]):e.rank===2?t=W(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function nO(e,t,n,a,r,s){s==null&&(s=.001);let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;a!=null&&(p=_(a,"offset","batchNorm")),A(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:tO(i),scale:u,offset:p,mean:o,variance:l},c={varianceEpsilon:s},h=O.runKernel(Qi,d,c);return W(h,i.shape)}var _s=L({batchNorm_:nO});function aO(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;return a!=null&&(p=_(a,"offset","batchNorm")),A(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),A(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&A(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),_s(i,o,l,p,u,s)}var Kv=L({batchNorm2d_:aO});function rO(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;return a!=null&&(p=_(a,"offset","batchNorm")),A(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),A(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&A(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),_s(i,o,l,p,u,s)}var Xv=L({batchNorm3d_:rO});function sO(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let p;return a!=null&&(p=_(a,"offset","batchNorm")),A(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),A(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),A(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&A(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),_s(i,o,l,p,u,s)}var Yv=L({batchNorm4d_:sO});function iO(e,t,n){let a=_(e,"x","bincount"),r=_(t,"weights","bincount");A(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),A(n>=0,()=>`size must be non-negative, but got ${n}.`),A(r.size===a.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${r.shape}.`);let s={x:a,weights:r},i={size:n};return O.runKernel(fu,s,i)}var Zv=L({bincount_:iO});function oO(e,t){let n=_(e,"x","bitwiseAnd"),a=_(t,"y","bitwiseAnd");if(!Pr(n.shape,a.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${a.shape}`);if(n.dtype!=="int32"||a.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${a.dtype}`);let r={a:n,b:a};return O.runKernel(gu,r)}var MN=L({bitwiseAnd_:oO});function lO(e,t){let n=_(e,"s0","broadcastArgs","int32"),a=_(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(a.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${a.rank}`);let r={s0:n,s1:a};return O.runKernel(zc,r)}var PN=L({broadcastArgs_:lO});function uO(e,t){let n=_(e,"broadcastTo","x"),a=n.shape;if(sa(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){let l=n.shape.slice();for(;l.length<t.length;)l.unshift(1);n=W(n,l)}let r=n.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(r[l]===t[l])s[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return or(n);let i={x:n},o={reps:s};return O.runKernel(Ns,i,o)}var ri=L({broadcastTo_:uO});function pO(e){let t={x:_(e,"x","ceil","float32")};return O.runKernel(Oi,t)}var Jv=L({ceil_:pO});function xn(e,t,n){sa(e),n=n||Pc(t);let a={shape:e,value:t,dtype:n};return O.runKernel(Uc,{},a)}function cO(e,t,n){let a=_(e,"x","clipByValue");if(A(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return xn(a.shape,t,a.dtype);let r={x:a},s={clipValueMin:t,clipValueMax:n};return O.runKernel(Ss,r,s)}var sn=L({clipByValue_:cO});function dO(e){return et(e,0)}var Qv=L({concat1d_:dO});function hO(e,t){return et(e,t)}var ew=L({concat2d_:hO});function mO(e,t){return et(e,t)}var tw=L({concat3d_:mO});function fO(e,t){return et(e,t)}var nw=L({concat4d_:fO});function gO(e,t,n,a,r="NHWC",s=[1,1],i){let o=_(e,"x","conv2d","float32"),l=_(t,"filter","conv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Cn("conv2d",a,i);let d=r==="NHWC"?u.shape[3]:u.shape[1];A(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),A(mr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),A(hi(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),A(hi(n),()=>"Error in conv2D: Strides should be larger than 0.");let c={x:u,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=O.runKernel(Li,c,h);return p?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Rt=L({conv2d_:gO});function bO(e,t,n,a,r="NWC",s=1,i){let o=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),u=o,p=!1;o.rank===2&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1]])),A(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),A(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Cn("conv1d",a,i),A(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),A(mr(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),A(hi(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),A(hi(n),()=>"Error in conv1D: Stride should be larger than 0."),A(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=W(l,[1,l.shape[0],l.shape[1],l.shape[2]]),c=W(u,[u.shape[0],1,u.shape[1],u.shape[2]]),h=Rt(c,d,[1,n],a,"NHWC",[1,s],i);return p?W(h,[h.shape[2],h.shape[3]]):W(h,[h.shape[0],h.shape[2],h.shape[3]])}var ef=L({conv1d_:bO});function yO(e,t,n,a,r,s="NHWC",i){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),A(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),A(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),A(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let p=s==="NHWC"?o[3]:o[1],d=s==="NHWC"?l.shape[3]:l.shape[1];A(p===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${n.shape[2]}.`),A(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),Cn("conv2dDerInput",r,i);let c={dy:l,filter:n},h={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=O.runKernel(zi,c,h);return u?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var aw=L({conv2DBackpropInput_:yO});function xO(e,t,n,a,r,s){let i=_(e,"x","conv2dTranspose"),o=_(t,"filter","conv2dTranspose");return aw(n,i,o,a,r,"NHWC",s)}var tf=L({conv2dTranspose_:xO});function vO(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=_(e,"x","conv3d"),o=_(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),A(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),A(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),A(mr(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),A(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`),A(hi(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),A(hi(n),()=>"Error in conv3D: Strides should be larger than 0.");let p={x:l,filter:o},d={strides:n,pad:a,dataFormat:r,dilations:s},c=O.runKernel(Wi,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var rw=L({conv3d_:vO});function wO(e,t,n,a,r){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];A(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),A(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),A(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),A(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),A(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let p={dy:i,filter:n},d={pad:r,strides:a,inputShape:s},c=O.runKernel(xu,p,d);return o?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var ON=L({conv3DBackpropInput_:wO});function kO(e,t,n,a,r){let s=_(e,"x","conv3dTranspose"),i=_(t,"filter","conv3dTranspose");return ON(n,s,i,a,r)}var sw=L({conv3dTranspose_:kO});function IO(e){let t={x:_(e,"x","cos","float32")};return O.runKernel(Bi,t)}var cd=L({cos_:IO});function SO(e){let t={x:_(e,"x","cosh","float32")};return O.runKernel(Vi,t)}var nf=L({cosh_:SO});function NO(e,t=0,n=!1,a=!1){let r={x:_(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:a};return O.runKernel(vu,r,s)}var Nc=L({cumprod_:NO});function TO(e,t=0,n=!1,a=!1){let r={x:_(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return O.runKernel(Ui,r,s)}var af=L({cumsum_:TO});function CO(e,t,n,a=!1){let r=_(e,"x","denseBincount"),s=_(t,"weights","denseBincount");A(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),A(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),A(n>=0,()=>`size must be non-negative, but got ${n}.`),A(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:n,binaryOutput:a};return O.runKernel(Bc,i,o)}var dm=L({denseBincount_:CO});function _O(e,t,n="NHWC"){let a=_(e,"x","depthToSpace","float32"),r=n==="NHWC"?a.shape[1]:a.shape[2],s=n==="NHWC"?a.shape[2]:a.shape[3],i=n==="NHWC"?a.shape[3]:a.shape[1];A(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),A(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
    ${r} and ${t}  for depthToSpace with input shape
    ${a.shape}`),A(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
    ${s} and ${t} for depthToSpace with input shape
        ${a.shape}`),A(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:n};return O.runKernel(ku,o,l)}var iw=L({depthToSpace_:_O});function EO(e,t,n,a,r="NHWC",s=[1,1],i){let o=_(e,"x","depthwiseConv2d","float32"),l=_(t,"filter","depthwiseConv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);let d=r==="NHWC"?u.shape[3]:u.shape[1];A(d===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${l.shape[2]}.`),Cn("depthwiseConv2d",a,i);let c={x:u,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=O.runKernel(Gi,c,h);return p?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Es=L({depthwiseConv2d_:EO});function AO(e){let t={x:_(e,"x","diag")};return O.runKernel(Vc,t)}var LN=L({diag_:AO});function FO(e,t,n,a,r=[1,1],s="NHWC"){let i=_(e,"x","dilation2d"),o=_(t,"filter","dilation2d");A(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),A(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),A(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0),A(l.shape[3]===o.shape[2],()=>`Error in dilation2d:  input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`);let p={x:l,filter:o},d={strides:n,pad:a,dilations:r},c=O.runKernel(Hi,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var ow=L({dilation2d_:FO}),pp={};Ee(pp,{assertAndGetBroadcastShape:()=>pt,getBroadcastDims:()=>zN,getReductionAxes:()=>Ut});function zN(e,t){let n=e.length,a=[];for(let r=0;r<n;r++){let s=n-1-r,i=e[s]||1;(t[t.length-1-r]||1)>1&&i===1&&a.unshift(s)}return a}function Ut(e,t){let n=[];for(let a=0;a<t.length;a++){let r=e[e.length-a-1],s=t.length-a-1,i=t[s];(r==null||r===1&&i>1)&&n.unshift(s)}return n}function pt(e,t){let n=Math.max(e.length,t.length),a=new Array(n);for(let r=0;r<n;r++){let s=e[e.length-r-1];s==null&&(s=1);let i=t[t.length-r-1];if(i==null&&(i=1),s===1)a[n-r-1]=i;else if(i===1)a[n-r-1]=s;else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else a[n-r-1]=s}return a}function $O(e,t){let n=_(e,"a","equal","string_or_numeric"),a=_(t,"b","equal","string_or_numeric");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Su,r)}var ta=L({equal_:$O});function DO(e,t,n){let a=_(t,"a","where"),r=_(n,"b","where"),s=_(e,"condition","where","bool"),i=pt(pt(s.shape,a.shape),r.shape),o=ri(s,i),l=ri(a,i),u=ri(r,i),p={condition:o,t:l,e:u};return O.runKernel(Ju,p)}var rn=L({where_:DO});function RO(e){let t={x:_(e,"x","zerosLike")};return O.runKernel(lp,t)}var qe=L({zerosLike_:RO});function MO(e,t){let n=_(e,"a","div"),a=_(t,"b","div");[n,a]=Ft(n,a);let r=he(n,a),s=qe(r),i=ta(a,s);return rn(i,s,r)}var lw=L({divNoNan_:MO});function PO(e,t){let n=_(e,"t1","dot"),a=_(t,"t2","dot");A((n.rank===1||n.rank===2)&&(a.rank===1||a.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${a.rank}.`);let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if(A(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=W(n,[1,-1]),o=W(a,[-1,1]),l=$e(i,o);return W(l,[])}else if(n.rank===1&&a.rank===2){let i=W(n,[1,-1]),o=W(a,[a.shape[0],a.shape[1]]),l=$e(i,o);return W(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=W(a,[-1,1]),o=$e(n,i);return W(o,[o.size])}else{let i=W(a,[a.shape[0],a.shape[1]]);return $e(n,i)}}var uw=L({dot_:PO});function OO(e,...t){let n=t.map((r,s)=>_(r,`tensors${s}`,"einsum")),a={equation:e};return O.runKernel(Bm,n,a)}var WN=L({einsum_:OO});function LO(e){let t={x:_(e,"x","elu","float32")};return O.runKernel(ji,t)}var cp=L({elu_:LO});function zO(e,t){let n=_(e,"x","ensureShape","string_or_numeric");if(!qS(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}var BN=L({ensureShape_:zO});function WO(e){let t=_(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=se(t,"float32"));let n={x:t};return O.runKernel(Ki,n)}var pw=L({erf_:WO});function cw(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function VN(e,t,n){let a=e.length+t.length,r=[],s=0,i=0;for(let o=0;o<a;o++)n.indexOf(o)===-1?r.push(e[s++]):r.push(t[i++]);return r}function UN(e,t){let n=[],a=e.length;for(let s=0;s<a;s++)t.indexOf(s)===-1&&n.push(e[s]);let r=t.map(s=>e[s]);return[n,r]}function fi(e,t){let n=t.map(a=>1);return VN(e,n,t)}function BO(e,t,n){A(cw(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function GN(e,t){if(cw(e,t))return null;let n=[];for(let a=0;a<t;++a)e.indexOf(a)===-1&&n.push(a);return e.forEach(a=>n.push(a)),n}function dw(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function VO(e,t){let n=[];for(let a=t-e;a<t;++a)n.push(a);return n}function UO(e,t=null,n=!1){let a={x:_(e,"x","max")},r={reductionIndices:t,keepDims:n};return O.runKernel(uo,a,r)}var ga=L({max_:UO});function GO(e,t=null,n=!1){let a={x:_(e,"x","min")},r={axis:t,keepDims:n};return O.runKernel(mo,a,r)}var Hl=L({min_:GO});function HO(e,t){let n=_(e,"base","pow"),a=_(t,"exp","pow");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(wo,r)}var Mr=L({pow_:HO});function ve(e,t){if((tn(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&tn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Cs(e,[],[],t)}function qO(e){let t={x:_(e,"x","sqrt","float32")};return O.runKernel(Lo,t)}var mn=L({sqrt_:qO});function jO(e){let t=_(e,"x","square"),n={};return O.runKernel("Square",{x:t},n)}var ut=L({square_:jO});function KO(e,t=null,n=!1){let a=_(e,"x","sum");a.dtype==="bool"&&(a=se(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return O.runKernel(zo,r,s)}var fe=L({sum_:KO});function XO(e,t="euclidean",n=null,a=!1){e=_(e,"x","norm");let r=HN(e,t,n),s=r.shape;if(a){let i=Ra(n,e.shape);s=fi(r.shape,i)}return W(r,s)}function HN(e,t,n=null){if(e.rank===0)return Wt(e);if(e.rank!==1&&n===null)return HN(W(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return fe(Wt(e),n);if(t===1/0)return ga(Wt(e),n);if(t===-1/0)return Hl(Wt(e),n);if(t==="euclidean"||t===2)return mn(fe(Mr(Wt(e),ve(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return ga(fe(Wt(e),n[0]),n[1]-1);if(t===1/0)return ga(fe(Wt(e),n[1]),n[0]);if(t===-1/0)return Hl(fe(Wt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return mn(fe(ut(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var dp=L({norm_:XO});function YO(e,t=null,n=!1){return dp(e,"euclidean",t,n)}var hw=L({euclideanNorm_:YO});function ZO(e){let t={x:_(e,"x","exp")};return O.runKernel(Xi,t)}var yn=L({exp_:ZO});function JO(e,t=0){let n=_(e,"x","expandDims","string_or_numeric");A(t<=n.rank,()=>"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return O.runKernel(Nu,a,r)}var nn=L({expandDims_:JO});function QO(e){let t={x:_(e,"x","expm1")};return O.runKernel(Yi,t)}var mw=L({expm1_:QO});function e3(e,t){let n=_(e,"x","tile","string_or_numeric");A(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let a={x:n},r={reps:t};return O.runKernel(Ns,a,r)}var Ln=L({tile_:e3});function t3(e,t,n,a="float32"){t==null&&(t=e);let r=ze([e,t],a),s=e<=t?e:t;for(let o=0;o<s;++o)r.set(1,o,o);let i=W(r.toTensor(),[e,t]);if(n==null)return i;if(n.length===1)return Ln(nn(i,0),[n[0],1,1]);if(n.length===2)return Ln(nn(nn(i,0),0),[n[0],n[1],1,1]);if(n.length===3)return Ln(nn(nn(nn(i,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}var rf=L({eye_:t3});function n3(e){let t={x:_(e,"x","floor","float32")};return O.runKernel(Zi,t)}var hp=L({floor_:n3});function a3(e,t,n=0,a=0){let r=_(e,"x","gather"),s=_(t,"indices","gather","int32"),i={x:r,indices:s},o={axis:n,batchDims:a};return O.runKernel(Cu,i,o)}var mp=L({gather_:a3});function r3(e,t){let n=_(e,"a","greater","string_or_numeric"),a=_(t,"b","greater","string_or_numeric");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Eu,r)}var _n=L({greater_:r3});function s3(e,t){let n=_(e,"a","greaterEqual","string_or_numeric"),a=_(t,"b","greaterEqual","string_or_numeric");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(eo,r)}var Or=L({greaterEqual_:s3});function i3(e){let t={input:_(e,"input","imag")};return O.runKernel(Gm,t)}var dd=L({imag_:i3});function o3(e){let t={x:_(e,"x","isFinite")};return O.runKernel(no,t)}var fw=L({isFinite_:o3});function l3(e){let t={x:_(e,"x","isInf")};return O.runKernel(ao,t)}var gw=L({isInf_:l3});function u3(e){let t={x:_(e,"x","isNaN")};return O.runKernel(ro,t)}var bw=L({isNaN_:u3});function p3(e,t=.2){let n={x:_(e,"x","leakyRelu")},a={alpha:t};return O.runKernel(so,n,a)}var hd=L({leakyRelu_:p3});function c3(e,t){let n=_(e,"a","less","string_or_numeric"),a=_(t,"b","less","string_or_numeric");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Au,r)}var ql=L({less_:c3});function d3(e,t){let n=_(e,"a","lessEqual","string_or_numeric"),a=_(t,"b","lessEqual","string_or_numeric");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Fu,r)}var As=L({lessEqual_:d3});function qN(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let a={start:e,stop:t,num:n};return O.runKernel($u,{},a)}function h3(e,t=5,n=1,a=1,r=.5){let s=_(e,"x","localResponseNormalization");A(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
               rank ${s.rank}.`),A(Bl(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=W(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:n,alpha:a,beta:r},p=O.runKernel(lo,l,u);return o?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var yw=L({localResponseNormalization_:h3});function m3(e){let t={x:_(e,"x","log","float32")};return O.runKernel(io,t)}var na=L({log_:m3});function f3(e){let t={x:_(e,"x","log1p")};return O.runKernel(oo,t)}var md=L({log1p_:f3});function g3(e){return A(cs(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return O.tidy(()=>{let{value:s,grads:i}=O.gradients(()=>e(a),[a],r);return r!=null&&Tn(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),sf(i),i[0]})}}function b3(e){return A(cs(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=wc(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return O.tidy(()=>{let{value:s,grads:i}=O.gradients(()=>e(...a),a,r);return r!=null&&Tn(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),sf(i),i})}}function y3(e){return A(cs(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof Te,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof Te,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=O.gradients(()=>e(t),[t],n);return sf(a),{grad:a[0],value:r}}}function x3(e){return A(cs(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(r=>r instanceof Te),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof Te,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=O.gradients(()=>e(...t),t,n);return n!=null&&Tn(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),sf(a.grads),a}}function jN(e,t){A(cs(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(u=>u instanceof hs),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in O.registeredVariables)t.push(O.registeredVariables[u])}let a=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),A(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let s=!0,{value:i,grads:o}=O.gradients(e,t,null,s);A(o.some(u=>u!=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()."),A(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,p)=>{o[p]!=null&&(l[u.name]=o[p])}),a!=null&&a.forEach(u=>l[u.name]=null),{value:i,grads:l}}function cr(e){return O.customGrad(e)}function sf(e){if(e.filter(t=>t==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 v3(e){let t={x:_(e,"x","neg")};return O.runKernel(zu,t)}var yt=L({neg_:v3});function w3(e){let t={x:_(e,"x","softplus")};return O.runKernel(Oo,t)}var Ho=L({softplus_:w3});function k3(e){let t=_(e,"x","logSigmoid");return cr(n=>({value:yt(Ho(yt(n))),gradFunc:a=>z(a,fa(yt(n)))}))(t)}var xw=L({logSigmoid_:k3});function I3(e,t){let n=_(e,"a","sub"),a=_(t,"b","sub");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(Vo,r)}var pe=L({sub_:I3});function S3(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return cr((a,r)=>{let s=ga(a,t,!0),i=pe(a,s),o=pe(se(i,"float32"),na(fe(yn(i),t,!0)));return r([o]),{value:o,gradFunc:(l,u)=>{let[p]=u,d=!0,c=yn(p);return pe(l,z(fe(l,t,d),c))}}})(n)}var of=L({logSoftmax_:S3});function N3(e,t=null,n=!1){let a=_(e,"x","logSumExp"),r=Ra(t,a.shape),s=ga(a,r,!0),i=pe(a,s),o=yn(i),l=fe(o,r),u=na(l),p=X(W(s,u.shape),u);if(n){let d=fi(p.shape,r);return W(p,d)}return p}var lf=L({logSumExp_:N3});function T3(e,t){let n=_(e,"a","logicalAnd","bool"),a=_(t,"b","logicalAnd","bool");pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Du,r)}var Da=L({logicalAnd_:T3});function C3(e){let t={x:_(e,"x","logicalNot","bool")};return O.runKernel(Ru,t)}var fd=L({logicalNot_:C3});function _3(e,t){let n=_(e,"a","logicalOr","bool"),a=_(t,"b","logicalOr","bool");pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Mu,r)}var uf=L({logicalOr_:_3});function E3(e,t){let n=_(e,"a","logicalXor","bool"),a=_(t,"b","logicalXor","bool");return pt(n.shape,a.shape),Da(uf(e,t),fd(Da(e,t)))}var vw=L({logicalXor_:E3}),Mh=2147483648;function A3(e,t,n="left"){let a=_(e,"sortedSequence","searchSorted"),r=_(t,"values","searchSorted"),s=a.shape[a.shape.length-1],i=r.shape[r.shape.length-1],o=W(a,[-1,s]),l=W(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(bt(l.shape)>=Mh)throw new Error(`values tensor size must less than ${Mh}`);if(o.shape[1]>=Mh)throw new Error(`trailing dim_size must less than ${Mh} for int32 output type, was ${o.shape[1]}`);let u={sortedSequence:o,values:l},p={side:n};return O.runKernel(Zu,u,p)}var pf=L({searchSorted_:A3});function KN(e,t){return pf(e,t,"left")}function F3(e,t,n,a,r){let s=_(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),A(mr(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),Cn("maxPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=O.runKernel(co,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Mt=L({maxPool_:F3});function $3(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=_(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Cn("maxPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=O.runKernel(Ou,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var ww=L({maxPool3d_:$3});function D3(e,t,n,a,r=!1){let s={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=O.runKernel(qc,s,i);return{result:o[0],indexes:o[1]}}var XN=L({maxPoolWithArgmax_:D3});function R3(e,t){let n=_(e,"a","maximum"),a=_(t,"b","maximum");[n,a]=Ft(n,a),n.dtype==="bool"&&(n=se(n,"int32"),a=se(a,"int32")),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(po,r)}var fr=L({maximum_:R3});function M3(e,t=null,n=!1){let a={x:_(e,"x","mean")},r={axis:t,keepDims:n};return O.runKernel(ho,a,r)}var Et=L({mean_:M3});function Nt(e,t="float32"){if(sa(e),t==="complex64"){let a=Nt(e,"float32"),r=Nt(e,"float32");return Rr(a,r)}let n=Mm(bt(e),t);return O.makeTensor(n,e,t)}function Qn(e,t="float32"){if(sa(e),t==="complex64"){let a=Qn(e,"float32"),r=Nt(e,"float32");return Rr(a,r)}let n=Cv(bt(e),t);return O.makeTensor(n,e,t)}function YN(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let a=_(e,"x","meshgrid",e instanceof Te?e.dtype:"float32");if(t===void 0)return[a];let r=_(t,"y","meshgrid",t instanceof Te?t.dtype:"float32"),s=bt(a.shape),i=bt(r.shape);return n==="xy"?(a=W(a,[1,-1]),r=W(r,[-1,1]),[$e(Qn([i,1],a.dtype),a),$e(r,Qn([1,s],r.dtype))]):(a=W(a,[-1,1]),r=W(r,[1,-1]),[$e(a,Qn([1,i],a.dtype)),$e(Qn([s,1],r.dtype),r)])}function P3(e,t){let n=_(e,"a","minimum"),a=_(t,"b","minimum");[n,a]=Ft(n,a),n.dtype==="bool"&&(n=se(n,"int32"),a=se(a,"int32")),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(fo,r)}var fs=L({minimum_:P3});function O3(e,t,n){A(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=_(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(t.length===a.rank,()=>`Padding doesn't match input. Must be ${a.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let o=0;o<a.rank;o++)A(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(t[o][0]>=0&&t[o][0]<=a.shape[o]-r&&t[o][1]>=0&&t[o][1]<=a.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-r} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:n},i={x:a};return O.runKernel(go,i,s)}var kw=L({mirrorPad_:O3});function L3(e,t){let n=_(e,"a","mod"),a=_(t,"b","mod");[n,a]=Ft(n,a);let r={a:n,b:a};return O.runKernel(bo,r)}var Iw=L({mod_:L3});function z3(e,t=null,n=!1){e=_(e,"x","moments");let a=Ra(t,e.shape),r=Et(e,a,n),s=r.shape;n||(s=fi(r.shape,a));let i=ut(pe(se(e,"float32"),W(r,s))),o=Et(i,a,n);return{mean:r,variance:o}}var gd=L({moments_:z3});function W3(e,t,n,a){let r=_(t,"data","multiRNNCell"),s=wc(n,"c","multiRNNCell"),i=wc(a,"h","multiRNNCell"),o=r,l=[];for(let d=0;d<e.length;d++){let c=e[d](o,s[d],i[d]);l.push(c[0]),l.push(c[1]),o=c[1]}let u=[],p=[];for(let d=0;d<l.length;d+=2)u.push(l[d]),p.push(l[d+1]);return[u,p]}var ZN=L({multiRNNCell_:W3});function B3(e,t,n,a=!1){let r=_(e,"logits","multinomial"),s=r.size,i=r.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}`);n=n||Math.random();let o={logits:i===1?W(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},u=O.runKernel(Lu,o,l);return i===1?W(u,[u.size]):u}var JN=L({multinomial_:B3});function V3(e,t){let n=_(e,"a","notEqual","string_or_numeric"),a=_(t,"b","notEqual","string_or_numeric");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a};return O.runKernel(Wu,r)}var gi=L({notEqual_:V3});function U3(e,t,n=1,a=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let s={indices:_(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:a};return O.runKernel(xo,s,i)}var jl=L({oneHot_:U3});function G3(e){let t={x:_(e,"x","onesLike")};return O.runKernel(Gu,t)}var aa=L({onesLike_:G3});function H3(e,t){let n=_(e,"v1","outerProduct"),a=_(t,"v2","outerProduct");A(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=W(n,[-1,1]),s=W(a,[1,-1]);return $e(r,s)}var QN=L({outerProduct_:H3});function q3(e,t,n=0){let a=_(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},s={x:a};return O.runKernel(vo,s,r)}var va=L({pad_:q3});function j3(e,t,n=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),va(e,[t],n)}var eT=L({pad1d_:j3});function K3(e,t,n=0){return A(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),va(e,t,n)}var tT=L({pad2d_:K3});function X3(e,t,n=0){return A(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."),va(e,t,n)}var nT=L({pad3d_:X3});function Y3(e,t,n=0){return A(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."),va(e,t,n)}var aT=L({pad4d_:Y3});function Z3(e,t,n){let a=_(e,"x","spaceToBatchND");A(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),A(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),A(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+n[l-1][0]+n[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:a},s={blockShape:t,paddings:n};return O.runKernel(ep,r,s)}var bd=L({spaceToBatchND_:Z3});function J3(e,t,n,a,r,s,i){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let o=_(e,"x","maxPool"),l=o,u=!1;o.rank===3&&(u=!0,l=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(mr(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let p=FN(l.shape,t,s,r,a),d=[p.dilationHeight,p.dilationWidth],c;a==="same"?c=eL([p.filterHeight,p.filterWidth],d):c=[[0,0],[0,0]];let h=d[0]===1&&d[1]===1,[m,f]=Q3([p.inHeight,p.inWidth],d,c),g=h?a:"valid",b=h?l:bd(l,d,m),y=(n==="avg"?()=>xa(b,t,s,g,i):()=>Mt(b,t,s,g,i))(),x=h?y:pd(y,d,f);return u?W(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function Q3(e,t,n){let a=n.map(p=>p[0]),r=n.map(p=>p[1]),s=e.concat(a,r),i=t.map((p,d)=>(p-s[d]%p)%p),o=r.map((p,d)=>p+i[d]),l=t.map((p,d)=>[a[d],o[d]]),u=t.map((p,d)=>[0,i[d]]);return[l,u]}function eL(e,t){let n=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),a=n.map(s=>Math.floor(s/2)),r=n.map((s,i)=>s-a[i]);return n.map((s,i)=>[a[i],r[i]])}var Sw=L({pool_:J3});function tL(e,t){let n=_(e,"x","prelu"),a=_(t,"alpha","prelu"),r={x:n,alpha:a};return O.runKernel(ko,r)}var yd=L({prelu_:tL});function nL(e,t=null,n=!1){let a=_(e,"x","prod");a.dtype==="bool"&&(a=se(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return O.runKernel(Io,r,s)}var Nw=L({prod_:nL});function aL(e,t,n,a){let r=e.map((p,d)=>_(p,`tensors${d}`,"raggedGather","int32")),s=_(t,"paramsDenseValues","raggedGather"),i=_(n,"indices","raggedGather","int32"),o={paramsNestedSplits:r,paramsDenseValues:s,indices:i},l={outputRaggedRank:a},u=O.runKernel(Hm,o,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}var rT=L({raggedGather_:aL});function rL(e,t,n){let a=_(e,"starts","raggedRange"),r=_(t,"limits","raggedRange",a.dtype),s=_(n,"deltas","raggedRange",a.dtype),i={starts:a,limits:r,deltas:s},o=O.runKernel(qm,i);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}var sT=L({raggedRange_:rL});function sL(e,t,n,a,r){let s=_(e,"shape","raggedTensorToTensor","int32"),i=_(t,"values","raggedTensorToTensor"),o=_(n,"defaultValue","raggedTensorToTensor",i.dtype),l=a.map((d,c)=>_(d,`tensors${c}`,"raggedTensorToTensor","int32")),u={shape:s,values:i,defaultValue:o,rowPartitionTensors:l},p={rowPartitionTypes:r};return O.runKernel(jm,u,p)}var iT=L({raggedTensorToTensor_:sL});function iL(e,t,n){sa(e);let a=bt(e),r=null;if(n==null||n==="float32")r=new Float32Array(a);else if(n==="int32")r=new Int32Array(a);else if(n==="bool")r=new Uint8Array(a);else throw new Error(`Unknown data type ${n}`);for(let s=0;s<a;s++)r[s]=t();return O.makeTensor(r,e,n)}var oT=L({rand_:iL}),Tw=ks(Dm()),lT={};Ee(lT,{TEST_EPSILON_FLOAT16:()=>uT,createVideoElement:()=>mL,encodeStrings:()=>pT,expectArrayBuffersEqual:()=>hL,expectArraysClose:()=>lL,expectArraysEqual:()=>pL,expectNumbersClose:()=>cL,expectPromiseToFail:()=>uL,expectValuesInRange:()=>dL,play:()=>fL,testEpsilon:()=>Cw});var oL=.001,uT=.1;function lL(e,t,n){return n==null&&(n=Cw()),zx(e,t,(a,r)=>_w(a,r,n))}function Cw(){return O.backend.floatPrecision()===32?oL:uT}function zx(e,t,n){let a=!0;if((tn(e)||tn(t))&&(a=!1),tn(e)&&tn(t)&&(a=!0),a){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=pr(e),o=pr(t);if(!Pr(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=tn(e)?e:ds(e),s=tn(t)?t:ds(t);if(r.length!==s.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${s.length}.
Actual:   ${r}.
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=r[i],l=s[i];if(!n(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
Actual:   ${r}.
Expected: ${s}.`)}typeof expect!="undefined"&&expect().nothing()}function uL(e,t){e().then(()=>t.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function pL(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return rs(e)||rs(e[0])||rs(t)||rs(t[0])?zx(e,n,(a,r)=>a==r):zx(e,t,(a,r)=>_w(a,r,0))}function cL(e,t,n){if(n==null&&(n=Cw()),!_w(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function _w(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function dL(e,t,n){for(let a=0;a<e.length;a++)if(e[a]<t||e[a]>n)throw new Error(`Value out of range:${e[a]} low: ${t}, high: ${n}`)}function hL(e,t){let n=new Float32Array(e),a=new Float32Array(t);if(n.length!==a.length)throw new Error(`Expected ArrayBuffer to be of length ${a.length}, but it was ${n.length}`);for(let r=0;r<a.length;r++)if(n[r]!==a[r])throw new Error(`Expected ArrayBuffer value at ${r} to be ${a[r]} but got ${n[r]} instead`)}function pT(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?pT(n):e[t]=id(n)}return e}function mL(e){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(e),new Promise(n=>{t.addEventListener("loadeddata",a=>n(t)),t.load()})}async function fL(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var Ew=class{constructor(e,t,n,a,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=a,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=r||Math.random();this.random=Tw.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let a=this.nextVal;return this.nextVal=NaN,a}let e,t,n=!1;for(;!n;){let a,r,s;do a=2*this.random()-1,r=2*this.random()-1,s=a*a+r*r;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*r*i,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},gL=class{constructor(e,t,n,a){this.alpha=e,this.beta=1/t,this.dtype=n;let r=a||Math.random();this.randu=Tw.alea(r.toString()),this.randn=new Ew(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,a,r,s;for(;;){do a=this.randn.nextValue(),s=1+this.c*a;while(s<=0);if(s*=s*s,e=a*a,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),r=this.randu(),r<t||Math.log(r)<n)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},bL=class{constructor(e=0,t=1,n,a){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Tw.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function yL(e,t,n=1,a="float32",r){if(sa(e),n==null&&(n=1),a==null&&(a="float32"),a!=="float32"&&a!=="int32")throw new Error(`Unsupported data type ${a}`);let s=new gL(t,n,a,r),i=ze(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var cT=L({randomGamma_:yL});function xL(e,t=0,n=1,a,r){if(sa(e),a!=null&&a==="bool")throw new Error(`Unsupported data type ${a}`);let s=new Ew(t,n,a,!1,r),i=ze(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var cf=L({randomNormal_:xL});function vL(e,t,n){if(t!=null&&t==="bool")throw new Error(`Unsupported data type ${t}`);return cf(e,0,1,t,n)}var dT=L({randomStandardNormal_:vL});function wL(e,t=0,n=1,a="float32",r){sa(e);let s=ze(e,a),i=new bL(t,n,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Fs=L({randomUniform_:wL});function kL(e,t,n,a){return Fs(e,t,n,"int32",a)}var hT=L({randomUniformInt_:kL});function bi(e,t,n=1,a="float32"){if(n===0)throw new Error("Cannot have a step of zero");let r={start:e,stop:t,step:n,dtype:a};return O.runKernel(jc,{},r)}function IL(e){let t={input:_(e,"input","real")};return O.runKernel(Km,t)}var Kl=L({real_:IL});function SL(e){let t={x:_(e,"x","reciprocal")};return O.runKernel(So,t)}var Aw=L({reciprocal_:SL});function NL(e){let t={x:_(e,"x","relu")};return O.runKernel(No,t)}var Ke=L({relu_:NL});function TL(e){let t={x:_(e,"x","relu6")};return O.runKernel(_o,t)}var df=L({relu6_:TL});function CL(e,t){let n={x:_(e,"x","reverse")},a={dims:t};return O.runKernel(Eo,n,a)}var ya=L({reverse_:CL});function _L(e){let t=_(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),ya(t,0)}var mT=L({reverse1d_:_L});function EL(e,t){let n=_(e,"x","reverse");return A(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),ya(n,t)}var fT=L({reverse2d_:EL});function AL(e,t){let n=_(e,"x","reverse");return A(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),ya(n,t)}var gT=L({reverse3d_:AL});function FL(e,t){let n=_(e,"x","reverse");return A(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),ya(n,t)}var bT=L({reverse4d_:FL});function $L(e){let t={x:_(e,"x","round")};return O.runKernel(Ao,t)}var hf=L({round_:$L});function DL(e){let t={x:_(e,"x","rsqrt","float32")};return O.runKernel(Fo,t)}var mf=L({rsqrt_:DL});function RL(e){let t={x:_(e,"x","selu")};return O.runKernel($o,t)}var ff=L({selu_:RL});function ML(e,t,n,a,r,s=[1,1],i="NHWC"){let o=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),u=_(n,"pointwiseFilter","separableConv2d"),p=o,d=!1;if(o.rank===3&&(d=!0,p=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");A(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),A(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),A(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${u.shape[0]}.`),A(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let c=l.shape[2],h=l.shape[3];A(u.shape[2]===c*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${c*h}, but got ${u.shape[2]}.`);let m=Es(p,l,a,r,i,s),f=Rt(m,u,1,"valid",i);return d?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var $s=L({separableConv2d_:ML});async function PL(e,t){let n=_(e,"x","setdiff1d"),a=_(t,"y","setdiff1d");A(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),A(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),A(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let r=await n.data(),s=await a.data(),i=new Set(s),o=0;for(let p=0;p<r.length;p++)i.has(r[p])||o++;let l=new Vt([o],n.dtype),u=new Vt([o],"int32");for(let p=0,d=0;p<r.length;p++)i.has(r[p])||(l.values[d]=r[p],u.values[d]=p,d++);return[l.toTensor(),u.toTensor()]}var yT=PL;function OL(e){let t={x:_(e,"x","sign")};return O.runKernel(Mo,t)}var Fw=L({sign_:OL});function LL(e){let t={x:_(e,"x","sin","float32")};return O.runKernel(Do,t)}var gf=L({sin_:LL});function zL(e){let t={x:_(e,"x","sinh")};return O.runKernel(Ro,t)}var bf=L({sinh_:zL});function WL(e,t,n){let a=_(e,"x","slice1d");return A(a.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),Ue(a,[t],[n])}var xd=L({slice1d_:WL});function BL(e,t,n){let a=_(e,"x","slice2d");return A(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),Ue(a,t,n)}var yf=L({slice2d_:BL});function VL(e,t,n){let a=_(e,"x","slice3d");return A(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),Ue(a,t,n)}var qo=L({slice3d_:VL});function UL(e,t,n){let a=_(e,"x","slice4d");return A(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),Ue(a,t,n)}var Xl=L({slice4d_:UL});function GL(e,t=-1){let n=_(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let a={logits:n},r={dim:t};return O.runKernel(Wo,a,r)}var Xa=L({softmax_:GL});function HL(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return O.runKernel(Vm,t)}var vd=L({fft_:HL});function qL(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return O.runKernel(Um,t)}var Yl=L({ifft_:qL});function jL(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=W(e,[n,t]);a=Yl(r)}else{let r=[n,2*(t-1)],s=W(Kl(e),[n,t]),i=W(dd(e),[n,t]),o=ya(Ue(s,[0,1],[n,t-2]),1),l=z(ya(Ue(i,[0,1],[n,t-2]),1),ve(-1)),u=et([s,o],1),p=et([i,l],1),d=W(Rr(u,p),[r[0],r[1]]);a=Yl(d)}if(a=Kl(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=W(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var xf=L({irfft_:jL});function KL(e,t,n=0){let a={x:_(e,"x","split")},r={numOrSizeSplits:t,axis:n};return O.runKernel(tp,a,r)}var zn=L({split_:KL});function XL(e,t){A(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],a=e.size/n,r;if(t!=null&&t<n){let m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=Ue(e,m,f),n=t}else if(t!=null&&t>n){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-n,r=et([e,Nt(m)],e.shape.length-1),n=t}else r=e;let s=qe(r),i=W(Rr(r,s),[a,n]),o=vd(i),l=Math.floor(n/2)+1,u=Kl(o),p=dd(o),d=zn(u,[l,n-l],u.shape.length-1),c=zn(p,[l,n-l],p.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,W(Rr(d[0],c[0]),h)}var wd=L({rfft_:XL});function YL(e,t){let n=_(e,"a","squaredDifference"),a=_(t,"b","squaredDifference");[n,a]=Ft(n,a),pt(n.shape,a.shape);let r={a:n,b:a},s={};return O.runKernel(Bo,r,s)}var vf=L({squaredDifference_:YL});function ZL(e,t){let n=_(e,"x","squeeze","string_or_numeric");return W(n,jS(n.shape,t).newShape)}var Ds=L({squeeze_:ZL});function JL(e,t=0){let n=wc(e,"tensors","stack","string_or_numeric");A(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&A(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return O.runKernel(Hu,a,r)}var Dt=L({stack_:JL});function QL(e,t=0){let n={x:_(e,"x","step")},a={alpha:t};return O.runKernel(Ts,n,a)}var jo=L({step_:QL});function ez(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let u={x:_(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return O.runKernel(rp,u,p)}var $w=L({stridedSlice_:ez});function tz(e){let t={x:_(e,"x","tan","float32")};return O.runKernel(Uo,t)}var Dw=L({tan_:tz});function je(e,t){Ni(e);let n=pr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Cs(e,null,n,t)}function $a(e,t,n){if(Ni(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=pr(e,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Cs(e,t,a,n)}function kd(e,t,n){if(Ni(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=pr(e,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Cs(e,t,a,n)}function Ma(e,t,n){if(Ni(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=pr(e,n);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Cs(e,t,a,n)}function xT(e,t,n){if(Ni(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=pr(e,n);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Cs(e,t,a,n)}function vT(e,t,n){if(Ni(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=pr(e,n);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||a,Cs(e,t,a,n)}var wf={};Ee(wf,{calculateShapes:()=>wT,validateInput:()=>kf,validateUpdateShape:()=>Rw});function Rw(e,t,n){let a=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${a}, and batchDim: ${r}.`;if(n.rank<r)throw new Error(s+` update.rank < ${r}. `);if(e.length<a+(n.rank-r))throw new Error(s+` Output shape length < ${a+(n.rank-r)}`);if(n.rank!==r+e.length-a)throw new Error(s+` update.rank != ${r+e.length-a}`);for(let i=0;i<r;++i)if(n.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${n.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<n.rank-r;++i)if(n.shape[i+r]!==e[i+a])throw new Error(s+` updates.shape[${i+r}] (${n.shape[i+r]}) != shape[${i+r}] (${e[i+r]})`)}function kf(e,t,n){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(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Rw(n,t,e)}function wT(e,t,n){let a=t.shape.length,r=a>1?t.shape[a-1]:1,s=n.length,i=1;for(let d=r;d<s;++d)i*=n[d];let o=r<1?1:r,l=bt(t.shape)/o,u=[...ou(n.slice(0,r)),1],p=bt(n);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:u,outputSize:p}}function nz(e,t,n){let a=_(e,"tensor","tensorScatterupdate"),r=_(t,"indices","tensorScatterupdate","int32"),s=_(n,"updates","tensorScatterupdate");if(kf(s,r,a.shape),a.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${a.dtype} and ${s.dtype}.`);let i={tensor:a,indices:r,updates:s},o={};return O.runKernel(Yu,i,o)}var kT=L({tensorScatterUpdate_:nz});function az(e,t=1,n=!0){let a=_(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=a.shape[a.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let s={x:a},i={k:t,sorted:n},[o,l]=O.runKernel(sp,s,i);return{values:o,indices:l}}var Mw=L({topk_:az});function rz(e,t=0,n=1,a,r){if(sa(e),a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Ew(t,n,a,!0,r),i=ze(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var If=L({truncatedNormal_:rz});function sz(e,t=0){let n=_(e,"x","unique","string_or_numeric");A(n.rank>0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=O.runKernel(nd,a,r);return{values:s,indices:i}}var Pw=L({unique_:sz});function iz(e,t,n){let a=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");A(Bl(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return O.runKernel(ad,s,i)}var Sf=L({unsortedSegmentSum_:iz});function oz(e,t=0){let n=_(e,"x","unstack","string_or_numeric");A(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return O.runKernel(op,a,r)}var ct=L({unstack_:oz});function IT(e,t){return pf(e,t,"right")}function Ow(e,t=!0,n,a){return O.makeVariable(e,t,n,a)}function ST(e,t){let n=[];for(let s=0;s<t.length;s++)t[s]&&n.push(s);let a=ze(e,"int32"),r=ze([n.length,e.length],"int32");for(let s=0;s<n.length;s++){let i=a.indexToLoc(n[s]),o=s*e.length;r.values.set(i,o)}return r.toTensor()}async function lz(e){let t=_(e,"condition","whereAsync","bool"),n=await t.data(),a=ST(t.shape,n);return e!==t&&t.dispose(),a}var Lw=lz;async function uz(e,t,n){let a=_(e,"tensor","boolMask"),r=_(t,"mask","boolMask","bool"),s=n==null?0:n,i=r.rank,o=a.shape;A(i>0,()=>"mask cannot be scalar"),Tn(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f<s+i;f++)l*=o[f];let u=o.slice(0,s).concat([l],o.slice(s+i)),p=W(a,u),d=W(r,[-1]),c=await Lw(d),h=Ds(c,[1]),m=mp(p,h,s);return e!==a&&a.dispose(),t!==r&&r.dispose(),h.dispose(),p.dispose(),d.dispose(),c.dispose(),m}var NT=uz;function pz(e,t,n){let a=_(e,"x","transpose");if(t==null&&(t=a.shape.map((i,o)=>o).reverse()),A(a.rank===t.length,()=>`Error in transpose: rank of input ${a.rank} must match length of perm ${t}.`),t.forEach(i=>{A(i>=0&&i<a.rank,()=>`All entries in 'perm' must be between 0 and ${a.rank-1} but got ${t}`)}),a.rank<=1)return a.clone();let r={x:a},s={perm:t};return a.dtype==="complex64"?P(()=>{let i=Kl(a),o=dd(a);return i=O.runKernel($r,{x:i},s),o=O.runKernel($r,{x:o},s),n&&(o=yt(o)),Rr(i,o)}):O.runKernel($r,r,s)}var De=L({transpose_:pz});function cz(e,t,n,a,r=!0){let s=_(e,"v","movingAverage"),i=_(t,"x","movingAverage"),o=_(n,"decay","movingAverage");hN(s,i),A(Pr(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=ve(1),u=pe(l,o),p=z(pe(i,s),u);if(r){A(a!=null,()=>"When using zeroDebias: true, step is required.");let d=_(a,"step","movingAverage");p=he(p,pe(l,Mr(o,d)))}return X(s,p)}var TT=L({movingAverage_:cz});function dz(e,t,n){sa(n);let a=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");kf(r,a,n);let s={indices:a,updates:r},i={shape:n};return O.runKernel(Xu,s,i)}var CT=L({scatterND_:dz});function hz(e,t,n,a){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function mz(e,t,n,a=0){sa(n);let r=_(e,"sparseIndices","sparseToDense","int32"),s=_(t,"sparseValues","sparseToDense","string_or_numeric"),i=_(a,"defaultValue","sparseToDense",s.dtype);hz(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return O.runKernel(ap,o,l)}var _T=L({sparseToDense_:mz});function fz(e,t){let n=_(t,"indices","gatherND","int32"),a={params:_(e,"x","gatherND","string_or_numeric"),indices:n};return O.runKernel(_u,a)}var ET=L({gatherND_:fz});function gz(e,t){if(t==null)return e.shape.slice();if(Pr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let a=0;a<e.shape.length;a++)t[a]==null&&e.shape[a]!=null?n.push(e.shape[a]):n.push(t[a]);return n}return t}function bz(e,t,n,a){let r=_(e,"x","dropout");if(A(r.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),A(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Te?r.clone():r;let s=gz(r,n),i=1-t,o=he(hp(X(Fs(s,0,1,"float32",a),i)),i);return z(r,o)}var zw=L({dropout_:bz});function Ww(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Nf(e,t,n){let a=1-e%2,r=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+a-1);r[s]=t-n*Math.cos(i)}return je(r,"float32")}async function yz(e,t,n=1){let a=_(e,"predictions","inTopK"),r=_(t,"targets","inTopK");A(a.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),A(a.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${a.rank} and targets rank ${r.rank}`),Tn(a.shape.slice(0,a.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=a.shape[a.shape.length-1];A(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);let i=await a.data(),o=await r.data(),[l,u]=[i.length/s,s],p=KS("bool",l);for(let d=0;d<l;d++){let c=d*u,h=i.subarray(c,c+u),m=[];for(let f=0;f<h.length;f++)m.push({value:h[f],index:f});m.sort((f,g)=>g.value-f.value),p[d]=0;for(let f=0;f<n;f++)if(m[f].index===o[d]){p[d]=1;break}}return e!==a&&a.dispose(),t!==r&&r.dispose(),bn(p,r.shape,"bool")}var AT=yz,Zl={};Ee(Zl,{conv2d:()=>wz,depthwiseConv2d:()=>Nz,matMul:()=>Cz});function xz(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]])),A(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),A(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),A(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],p=s==="NHWC"?l.shape[3]:l.shape[1];A(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),A(p===n[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${n[3]}).`),Cn("conv2dDerFilter",r,i);let d={x:o,dy:l},c={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return O.runKernel(Lm,d,c)}var Bw=L({conv2DBackpropFilter_:xz});function Tf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return z(e,jo(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Cf(e,t){let n=t,a=Ut(e.shape,t.shape);return a.length>0&&(n=fe(n,a)),W(n,e.shape)}function _f(e,t,n,a){if(t==="linear")return e;if(t==="relu")return Ke(e);if(t==="elu")return cp(e);if(t==="relu6")return df(e);if(t==="prelu")return yd(e,n);if(t==="leakyrelu")return hd(e,a);if(t==="sigmoid")return fa(e);throw new Error(`Unknown fused activation ${t}.`)}var Ef=(e,t)=>!(e>0)||t==="linear";function vz({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(l=l||"linear",Ef(O.state.gradientDepth,l)===!1){A(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let T=Rt(e,t,n,a,r,s,i);return o!=null&&(T=X(T,o)),_f(T,l,u,p)}let d=_(e,"x","conv2d","float32"),c=_(t,"filter","conv2d","float32"),h=d,m=!1;d.rank===3&&(m=!0,h=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),A(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),A(c.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${c.rank}.`),Cn("fused conv2d",a,i);let f=r==="NHWC"?h.shape[3]:h.shape[1];A(c.shape[2]===f,()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${c.shape[2]}.`),A(mr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let g=ud(h.shape,c.shape,n,s,a,i),b;o!=null&&(b=_(o,"bias","fused conv2d"),[b]=Ft(b,d),r==="NHWC"?pt(g.outShape,b.shape):(A(b.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`),A(b.shape.length===0||b.shape[0]===g.outChannels||b.shape[0]===1,()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let y;if(u!=null){let T=u.shape;if(A(T.length<=1||T.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-${T.length}.`),T.length===1)A(T[0]===1||T[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${T}) is not compatible with the number of output channels (${g.outChannels}).`);else if(T.length===3)try{pt(T,g.outShape)}catch(C){let E=`Error in fused conv2d: PReLU activation weights (${T}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(E)}y=_(u,"prelu weights","fused conv2d")}let x=(T,C)=>{A(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);let[E,F,D,$]=C,S=Tf(T,D,l);A(ms(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let M=aw(F.shape,S,E,n,a),B=Bw(F,S,E.shape,n,a),U=[M,B];if($!=null){let H=Cf($,S);U.push(H)}return U},v={x:h,filter:c,bias:b,preluActivationWeights:y},I={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?cr((T,C,E)=>{let F=O.runKernel(li,v,I);return E([C,T,F]),m&&(F=W(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:x}})(h,c):cr((T,C,E,F)=>{let D=O.runKernel(li,v,I);return F([C,T,D,E]),m&&(D=W(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:x}})(h,c,b)}var wz=L({fusedConv2d_:vz});function kz(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},p={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return O.runKernel(zm,u,p)}var FT=L({depthwiseConv2dNativeBackpropFilter_:kz});function Iz(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:n},p={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},d=O.runKernel(Wm,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var $T=L({depthwiseConv2dNativeBackpropInput_:Iz});function Sz({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(Ef(O.state.gradientDepth,l)===!1){let I=Es(e,t,n,a,r,s,i);return o!=null&&(I=X(I,o)),_f(I,l,u,p)}let d=_(e,"x","depthwiseConv2d","float32"),c=_(t,"filter","depthwiseConv2d","float32"),h=d,m=!1;d.rank===3&&(m=!0,h=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),A(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),A(c.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),A(h.shape[3]===c.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),s==null&&(s=[1,1]),A(mr(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),Cn("fused depthwiseConv2d",a,i);let f=ud(h.shape,c.shape,n,s,a,i,!0),g;o!=null&&(g=_(o,"bias","fused conv2d"),[g]=Ft(g,d),pt(f.outShape,g.shape));let b;u!=null&&(b=_(u,"prelu weights","fused depthwiseConv2d"));let y=(I,T)=>{A(ms(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,E,F,D]=T,$=Tf(I,F,l),S=$T(E.shape,$,C,n,a,s,i),M=FT(E,$,C.shape,n,a,s,i);if(D!=null){let B=Cf(g,$);return[S,M,B]}return[S,M]},x={x:h,filter:c,bias:g,preluActivationWeights:b},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?cr((I,T,C)=>{let E=O.runKernel(ui,x,v);return C([T,I,E]),m&&(E=W(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:y}})(h,c):cr((I,T,C,E)=>{let F=O.runKernel(ui,x,v);return E([T,I,F,C]),m&&(F=W(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,c,g)}var Nz=L({fusedDepthwiseConv2d_:Sz});function Tz({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(Ef(O.state.gradientDepth,s)===!1){let D=$e(e,t,n,a);return r!=null&&(D=X(D,r)),_f(D,s,i,o)}let l=_(e,"a","fused matMul"),u=_(t,"b","fused matMul");[l,u]=Ft(l,u);let p=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=a?u.shape[u.rank-1]:u.shape[u.rank-2],c=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=a?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=bt(m),b=bt(f);A(p===d,()=>`Error in fused matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${a} must match.`);let y=pt(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([c,h]),x=n?W(l,[g,p,c]):W(l,[g,c,p]),v=a?W(u,[b,h,d]):W(u,[b,d,h]),I;r!=null&&(I=_(r,"bias","fused matMul"),[I]=Ft(I,l),pt(y,I.shape));let T;i!=null&&(T=_(i,"prelu weights","fused matMul"));let C=(D,$)=>{let[S,M,B,U]=$,H=Tf(W(D,B.shape),B,s),j,K;if(!n&&!a?(j=$e(H,M,!1,!0),K=$e(S,H,!0,!1)):!n&&a?(j=$e(H,M,!1,!1),K=$e(H,S,!0,!1)):n&&!a?(j=$e(M,H,!1,!0),K=$e(S,H,!1,!1)):(j=$e(M,H,!0,!0),K=$e(H,S,!0,!0)),r!=null){let Z=Cf(U,H);return[j,K,Z]}else return[j,K]},E={a:x,b:v,bias:I,preluActivationWeights:T},F={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?cr((D,$,S)=>{let M=O.runKernel(oi,E,F);return S([D,$,M]),{value:W(M,y),gradFunc:C}})(x,v):cr((D,$,S,M)=>{let B=O.runKernel(oi,E,F);return M([D,$,B,S]),{value:W(B,y),gradFunc:C}})(x,v,I)}var Cz=L({fusedMatMul_:Tz});function _z(e){return Nf(e,.54,.46)}var Ez=L({hammingWindow_:_z});function Az(e){return Nf(e,.5,.5)}var DT=L({hannWindow_:Az});function Fz(e,t,n,a=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Ue(e,s,t)),s+=n;if(a)for(;s<e.size;){let o=s+t-e.size,l=et([Ue(e,s,t-o),xn([o],r)]);i.push(l),s+=n}return i.length===0?$a([],[0,t]):W(et(i),[i.length,t])}var RT=L({frame_:Fz});function $z(e,t,n,a,r=DT){a==null&&(a=Ww(t));let s=RT(e,t,n),i=z(s,r(t));return wd(i,a)}var Dz=L({stft_:$z});function Rz(e,t,n,a,r="bilinear",s=0){let i=_(e,"image","cropAndResize"),o=_(t,"boxes","cropAndResize","float32"),l=_(n,"boxInd","cropAndResize","int32"),u=o.shape[0];A(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),A(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),A(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),A(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),A(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let p={image:i,boxes:o,boxInd:l},d={method:r,extrapolationValue:s,cropSize:a};return O.runKernel(wu,p,d)}var Mz=L({cropAndResize_:Rz});function Pz(e){let t=_(e,"image","flipLeftRight","float32");A(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return O.runKernel(Tu,n,{})}var Oz=L({flipLeftRight_:Pz});function Lz(e){let t=_(e,"image","grayscaleToRGB"),n=t.rank-1,a=t.shape[n];A(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),A(a===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${a}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Ln(t,r)}var zz=L({grayscaleToRGB_:Lz});function Wz(e,t,n=0,a=.5){let r=_(e,"image","rotateWithOffset","float32");A(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:n,center:a};return O.runKernel(up,s,i)}var Bz=L({rotateWithOffset_:Wz});function fp(e,t,n,a,r,s){a==null&&(a=.5),r==null&&(r=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return n=Math.min(n,i),A(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),A(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),A(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),A(t.rank===1,()=>"scores must be a 1D tensor"),A(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),A(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function Vz(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=_(e,"boxes","nonMaxSuppression","float32"),i=_(t,"scores","nonMaxSuppression","float32"),o=fp(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return O.runKernel(Bu,{boxes:s,scores:i},l)}var Uz=L({nonMaxSuppression_:Vz});function Gz(e,t,n){let a=Hz(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function Hz(e,t,n){return jz(e,t,n||qz)}function qz(e,t){return e>t?1:e<t?-1:0}function jz(e,t,n){let a=0,r=e.length,s=0,i=!1;for(;a<r;){s=a+(r-a>>>1);let o=n(t,e[s]);o>0?a=s+1:(r=s,i=!o)}return i?a:-a-1}function MT(e,t,n,a,r){return Vw(e,t,n,a,r,0)}function PT(e,t,n,a,r,s){return Vw(e,t,n,a,r,0,!1,s,!0)}function OT(e,t,n,a,r,s){return Vw(e,t,n,a,r,s,!0)}function Vw(e,t,n,a,r,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;g<t.length;g++)t[g]>r&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(mI);let p=s>0?-.5/s:0,d=[],c=[];for(;d.length<n&&u.length>0;){let g=u.pop(),{score:b,boxIndex:y,suppressBeginIndex:x}=g;if(b<r)break;let v=!1;for(let I=d.length-1;I>=x;--I){let T=Kz(e,y,d[I]);if(T>=a){v=!0;break}if(g.score=g.score*Xz(a,p,T),g.score<=r)break}g.suppressBeginIndex=d.length,v||(g.score===b?(d.push(y),c.push(g.score)):g.score>r&&Gz(u,g,mI))}let h=d.length,m=n-h;o&&m>0&&(d.push(...new Array(m).fill(0)),c.push(...new Array(m).fill(0)));let f={selectedIndices:d};return i&&(f.selectedScores=c),l&&(f.validOutputs=h),f}function Kz(e,t,n){let a=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),s=Math.min(a[0],a[2]),i=Math.min(a[1],a[3]),o=Math.max(a[0],a[2]),l=Math.max(a[1],a[3]),u=Math.min(r[0],r[2]),p=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),h=(o-s)*(l-i),m=(d-u)*(c-p);if(h<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,p),b=Math.min(o,d),y=Math.min(l,c),x=Math.max(b-f,0)*Math.max(y-g,0);return x/(h+m-x)}function Xz(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function mI(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function Yz(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),o=fp(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],p=l[1],{selectedIndices:d}=MT(u,p,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),je(d,"int32")}var Zz=Yz;function Jz(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),l=fp(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},p={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},d=O.runKernel(Uu,u,p);return{selectedIndices:d[0],selectedScores:d[1]}}var Qz=L({nonMaxSuppressionWithScore_:Jz});async function eW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),l=fp(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),p=u[0],d=u[1],{selectedIndices:c,selectedScores:h}=OT(p,d,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:je(c,"int32"),selectedScores:je(h)}}var tW=eW;function nW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),l=fp(i,o,n,a,r,null),u=l.maxOutputSize,p=l.iouThreshold,d=l.scoreThreshold,c={boxes:i,scores:o},h={maxOutputSize:u,iouThreshold:p,scoreThreshold:d,padToMaxOutputSize:s},m=O.runKernel(Vu,c,h);return{selectedIndices:m[0],validOutputs:m[1]}}var aW=L({nonMaxSuppressionPadded_:nW});async function rW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),l=fp(i,o,n,a,r,null),u=l.maxOutputSize,p=l.iouThreshold,d=l.scoreThreshold,[c,h]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=PT(c,h,u,p,d,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:je(m,"int32"),validOutputs:ve(f,"int32")}}var sW=rW;function iW(e,t,n=!1,a=!1){let r=_(e,"images","resizeBilinear");A(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),A(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),A(a===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=O.runKernel(Co,o,l);return i?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var LT=L({resizeBilinear_:iW});function oW(e,t,n=!1,a=!1){let r=_(e,"images","resizeNearestNeighbor");A(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),A(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),A(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),A(a===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=O.runKernel(To,o,l);return i?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var zT=L({resizeNearestNeighbor_:oW});function lW(e,t="binary",n=!1,a=.5){let r=_(e,"image","threshold"),s=.2989,i=.587,o=.114,l=r.shape[0]*r.shape[1],u=z(je([a]),255),p,d,c,h;if(A(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),A(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),A(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),A(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[p,d,c]=zn(r,[1,1,1],-1);let f=z(p,s),g=z(d,i),b=z(c,o);h=X(X(f,g),b)}else h=e;if(t==="otsu"){let f=Zv(se(hf(h),"int32"),bn([]),256);u=uW(f,l)}let m=n?As(h,u):_n(h,u);return se(z(m,255),"int32")}function uW(e,t){let n=je([-1]),a=je([0]),r=je([0]),s,i,o,l,u,p;for(let d=0;d<e.size-1;d++){s=Ue(e,0,d+1),i=Ue(e,d+1),u=he(fe(s),t),p=he(fe(i),t);let c=fe(z(s,bi(0,s.size)));o=he(c,fe(s));let h=xn(i.shape,s.size),m=X(bi(0,i.size),h),f=z(i,m);l=he(fe(f),fe(i));let g=pe(o,l),b=pe(o,l),y=z(u,p);r=z(z(y,g),b);let x=_n(r,a);a=rn(x,r,a),n=rn(x,je([d]),n)}return n}var pW=L({threshold_:lW});function cW(e,t,n="nearest",a="constant",r=0,s){let i=_(e,"image","transform","float32"),o=_(t,"transforms","transform","float32");A(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),A(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:n,fillMode:a,fillValue:r,outputShape:s};return O.runKernel(ip,l,u)}var dW=L({transform_:cW});function hW(e,t,n){let a=_(e,"a","bandPart");A(a.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${a.rank}.`);let r=a.shape,[s,i]=a.shape.slice(-2),o,l;typeof t=="number"?(A(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),A(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),o=_(t<0?s:t,"numLower","bandPart")):(A(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),o=rn(ql(t,0),s,fs(t,s))),typeof n=="number"?(A(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`),A(n<=i,()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`),l=_(n<0?i:n,"numUpper","bandPart")):(A(n.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=rn(ql(n,0),i,fs(n,i)));let u=W(bi(0,s,1,"int32"),[-1,1]),p=bi(0,i,1,"int32"),d=pe(u,p),c=Da(As(d,o),Or(d,yt(l))),h=Nt([s,i],a.dtype);return W(Dt(ct(W(a,[-1,s,i])).map(m=>rn(c,m,h))),r)}var mW=L({bandPart_:hW});function fW(e){let t;if(Array.isArray(e)){t=!1,A(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let s=1;s<e.length;++s)A(e[s].shape[0]===r,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=zn(e,e.shape[0],0).map(r=>Ds(r,[0]));A(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],a=e;for(let r=0;r<e.length;++r)n.push(O.tidy(()=>{let s=a[r];if(r>0)for(let i=0;i<r;++i){let o=z(fe(z(n[i],s)),n[i]);s=pe(s,o)}return he(s,dp(s,"euclidean"))}));return t?Dt(n,0):n}var gW=L({gramSchmidt_:fW});function bW(e,t=!1){if(A(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return fI(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),a=ct(W(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[u,p]=fI(l,t);r.push(u),s.push(p)});let i=W(Dt(r,0),e.shape),o=W(Dt(s,0),e.shape);return[i,o]}}function fI(e,t=!1){return O.tidy(()=>{A(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],a=e.shape[1],r=rf(n),s=or(e),i=$a([[1]],[1,1]),o=or(i),l=n>=a?a:n;for(let u=0;u<l;++u){let p=s,d=o,c=r;[o,s,r]=O.tidy(()=>{let h=Ue(s,[u,u],[n-u,1]),m=dp(h),f=Ue(s,[u,u],[1,1]),g=rn(_n(f,0),$a([[-1]]),$a([[1]])),b=pe(f,z(g,m)),y=he(h,b);y.shape[0]===1?o=or(i):o=et([i,Ue(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=yt(he($e(g,b),m)),v=Ue(s,[u,0],[n-u,a]),I=z(x,o),T=De(o);if(u===0)s=pe(v,$e(I,$e(T,v)));else{let F=pe(v,$e(I,$e(T,v)));s=et([Ue(s,[0,0],[u,a]),F],0)}let C=De(I),E=Ue(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=pe(E,$e($e(E,o),C));else{let F=pe(E,$e($e(E,o),C));r=et([Ue(r,[0,0],[n,u]),F],1)}return[o,s,r]}),_e([p,d,c])}return!t&&n>a&&(r=Ue(r,[0,0],[n,a]),s=Ue(s,[0,0],[a,a])),[r,s]})}var yW=L({qr_:bW}),In;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(In||(In={}));function xW(e,t,n=In.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let s=r==null?a:z(a,r);if(n===In.NONE)return s;if(n===In.SUM)return fe(s);if(n===In.MEAN){if(r==null)return Et(s);{let i=a.size/r.size,o=he(fe(s),fe(r));return i>1?he(o,ve(i)):o}}if(n===In.SUM_BY_NONZERO_WEIGHTS){if(r==null)return he(fe(s),ve(a.size));{let i=z(r,Qn(a.shape)),o=se(fe(gi(i,ve(0))),"float32");return he(fe(s),o)}}throw Error(`Unknown reduction: ${n}`)}var Lr=L({computeWeightedLoss_:xW});function vW(e,t,n,a=In.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),s=_(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=_(n,"weights","absoluteDifference")),Tn(r.shape,s.shape,"Error in absoluteDifference: ");let o=Wt(pe(r,s));return Lr(o,i,a)}var wW=L({absoluteDifference_:vW});function kW(e,t,n,a,r=In.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","cosineDistance"),i=_(t,"predictions","cosineDistance"),o=null;a!=null&&(o=_(a,"weights","cosineDistance")),Tn(s.shape,i.shape,"Error in cosineDistance: ");let l=ve(1),u=pe(l,fe(z(s,i),n,!0));return Lr(u,o,r)}var IW=L({cosineDistance_:kW});function SW(e,t,n,a=In.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),s=_(t,"predictions","hingeLoss"),i=null;n!=null&&(i=_(n,"weights","hingeLoss")),Tn(r.shape,s.shape,"Error in hingeLoss: ");let o=ve(1);r=pe(z(ve(2),r),o);let l=Ke(pe(o,z(r,s)));return Lr(l,i,a)}var NW=L({hingeLoss_:SW});function TW(e,t,n,a=1,r=In.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","huberLoss"),i=_(t,"predictions","huberLoss"),o=null;n!=null&&(o=_(n,"weights","huberLoss")),Tn(s.shape,i.shape,"Error in huberLoss: ");let l=ve(a),u=Wt(pe(i,s)),p=fs(u,l),d=pe(u,p),c=X(z(ve(.5),ut(p)),z(l,d));return Lr(c,o,r)}var CW=L({huberLoss_:TW});function _W(e,t,n,a=1e-7,r=In.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","logLoss"),i=_(t,"predictions","logLoss"),o=null;n!=null&&(o=_(n,"weights","logLoss")),Tn(s.shape,i.shape,"Error in logLoss: ");let l=ve(1),u=ve(a),p=yt(z(s,na(X(i,u)))),d=z(pe(l,s),na(X(pe(l,i),u))),c=pe(p,d);return Lr(c,o,r)}var EW=L({logLoss_:_W});function AW(e,t,n,a=In.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),s=_(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=_(n,"weights","meanSquaredError")),Tn(r.shape,s.shape,"Error in meanSquaredError: ");let o=vf(r,s);return Lr(o,i,a)}var FW=L({meanSquaredError_:AW});function $W(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),a=_(t,"logits","sigmoidCrossEntropyWithLogits");Tn(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Ke(a),s=z(a,n),i=md(yn(yt(Wt(a))));return X(pe(r,s),i)}function DW(e,t,n,a=0,r=In.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"multiClassLabels","sigmoidCrossEntropy"),i=_(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=_(n,"weights","sigmoidCrossEntropy")),Tn(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let u=ve(a),p=ve(1),d=ve(.5);s=X(z(s,pe(p,u)),z(d,u))}let l=$W(s,i);return Lr(l,o,r)}var RW=L({sigmoidCrossEntropy_:DW});function MW(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==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 ${n}`);return cr((a,r,s)=>{let i=lf(r,[n],!0),o=pe(se(r,"float32"),i);s([a,o]);let l=yt(z(o,a));return{value:fe(l,[n]),gradFunc:(u,p)=>{let[d,c]=p,h=fi(u.shape,[n]);return[z(W(u,h),pe(se(d,"float32"),yn(c))),z(W(u,h),pe(yn(c),se(d,"float32")))]}}})(e,t)}function PW(e,t,n,a=0,r=In.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"onehotLabels","softmaxCrossEntropy"),i=_(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=_(n,"weights","softmaxCrossEntropy")),Tn(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let u=ve(a),p=ve(1),d=ve(s.shape[1]);s=X(z(s,pe(p,u)),he(u,d))}let l=MW(s,i);return Lr(l,o,r)}var OW=L({softmaxCrossEntropy_:PW});function LW(e,t,n,a){let r=_(e,"indices","sparseFillEmptyRows","int32"),s=_(t,"values","sparseFillEmptyRows"),i=_(n,"denseShape","sparseFillEmptyRows","int32"),o=_(a,"defaultValue","sparseFillEmptyRows",s.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
        ${r.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(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:r,values:s,denseShape:i,defaultValue:o},u=O.runKernel(Kc,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var zW=L({sparseFillEmptyRows_:LW});function WW(e,t,n){let a=_(e,"inputIndices","sparseReshape","int32"),r=_(t,"inputShape","sparseReshape","int32"),s=_(n,"newShape","sparseReshape","int32");if(a.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
        ${a.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:a,inputShape:r,newShape:s},o=O.runKernel(np,i);return{outputIndices:o[0],outputShape:o[1]}}var BW=L({sparseReshape_:WW});function VW(e,t,n){let a=_(e,"data","sparseSegmentMean"),r=_(t,"indices","sparseSegmentMean","int32"),s=_(n,"segmentIds","sparseSegmentMean","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
          ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
          ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return O.runKernel(Xc,i)}var UW=L({sparseSegmentMean_:VW});function GW(e,t,n){let a=_(e,"data","sparseSegmentSum"),r=_(t,"indices","sparseSegmentSum","int32"),s=_(n,"segmentIds","sparseSegmentSum","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
         ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
         ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return O.runKernel(Yc,i)}var HW=L({sparseSegmentSum_:GW});function qW(e,t,n,a,r,s,i,o){let l=_(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=_(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:n,nGramWidths:a,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},d={data:l,dataSplits:u},c=O.runKernel(Qc,d,p);return{nGrams:c[0],nGramsSplits:c[1]}}var jW=L({stringNGrams_:qW});function KW(e,t,n=!0){let a=_(e,"input","stringSplit","string"),r=_(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${a.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let s={skipEmpty:n},i={input:a,delimiter:r},o=O.runKernel(ed,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var XW=L({stringSplit_:KW});function YW(e,t){let n=_(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return O.runKernel(td,r,a)}var ZW=L({stringToHashBucketFast_:YW});function JW(e,t,n,a=!0){let r=_(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:a};return O.runKernel(Jc,{x:r},s)}var QW=L({staticRegexReplace_:JW}),WT={fft:vd,ifft:Yl,rfft:wd,irfft:xf},BT={hammingWindow:Ez,hannWindow:DT,frame:RT,stft:Dz},ea={flipLeftRight:Oz,grayscaleToRGB:zz,resizeNearestNeighbor:zT,resizeBilinear:LT,rotateWithOffset:Bz,cropAndResize:Mz,nonMaxSuppression:Uz,nonMaxSuppressionAsync:Zz,nonMaxSuppressionWithScore:Qz,nonMaxSuppressionWithScoreAsync:tW,nonMaxSuppressionPadded:aW,nonMaxSuppressionPaddedAsync:sW,threshold:pW,transform:dW},Uw={bandPart:mW,gramSchmidt:gW,qr:yW},VT={absoluteDifference:wW,computeWeightedLoss:Lr,cosineDistance:IW,hingeLoss:NW,huberLoss:CW,logLoss:EW,meanSquaredError:FW,sigmoidCrossEntropy:RW,softmaxCrossEntropy:OW},UT={sparseFillEmptyRows:zW,sparseReshape:BW,sparseSegmentMean:UW,sparseSegmentSum:HW},GT={stringNGrams:jW,stringSplit:XW,stringToHashBucketFast:ZW,staticRegexReplace:QW},ne={};Ee(ne,{Serializable:()=>HT,SerializationMap:()=>Zs,registerClass:()=>qT});var HT=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Zs=class{constructor(){this.classNameMap={}}static getMap(){return Zs.instance==null&&(Zs.instance=new Zs),Zs.instance}static register(e){Zs.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function qT(e){A(e.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),A(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Zs.register(e)}var zr=class extends HT{minimize(e,t=!1,n){let{value:a,grads:r}=this.computeGradients(e,n);if(n!=null){let s=n.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return _e(r),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return jN(e,t)}dispose(){this.iterations_!=null&&_e(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:ve(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(zr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Gw=class extends zr{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:P(()=>qe(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:P(()=>qe(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;P(()=>{let l=X(z(i,this.rho),z(ut(s),1-this.rho)),u=z(he(mn(X(o,this.epsilon)),mn(X(i,this.epsilon))),s),p=X(z(o,this.rho),z(ut(u),1-this.rho));i.assign(l),o.assign(p);let d=X(z(u,-this.learningRate),a);a.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(_e(this.accumulatedGrads.map(e=>e.variable)),_e(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}},Hw=class extends zr{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t];this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:P(()=>xn(a.shape,this.initialAccumulatorValue).variable(!1))});let r=Array.isArray(e)?e[n].tensor:e[t];if(r==null)return;let s=this.accumulatedGrads[n].variable;P(()=>{let i=X(s,ut(r));s.assign(i);let o=X(z(he(r,mn(X(i,O.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&_e(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}},qw=class extends zr{static get className(){return"Adam"}constructor(e,t,n,a=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],P(()=>{this.accBeta1=ve(t).variable(),this.accBeta2=ve(n).variable()}),a==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);P(()=>{let n=pe(1,this.accBeta1),a=pe(1,this.accBeta2);t.forEach((r,s)=>{let i=O.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:P(()=>qe(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:P(()=>qe(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedSecondMoment[s].variable,d=X(z(u,this.beta1),z(l,1-this.beta1)),c=X(z(p,this.beta2),z(ut(l),1-this.beta2)),h=he(d,n),m=he(c,a);u.assign(d),p.assign(c);let f=X(z(he(h,X(mn(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(z(this.accBeta1,this.beta1)),this.accBeta2.assign(z(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&_e(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&_e(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),P(()=>{this.accBeta1.assign(Mr(this.beta1,this.iterations_+1)),this.accBeta2.assign(Mr(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}},jw=class extends zr{static get className(){return"Adamax"}constructor(e,t,n,a=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],P(()=>{this.iteration=ve(0).variable(),this.accBeta1=ve(t).variable()}),a==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);P(()=>{let n=pe(1,this.accBeta1),a=he(-this.learningRate,X(z(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=O.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:qe(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:qe(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedWeightedInfNorm[s].variable,d=X(z(u,this.beta1),z(l,1-this.beta1)),c=z(p,this.beta2),h=Wt(l),m=fr(c,h);u.assign(d),p.assign(m);let f=X(z(he(a,n),he(d,X(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(X(this.iteration,1)),this.accBeta1.assign(z(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&_e(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&_e(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){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(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}},Af=class extends zr{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=Array.isArray(e)?e[n].tensor:e[t];if(a==null)return;let r=O.registeredVariables[t];P(()=>{let s=X(z(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=qt(ve(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}},Kw=class extends Af{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=ve(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t];this.accumulations[n]==null&&(this.accumulations[n]={originalName:`${t}/momentum`,variable:P(()=>qe(a).variable(!1))});let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&P(()=>{let i,o=X(z(this.m,r),s);this.useNesterov?i=X(z(this.c,X(s,z(o,this.m))),a):i=X(z(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&_e(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}},Xw=class extends zr{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,a=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,a==null&&(this.epsilon=O.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=O.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:P(()=>qe(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:P(()=>qe(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:P(()=>qe(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;P(()=>{let l=X(z(i,this.decay),z(ut(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[n].variable,p=X(z(u,this.decay),z(s,1-this.decay)),d=he(z(s,this.learningRate),mn(pe(l,X(ut(p),this.epsilon)))),c=X(z(o,this.momentum),d);i.assign(l),u.assign(p),o.assign(c);let h=pe(a,c);a.assign(h)}else{let u=X(z(i,this.decay),z(ut(s),1-this.decay)),p=X(z(o,this.momentum),he(z(s,this.learningRate),mn(X(u,this.epsilon))));i.assign(u),o.assign(p);let d=pe(a,p);a.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&_e(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&_e(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&_e(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}},eB=[Gw,Hw,qw,jw,Kw,Xw,Af];function tB(){for(let e of eB)qT(e)}var jt={};Ee(jt,{CompositeArrayBuffer:()=>hr,browserFiles:()=>lB,browserHTTPRequest:()=>hB,concatenateArrayBuffers:()=>DM,copyModel:()=>tP,decodeWeights:()=>yN,encodeWeights:()=>EM,fromMemory:()=>fB,fromMemorySync:()=>ZT,getLoadHandlers:()=>BM,getModelArtifactsForJSON:()=>Mv,getModelArtifactsForJSONSync:()=>vN,getModelArtifactsInfoForJSON:()=>ld,getSaveHandlers:()=>WM,getWeightSpecs:()=>wN,http:()=>Zw,isHTTPScheme:()=>Wx,listModels:()=>QM,loadWeights:()=>uB,moveModel:()=>nP,registerLoadRouter:()=>zM,registerSaveRouter:()=>LM,removeModel:()=>eP,weightsLoaderFactory:()=>KT,withSaveHandler:()=>gB,withSaveHandlerSync:()=>bB});var nB="model",aB=".json",rB=".weights.bin";function gI(e){return new Promise(t=>setTimeout(t)).then(e)}var Jl=class{constructor(e){if(!G().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Jl.URL_SCHEME)&&(e=e.slice(Jl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=nB),this.modelJsonFileName=e+aB,this.weightDataFileName=e+rB}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=hr.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let a=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r=xN(e,a),s=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),i=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(i.download=this.modelJsonFileName,i.href=s,await gI(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=n,await gI(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ld(e)}}}};Jl.URL_SCHEME="downloads://";var sB=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=a=>{let r=JSON.parse(a.target.result),s=r.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:s});return}let i=Mv(r,o=>this.loadWeights(o));e(i)},n.onerror=a=>t(`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(e){let t=[],n=[];for(let s of e)t.push(...s.weights),n.push(...s.paths);let a=this.checkManifestAndWeightFiles(e),r=n.map(s=>this.loadWeightsFile(s,a[s]));return Promise.all(r).then(s=>[t,s])}loadWeightsFile(e,t){return new Promise((n,a)=>{let r=new FileReader;r.onload=s=>{let i=s.target.result;n(i)},r.onerror=s=>a(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>hI(r.name)),a={};for(let r of e)r.paths.forEach(s=>{let i=hI(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),n.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);a[s]=this.weightsFiles[n.indexOf(i)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return a}},iB=e=>G().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Jl.URL_SCHEME)?oB(e.slice(Jl.URL_SCHEME.length)):null;$t.registerSaveRouter(iB);function oB(e="model"){return new Jl(e)}function lB(e){return new sB(e)}function bI(e,t,n,a){i(e),n=n==null?0:n,a=a==null?1:a,o(n,a);let r=0,s=l=>(l.then(u=>{let p=n+ ++r/e.length*(a-n);return t(p),u}),l);function i(l){A(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){A(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),A(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),A(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function jT(e,t){t==null&&(t={});let n=t.fetchFunc==null?G().platform.fetch:t.fetchFunc,a=e.map(u=>n(u,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await bI(a,t.onProgress,r,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await bI(i,t.onProgress,o,l)}async function uB(e,t="",n,a){return KT(r=>jT(r,{requestInit:a}))(e,t,n)}function KT(e){return async(t,n="",a)=>{let r=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((h,m)=>{let f=0;h.weights.forEach(g=>{let b="quantization"in g?g.quantization.dtype:g.dtype,y=Rx[b]*bt(g.shape),x=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:y})};a!=null?a.forEach((v,I)=>{v===g.name&&(x(),i[I]=!0)}):x(),o.push(g.name),f+=y})}),!i.every(h=>h)){let h=a.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}. 
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((h,m,f)=>(m&&h.push(f),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;u.push(f)})});let p=await e(u),d={},c=0;return l.forEach(h=>{let m=t[h].paths.length,f=new hr(p.slice(c,c+m));s[h].forEach(g=>{let b=f.slice(g.groupOffset,g.groupOffset+g.sizeBytes),y=yN(b,[g.manifestEntry]);for(let x in y)d[x]=y[x]}),c+=m}),d}}var pB="application/octet-stream",cB="application/json",Yw=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(A(typeof t.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=t.fetchFunc):this.fetch=G().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],a=xN(e,n);if(t.body.append("model.json",new Blob([JSON.stringify(a)],{type:cB}),"model.json"),e.weightData!=null){let s=hr.join(e.weightData);t.body.append("model.weights.bin",new Blob([s],{type:pB}),"model.weights.bin")}let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ld(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(r){let s=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?s+=" 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.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let n=t.modelTopology,a=t.weightsManifest;if(n==null&&a==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Mv(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=dB(t),r=this.weightPathPrefix||n,s=wN(e),i=[],o=[];for(let u of e)for(let p of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(p)):i.push(r+p+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await jT(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,l]}};Yw.URL_SCHEME_REGEX=/^https?:\/\//;function dB(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function Wx(e){return e.match(Yw.URL_SCHEME_REGEX)!=null}var XT=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>Wx(a)):n=Wx(e),n)return Zw(e,t)}return null};$t.registerSaveRouter(XT);$t.registerLoadRouter(XT);function Zw(e,t){return new Yw(e,t)}function hB(e,t){return Zw(e,t)}var mx=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},YT=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},mB=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function fB(e,t,n,a){let r=arguments;return new mB(ZT(...r))}function ZT(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new mx(e):(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 mx({modelTopology:e})):(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 mx({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function gB(e){return new YT(e)}function bB(e){return new YT(e)}var JT={};Ee(JT,{confusionMatrix:()=>xB});function yB(e,t,n){let a=_(e,"labels","confusionMatrix"),r=_(t,"predictions","confusionMatrix");A(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),A(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),A(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),A(a.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${a.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),A(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=jl(se(a,"int32"),n),i=jl(se(r,"int32"),n),o=De(s),l=$e(o,i);return se(l,"int32")}var xB=L({confusionMatrix_:yB}),Ko={};Ee(Ko,{draw:()=>CB,fromPixels:()=>_B,fromPixelsAsync:()=>SB,toPixels:()=>TB});var qs,yI=!1;function QT(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,a=!1,r=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!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 ${e.constructor.name}`);if(om(im,O.backendName)!=null){let c={pixels:e},h={numChannels:t};return O.runKernel(im,c,h)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],p;if(i)p=e.getContext("2d").getImageData(0,0,l,u).data;else if(a||n)p=e.data;else if(s||r||o){if(qs==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")qs=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else qs=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});qs.canvas.width=l,qs.canvas.height=u,qs.drawImage(e,0,0,l,u),p=qs.getImageData(0,0,l,u).data}let d;if(t===4)d=new Int32Array(p);else{let c=l*u;d=new Int32Array(c*t);for(let h=0;h<c;h++)for(let m=0;m<t;++m)d[h*t+m]=p[h*4+m]}return kd(d,[u,l,t],"int32")}function vB(e){return e!=null&&e.data instanceof Uint8Array}function wB(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function kB(e){return e!=null&&e.width!==0&&e.height!==0}function IB(e){return wB()&&!(e instanceof ImageBitmap)&&kB(e)&&!vB(e)}async function SB(e,t=3){let n=null;if(G().getBool("WRAP_TO_IMAGEBITMAP")&&IB(e)){let a;try{a=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(r){a=null}a!=null&&a.width===e.width&&a.height===e.height?n=a:n=e}else n=e;return QT(n,t)}function e2(e){if(e.rank!==2&&e.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);let t=e.rank===2?1:e.shape[2];if(t>4||t===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if(e.dtype!=="float32"&&e.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}function NB(e){let t=(e==null?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}async function TB(e,t){let n=_(e,"img","toPixels");if(!(e instanceof Te)){let u=n;n=se(u,"int32"),u.dispose()}e2(n);let[a,r]=n.shape.slice(0,2),s=n.rank===2?1:n.shape[2],i=await n.data(),o=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*a*4);for(let u=0;u<a*r;++u){let p=[0,0,0,255];for(let c=0;c<s;c++){let h=i[u*s+c];if(n.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);s===1?(p[0]=h*o,p[1]=h*o,p[2]=h*o):p[c]=h*o}let d=u*4;l[d+0]=Math.round(p[0]),l[d+1]=Math.round(p[1]),l[d+2]=Math.round(p[2]),l[d+3]=Math.round(p[3])}if(t!=null){yI||(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),yI=!0),t.width=r,t.height=a;let u=t.getContext("2d"),p=new ImageData(l,r,a);u.putImageData(p,0,0)}return n!==e&&n.dispose(),l}function CB(e,t,n){let a=_(e,"img","draw");if(!(e instanceof Te)){let i=a;a=se(i,"int32"),i.dispose()}e2(a),NB(n==null?void 0:n.imageOptions);let r={image:a},s={canvas:t,options:n};O.runKernel(Av,r,s)}var _B=L({fromPixels_:QT}),Jw={};Ee(Jw,{prepareAndValidate:()=>t2});function t2(e,t){let n=e.shape.length,a=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);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[a-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${n}`);if(bt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let d=0;d<r.length-1;++d)i*=r[d];let o=e.shape,l=r.slice();l.pop();let u=1;for(let d=s;d<n;++d)u*=o[d],l.push(o[d]);let p=[...ou(e.shape).map(d=>d/u),1].slice(0,s);return[l,i,u,p]}var Xt={};Ee(Xt,{assertParamsValid:()=>AB,computeFlatOffset:()=>MB,computeOutShape:()=>$B,getNormalizedAxes:()=>DB,isSliceContinous:()=>RB,maskToAxes:()=>FB,parseSliceParams:()=>p2,sliceInfo:()=>PB,startForAxis:()=>l2,startIndicesWithElidedDims:()=>s2,stopForAxis:()=>u2,stopIndicesWithElidedDims:()=>i2,stridesForAxis:()=>o2,stridesWithElidedDims:()=>n2});var Bx=-2,EB=-1;function AB(e,t,n){let a=e.shape.length;A(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),A(a===n.length,()=>`Error in slice${a}D: Length of size ${n} must match the rank of the array (${a}).`);for(let r=0;r<a;++r)A(t[r]+n[r]<=e.shape[r],()=>`Error in slice${a}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function FB(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function $B(e,t,n){let a=[];for(let r=0;r<e.length;r++)a[r]=Math.ceil((t[r]-e[r])/n[r]);return a}function n2(e,t,n,a){let r=[...e];for(let s=r.length;s<a.length;s++)r.push(1);for(let s=0;s<n;s++)s===0?r[t]=1:(r.splice(t,0,1),r.pop());return r}function a2(e,t,n){return n<=e?n:n-(t-1)}function r2(e,t){let n=[];for(let a=0;a<e;a++)n.push(t+a);return n}function DB(e,t,n,a,r,s,i,o,l){let u=e.length,p=new Array(u),d=new Array(u),c=new Array(u);if(t.length&&n>0){let h=t[0],m=n+1;p=s2(i,h,m,a,e),d=i2(o,h,m,r,e),c=n2(s,h,m,e)}else for(let h=0;h<u;h++)p[h]=l2(i,a,s,e,h,l),d[h]=u2(o,r,s,e,h,l),c[h]=o2(s,h,l);return{begin:p,end:d,strides:c}}function s2(e,t,n,a,r){let s=[...r],i=r2(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=a2(t,n,o),u=a[l];e&1<<l&&(u=0),s[o]=u}return s}function i2(e,t,n,a,r){let s=[...r],i=r2(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=a2(t,n,o),u=a[l];e&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[o]=u}for(let o=0;o<s.length;o++){let l=r[o];s[o]<0&&(s[o]+=l),s[o]=bc(0,s[o],r[o])}return s}function o2(e,t,n){let a=e[t];return(n&1<<t||a==null)&&(a=1),a}function l2(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=bc(0,i,l-1),i}function u2(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),o>0?i=bc(0,i,l):i=bc(-1,i,l-1),i}function RB(e,t,n){let a=n.length;for(let r=0;r<n.length;r++)if(n[r]>1){a=r;break}for(let r=a+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function MB(e,t){let n=e.length>0?e[e.length-1]:1;for(let a=0;a<e.length-1;a++)n+=e[a]*t[a];return n}function p2(e,t,n){let a,r=e.shape.length;typeof t=="number"?a=[t,...new Array(r-1).fill(0)]:t.length<r?a=t.concat(new Array(r-t.length).fill(0)):a=t.slice(),a.forEach(i=>{A(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return n==null?s=new Array(r).fill(-1):typeof n=="number"?s=[n,...new Array(r-1).fill(-1)]:n.length<r?s=n.concat(new Array(r-n.length).fill(-1)):s=n,s=s.map((i,o)=>i>=0?i:(A(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-a[o])),[a,s]}function PB(e,t,n,a,r,s,i,o,l){let u;if(a==null?(u=new Array(t.length),u.fill(1)):u=a,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let p=!1,d={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let y=0;y<d.dims;y++)p&&1<<y&o&&d.numAddAxisAfterEllipsis++,1<<y&i&&(p=!0);p||(d.ellipsisMask|=1<<d.dims,d.dims++);let c={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};OB(d,c);let h=!0,m=!0,f=!0,g=[],b=[];for(let y=0;y<e.length;++y){if(c.strides[y]===0)throw Error(`strides[${y}] must be non-zero`);let x=!!(c.shrinkAxisMask&1<<y),v=e[y];if(v===-1){g.push(x?1:-1);continue}let I=[c.beginMask&1<<y,c.endMask&1<<y],T=[c.strides[y]>0?0:-1,c.strides[y]>0?v:v-1];if(x&&c.strides[y]<=0)throw Error("only stride 1 allowed on non-range indexing.");f=f&&c.strides[y]===1;let C=!!(c.beginMask&1<<y&&c.endMask&1<<y);if(c.beginValid&&c.endValid){if(x){let $=c.begin[y]<0?v+c.begin[y]:c.begin[y];if(c.begin[y]=$,c.end[y]=c.begin[y]+1,$<0||$>=v)throw Error(`slice index ${c.begin[y]} of dimension ${y} out of bounds.`)}else c.begin[y]=xI(c.begin[y],0,c.strides[y],v,I,T),c.end[y]=xI(c.end[y],1,c.strides[y],v,I,T);let D=c.strides[y]===1&&c.begin[y]===0&&c.end[y]===v;h=h&&D,m=m&&(y===0&&c.strides[y]===1||D)}else h=h&&c.strides[y]===1&&C,m=m&&(y===0&&c.strides[y]===1||C);let E,F=!1;if(c.beginValid&&c.endValid?(E=c.end[y]-c.begin[y],F=!0):x?(E=1,F=!0):C&&v>=0&&(c.strides[y]<0?E=-v:E=v,F=!0),F){let D;E===0||E<0!=c.strides[y]<0?D=0:D=Math.trunc(E/c.strides[y])+(E%c.strides[y]!==0?1:0),g.push(D)}else g.push(-1)}for(let y=0;y<c.finalShapeGatherIndices.length;++y){let x=c.finalShapeGatherIndices[y];x>=0?b.push(g[x]):x===Bx&&b.push(1)}return{finalShapeSparse:b.filter((y,x)=>c.finalShapeGatherIndices[x]!==Bx),finalShape:b,isIdentity:h,sliceDim0:m,isSimpleSlice:f,begin:c.begin,end:c.end,strides:c.strides}}function OB(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=e.begin!=null,t.endValid=e.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 a=0;a<e.dims;a++)if(1<<a&e.ellipsisMask){let r=Math.min(t.dims-(e.dims-a)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<r;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=a}else if(1<<a&e.newAxisMask)t.finalShapeGatherIndices.push(Bx),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[n]=e.begin[a]),e.end!=null&&(t.end[n]=e.end[a]),t.strides[n]=e.strides[a],e.beginMask&1<<a&&(t.beginMask|=1<<n),e.endMask&1<<a&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<a?(t.finalShapeGatherIndices.push(EB),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(a)),t.inputShapeGatherIndicesSparse[n]=a,n++}}function xI(e,t,n,a,r,s){if(r[t])return n>0?s[t]:s[t+1&1];{let i=e<0?a+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var LB="4.7.0",c2=class{static sgd(e){return new Af(e)}static momentum(e,t,n=!1){return new Kw(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new Xw(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new qw(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new Gw(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new jw(e,t,n,a,r)}static adagrad(e,t=.1){return new Hw(e,t)}},Xs=c2,zB=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Qw(){return new Promise(e=>zB(()=>e()))}var N={};Ee(N,{ERF_A1:()=>e4,ERF_A2:()=>t4,ERF_A3:()=>n4,ERF_A4:()=>a4,ERF_A5:()=>r4,ERF_P:()=>QB,PARALLELIZE_THRESHOLD:()=>e0,RowPartitionType:()=>ar,SELU_SCALE:()=>h2,SELU_SCALEALPHA:()=>d2,applyActivation:()=>_f,assertAndGetBroadcastShape:()=>pt,assertAxesAreInnerMostDims:()=>BO,assertParamsConsistent:()=>WB,assignToTypedArray:()=>p4,axesAreInnerMostDims:()=>cw,calculateShapes:()=>wT,checkEinsumDimSizes:()=>g4,checkPadOnDimRoundingMode:()=>Cn,combineLocations:()=>VN,combineRaggedTensorToTensorShapes:()=>VB,complexWithEvenIndex:()=>o4,complexWithOddIndex:()=>l4,computeConv2DInfo:()=>ud,computeConv3DInfo:()=>$N,computeDefaultPad:()=>qv,computeDilation2DInfo:()=>zP,computeOptimalWindowSize:()=>qB,computeOutAndReduceShapes:()=>UN,computeOutShape:()=>BB,computePool2DInfo:()=>FN,computePool3DInfo:()=>WP,convertConv2DDataFormat:()=>DN,decodeEinsumEquation:()=>m4,eitherStridesOrDilationsAreOne:()=>mr,expandShapeToKeepDim:()=>fi,exponent:()=>d4,exponents:()=>c4,fromStringArrayToUint8:()=>O4,fromUint8ToStringArray:()=>P4,getAxesPermutation:()=>GN,getBroadcastDims:()=>zN,getComplexWithIndex:()=>u4,getEinsumComputePath:()=>b4,getEinsumPermutation:()=>f4,getFusedBiasGradient:()=>Cf,getFusedDyActivation:()=>Tf,getImageCenter:()=>jB,getInnerMostAxes:()=>VO,getPermuted:()=>XB,getRaggedRank:()=>GB,getReductionAxes:()=>Ut,getReshaped:()=>KB,getReshapedPermuted:()=>YB,getRowPartitionTypesHelper:()=>UB,getSliceBeginCoords:()=>ZB,getSliceSize:()=>JB,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>w4,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>k4,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>I4,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>T4,getSparseReshapeInputOutputMismatchErrorMessage:()=>_4,getSparseReshapeInputOutputMultipleErrorMessage:()=>C4,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>S4,getSparseReshapeNegativeOutputDimErrorMessage:()=>N4,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>$4,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>E4,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>A4,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>F4,getUndoAxesPermutation:()=>dw,isIdentityPermutation:()=>y4,log:()=>YR,mergeRealAndImagArrays:()=>s4,prepareAndValidate:()=>t2,prepareSplitSize:()=>v4,segment_util:()=>m2,shouldFuse:()=>Ef,slice_util:()=>Xt,splitRealAndImagArrays:()=>i4,stridesOrDilationsArePositive:()=>hi,tupleValuesAreOne:()=>ms,upcastType:()=>ba,validateDefaultValueShape:()=>HB,validateInput:()=>kf,validateUpdateShape:()=>Rw,warn:()=>as});function WB(e,t){let n=e[0].length;e.forEach((r,s)=>{A(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),A(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let a=e[0];e.forEach((r,s)=>{for(let i=0;i<n;i++)A(i===t||r[i]===a[i],()=>`Error in concat${n}D: Shape of tensors[${s}] (${r}) does not match the shape of the rest (${a}) along the non-concatenated axis ${s}.`)})}function BB(e,t){let n=e[0].slice();for(let a=1;a<e.length;a++)n[t]+=e[a][t];return n}var ar;(function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"})(ar||(ar={}));function VB(e,t,n){let a=new Array;if(n==null&&t==null)return a;if(t==null)for(;a.length<e+n.length;)a.push(-1);else a=t.slice();if(n==null)return a;if(e+n.length!==a.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${a.length}`);for(let r=1;r<n.length;++r){let s=n[r],i=a[a.length-n.length+r],o=a[i];if(s>=0)if(o>=0){if(o!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${s} but shape[${r+e}] = ${o}`)}else a[i]=s}return a}function UB(e){let t={FIRST_DIM_SIZE:ar.FIRST_DIM_SIZE,VALUE_ROWIDS:ar.VALUE_ROWIDS,ROW_LENGTHS:ar.ROW_LENGTHS,ROW_SPLITS:ar.ROW_SPLITS,ROW_LIMITS:ar.ROW_LIMITS,ROW_STARTS:ar.ROW_STARTS},n=[];for(let a of e)if(a in t)n.push(t[a]);else break;return n}function GB(e){return e.length===0?0:e[0]===ar.FIRST_DIM_SIZE?e.length-1:e.length}function HB(e,t){if(e==null||t==null)return;let n=e.length,a=t.length;if(n>=a)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${a})`);for(let r=0;r<Math.min(n,a-1);++r){let s=e[r],i=t[r+1];if(s>=0&&i>=0&&s!==1&&s!==i)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${s} but ragged tensor input.flatValues.shape[${r-e.length}] = ${i}`)}}var e0=30;function qB(e){return e<=e0?e:sm(e,Math.floor(Math.sqrt(e)))}function jB(e,t,n){let a=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[a,r]}function KB(e,t,n,a=!0){let r=[];if(a)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)r=r.concat([e[i+1]/t[i],t[i]]);r=r.concat(e.slice(s+1))}return r}function XB(e,t,n=!0){let a=[];if(n){a.push(t);for(let r=t+1;r<e;++r)r<=2*t?(a.push(r),a.push(r-(t+1))):a.push(r)}else{let r=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):r.push(i);a.push(...r),a.push(0),a.push(...s)}return a}function YB(e,t,n,a=!0){let r=[];a?r.push(e[0]/n):r.push(e[0]*n);for(let s=1;s<e.length;++s)s<=t.length?a?r.push(t[s-1]*e[s]):r.push(e[s]/t[s-1]):r.push(e[s]);return r}function ZB(e,t){let n=[0];for(let a=0;a<t;++a)n.push(e[a][0]);return n}function JB(e,t,n){let a=e.slice(0,1);for(let r=0;r<n;++r)a.push(e[r+1]-t[r][0]-t[r][1]);return a}var d2=1.7580993408473768,h2=1.0507009873554805,QB=.3275911,e4=.254829592,t4=-.284496736,n4=1.421413741,a4=-1.453152027,r4=1.061405429;function s4(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let n=new Float32Array(e.length*2);for(let a=0;a<n.length;a+=2)n[a]=e[a/2],n[a+1]=t[a/2];return n}function i4(e){let t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let a=0;a<e.length;a+=2)t[a/2]=e[a],n[a/2]=e[a+1];return{real:t,imag:n}}function o4(e){let t=Math.ceil(e.length/4),n=new Float32Array(t),a=new Float32Array(t);for(let r=0;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],a[Math.floor(r/4)]=e[r+1];return{real:n,imag:a}}function l4(e){let t=Math.floor(e.length/4),n=new Float32Array(t),a=new Float32Array(t);for(let r=2;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],a[Math.floor(r/4)]=e[r+1];return{real:n,imag:a}}function u4(e,t){let n=e[t*2],a=e[t*2+1];return{real:n,imag:a}}function p4(e,t,n,a){e[a*2]=t,e[a*2+1]=n}function c4(e,t){let n=new Float32Array(e/2),a=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){let s=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(s),a[r]=Math.sin(s)}return{real:n,imag:a}}function d4(e,t,n){let a=(n?2:-2)*Math.PI*(e/t),r=Math.cos(a),s=Math.sin(a);return{real:r,imag:s}}var fx="->",h4=/->/g,vI=",",wI="...";function m4(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(h4,"").length)/fx.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${fx}").`);let[a,r]=e.split(fx);A(a.indexOf(wI)===-1,()=>`The ellipsis notation ("${wI}") is not supported yet.`);let s=a.split(vI),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 o=[];for(let c=0;c<r.length;++c){let h=r[c];if(!s.some(m=>m.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);o.indexOf(h)===-1&&o.push(h)}for(let c=0;c<a.length;++c){let h=a[c];o.indexOf(h)===-1&&h!==vI&&o.push(h)}let l=new Array(s.length);for(let c=0;c<i;++c){if(new Set(s[c].split("")).size!==s[c].length)throw new Error(`Found duplicate axes in input component ${s[c]}. Support for duplicate axes in input is not implemented yet.`);l[c]=[];for(let h=0;h<s[c].length;++h)l[c].push(o.indexOf(s[c][h]))}let u=o.length,p=r.length,d=[];for(let c=p;c<u;++c)d.push(c);return{allDims:o,summedDims:d,idDims:l}}function f4(e,t){let n=new Array(e);n.fill(-1);for(let r=0;r<t.length;++r)n[t[r]]=r;let a=[];for(let r=0;r<e;++r)n[r]===-1&&a.push(r);return n=n.filter(r=>r!==-1),{permutationIndices:n,expandDims:a}}function g4(e,t,n){let a=new Array(e);for(let r=0;r<n.length;++r){let s=n[r].shape;for(let i=0;i<t[r].length;++i)a[t[r][i]]===void 0?a[t[r][i]]=s[i]:A(a[t[r][i]]===s[i],()=>`Expected dimension ${a[t[r][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function b4(e,t){let n=e,a=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let i=0;i<r;++i)a.push([]);let s=[];for(let i=0;i<n.length;++i){let o=n[i],l=x4(t,o);for(let u of l)s.indexOf(u)===-1&&(a[i].push(u),s.push(u))}return{path:n,steps:a}}function y4(e){return e.every((t,n)=>t===n)}function x4(e,t){let n=[];for(let a=0;a<e.length;++a)(e[a].length===0||e[a].indexOf(t)!==-1||t===-1)&&n.push(a);return n}function v4(e,t,n=0){let a=[];if(typeof t=="number")A(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),a=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);A(r<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[n]-i}A(e.shape[n]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),a=t}return a}function w4(e){return`Received SparseTensor with denseShape[0] = 0 but
  indices.shape[0] = ${e}`}function k4(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function I4(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function S4(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function N4(e,t){return`size ${e} must be non-negative, not ${t}`}function T4(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function C4(e,t){let n=bt(e),a=bt(t);return`Input to reshape is a SparseTensor with ${n}
  dense values, but the requested shape requires a multiple of ${a}. inputShape=${e} outputShape= ${t}`}function _4(e,t){let n=bt(e),a=bt(t);return`Input to reshape is a tensor with ${n} dense values, but the requested shape has ${a}. inputShape=${e} outputShape=${t}`}function E4(){return"segment ids must be >= 0"}function A4(){return"segment ids are not increasing"}function F4(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function $4(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}var m2={};Ee(m2,{collectGatherOpShapeInfo:()=>M4,computeOutShape:()=>R4,segOpComputeOptimalWindowSize:()=>D4});function D4(e,t){let n=!1,a;for(e<=e0?(a=e,n=!0):a=sm(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=sm(e,a+1);return a}function R4(e,t,n){let a=[],r=e.length;for(let s=0;s<r;s++)s!==t?a.push(e[s]):a.push(n);return a}function M4(e,t,n,a){let r=t.shape.length,s=e.shape.length;if(a!==0&&(a<-r||a>r))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${a}`);if(a<0&&(a+=r),a>s)throw new Error(`batchDims (${a}) must be less than rank(x) (
    ${s}).`);if(n<a)throw new Error(`batchDims (${a}) must be less than or equal to axis (${n}).`);for(let d=0;d<a;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let i=e.shape[n],o=[],l=1,u=1,p=1;for(let d=0;d<a;++d)o.push(e.shape[d]),l*=e.shape[d];for(let d=a;d<n;d++)o.push(e.shape[d]),u*=e.shape[d];for(let d=a;d<r;d++)o.push(t.shape[d]);for(let d=n+1;d<s;d++)o.push(e.shape[d]),p*=e.shape[d];return{batchSize:l,sliceSize:p,outerSize:u,dimSize:i,outputShape:o}}function P4(e){try{return e.map(t=>um(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function O4(e){return e.map(t=>id(t))}var gr={};Ee(gr,{nonMaxSuppressionV3Impl:()=>MT,nonMaxSuppressionV4Impl:()=>PT,nonMaxSuppressionV5Impl:()=>OT,whereImpl:()=>ST});tB();var f2={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,jo(se(n,"float32"),-1))}}},L4={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=ut(se(n,"float32")),r=mn(pe(ve(1),a));return yt(he(e,r))}}}},z4={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=mn(pe(ut(se(n,"float32")),1));return he(e,a)}}}},W4={kernelName:Is,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=e,i=Ut(n.shape,r);return i.length>0&&(s=fe(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Ut(a.shape,r);return i.length>0&&(s=fe(s,i)),W(s,a.shape)}}}},B4={kernelName:_i,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},V4={kernelName:cu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>qe(n)}}},U4={kernelName:du,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>qe(n)}}},G4={kernelName:Ei,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,mn(pe(ve(1),ut(se(n,"float32")))))}}},H4={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=mn(X(ve(1),ut(se(n,"float32"))));return he(e,a)}}}},q4={kernelName:Di,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=X(ut(n),ut(a)),i=z(e,he(a,s)),o=Ut(n.shape,r);return o.length>0&&(i=fe(i,o)),W(i,n.shape)},b:()=>{let s=X(ut(n),ut(a)),i=yt(z(e,he(n,s))),o=Ut(a.shape,r);return o.length>0&&(i=fe(i,o)),W(i,a.shape)}}}},j4={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,X(ut(se(n,"float32")),1))}}},K4={kernelName:$i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,pe(ve(1),ut(se(n,"float32"))))}}};function X4(e,t,n,a,r,s){let i=_(e,"dy","avgPool3dGrad"),o=_(t,"input","avgPool3dGrad"),l=i,u=o,p=!1;o.rank===4&&(p=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),A(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),Cn("avgPool3dGrad",r,s);let d={dy:l,input:u},c={filterSize:n,strides:a,pad:r,dimRoundingMode:s},h=O.runKernel(Lc,d,c);return p?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Y4=L({avgPool3dGrad_:X4}),Z4={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>Y4(e,a,r,s,i,o)}}};function J4(e,t,n,a,r){let s=_(e,"dy","avgPoolGrad"),i=_(t,"input","avgPoolGrad");A(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,u=!1;i.rank===3&&(u=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),A(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let p={dy:l,input:o},d={filterSize:n,strides:a,pad:r},c=O.runKernel(Oc,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Q4=L({avgPoolGrad_:J4}),eV={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>Q4(e,a,r,s,i)}}},tV={kernelName:Mi,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[a,r]=t,{transposeA:s,transposeB:i}=n;return!s&&!i?{a:()=>$e(e,r,!1,!0),b:()=>$e(a,e,!0,!1)}:!s&&i?{a:()=>$e(e,r,!1,!1),b:()=>$e(e,a,!0,!1)}:s&&!i?{a:()=>$e(r,e,!1,!0),b:()=>$e(a,e,!1,!1)}:{a:()=>$e(r,e,!0,!0),b:()=>$e(e,a,!0,!0)}}},nV={kernelName:mu,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>bd(e,a,r)}}},aV={kernelName:aN,gradFunc:(e,t,n)=>{let a=n,r=a.inputShape,s=a.shape,i=Array.from(s);for(let l=r.length-1;l>=0;l--)if(r[l]===s[l])i[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>fe(e,o,!0)}}},rV={kernelName:Pi,gradFunc:e=>({x:()=>e.clone()})},sV={kernelName:Oi,gradFunc:e=>({x:()=>qe(e)})},iV={kernelName:Ss,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>rn(Da(Or(a,r),As(a,s)),e,qe(e))}}},oV={kernelName:Wc,inputsToSave:["x"],gradFunc:f2.gradFunc},lV={kernelName:bu,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=Ra(r,t[0].shape)[0],i=a.map(o=>o[s]);return zn(e,i,s).map(o=>()=>o)}},uV={kernelName:Li,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return A(ms(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>aw(a.shape,e,r,i,o,l),filter:()=>Bw(a,e,r.shape,i,o,l)}}},pV={kernelName:zi,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Rt(e,r,s,i,o,1,l),filter:()=>Bw(e,a,r.shape,s,i,o,l)}}};function cV(e,t,n,a,r){let s=e;e.rank===4&&(s=W(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),A(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),A(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),A(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),A(s.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`),A(i.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`);let o={x:s,dy:i},l={strides:a,pad:r,filterShape:n};return O.runKernel(yu,o,l)}var dV=L({conv3DBackpropFilter_:cV}),hV={kernelName:Wi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;A(ms(a),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let[i,o]=t;return{x:()=>ON(i.shape,e,o,r,s),filter:()=>dV(i,e,o.shape,r,s)}}},mV={kernelName:Bi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(yt(gf(se(n,"float32"))),e)}}},fV={kernelName:Vi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(bf(se(n,"float32")),e)}}},gV={kernelName:Ui,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=GN([r],a.rank),l=af(e,r,s,!i);return o!=null&&(l=De(l,o)),l}}}},bV={kernelName:Gi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;A(ms(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,u]=t;return A(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),A(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),A(mr(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${r} and dilations '${o}'.`),Cn("depthwiseConv2d",s,i),{x:()=>$T(l.shape,e,u,r,s,o,i),filter:()=>FT(l,e,u.shape,r,s,o,i)}}},yV={kernelName:Hi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,s={x:a,filter:r,dy:e},i={x:a,filter:r,dy:e};return{x:()=>O.runKernel(Vl,s,n),filter:()=>O.runKernel(Ul,i,n)}}},xV={kernelName:ji,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>O.runKernel(Iu,a)}}},vV={kernelName:Ki,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=z(yn(yt(ut(n))),2/Math.sqrt(Math.PI));return{x:()=>z(e,a)}}},wV={kernelName:Xi,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,n)}}},kV={kernelName:Nu,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>W(e,n.shape)}}},IV={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,yn(n))}}},SV={kernelName:Zi,gradFunc:e=>({x:()=>qe(e)})},NV={kernelName:Ji,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=he(e,se(a,"float32")),i=Ut(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,se(n,"float32")),i=Ut(a.shape,r);i.length>0&&(s=W(fe(s,i),a.shape));let o=ut(a);return yt(he(s,se(o,"float32")))}}}},TV={kernelName:Qi,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?ve(1):o,u=Ut(s.shape,r.shape),p=[];if(s.rank===1){for(let f=0;f<r.shape.length-1;++f)p.push(r.shape[f]);p.push(1)}let d=pe(r,s),c=z(e,l),h=mf(X(i,ve(a))),m=z(z(z(h,h),h),ve(-.5));return{x:()=>s.rank===1?W(z(z(e,Ln(W(h,[1,1,1,s.shape[0]]),p)),l),r.shape):W(z(z(e,h),l),r.shape),mean:()=>{let f=z(z(h,ve(-1)),c);return s.rank===1&&(f=fe(f,u)),W(f,s.shape)},variance:()=>{let f=z(z(m,d),c);return s.rank===1&&(f=fe(f,u)),W(f,s.shape)},scale:()=>{let f=z(d,h),g=z(e,f);return s.rank===1&&(g=fe(g,u)),W(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=fe(f,u)),W(f,s.shape)}}}},CV={kernelName:Cu,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s}=n,i=Ra(s,a.shape)[0];return{x:()=>{let o=a.shape,l=r.size,u=o.slice(0,i),p=u.length,d=o.slice(s,o.length).slice(1),c=d.length,h=kI(0,p),m=kI(p+1,p+1+c),f=II([u,[l],d]),g=W(e,f),b=W(r,[l]),y=II([[p],h,m]),x=De(g,y),v=Sf(x,b,a.shape[i]),I=dw(y);return v=De(v,I),v},indices:()=>r}}};function kI(e,t){let n=[];for(let a=e;a<t;++a)n.push(a);return n}function II(e){let t=[];for(let n=0;n<e.length;++n)for(let a=0;a<e[n].length;++a)t.push(e[n][a]);return t}var _V={kernelName:eo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>qe(n),b:()=>qe(a)}}},EV={kernelName:to,gradFunc:e=>({x:()=>se(e,"float32")})},AV={kernelName:no,gradFunc:e=>({x:()=>qe(e)})},FV={kernelName:ao,gradFunc:e=>({x:()=>qe(e)})},$V={kernelName:ro,gradFunc:e=>({x:()=>qe(e)})},DV={kernelName:so,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=_n(a,0);return{x:()=>rn(s,e,z(e,r))}}},RV={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,X(n,1))}}},MV={kernelName:io,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,se(n,"float32"))}}},PV={kernelName:sN,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=yn(a);return pe(e,z(fe(e,r,!0),s))}}}};function OV(e,t,n,a=5,r=1,s=1,i=.5){let o={x:e,y:t,dy:n},l={depthRadius:a,bias:r,alpha:s,beta:i};return O.runKernel(Pu,o,l)}var LV=L({localResponseNormalizationBackprop_:OV}),zV={kernelName:lo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>LV(a,r,e,s,i,o,l)}}};function g2(e,t,n,a){return t.rank<n.rank&&(t=W(t,fi(t.shape,a))),e.rank<n.rank&&(e=W(e,fi(e.shape,a))),{x:()=>z(e,se(ta(n,t),e.dtype))}}var SI={kernelName:uo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=Ra(r,s.shape),l=g2(e,i,s,o);return{x:()=>l.x()}}},WV={kernelName:po,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>z(e,se(Or(n,a),"float32")),b:()=>z(e,se(ql(n,a),"float32"))}}};function BV(e,t,n,a,r,s,i){let o=_(e,"dy","maxPool3dGrad"),l=_(t,"input","maxPool3dGrad"),u=_(n,"output","maxPool3dGrad"),p=o,d=l,c=u,h=!1;l.rank===4&&(h=!0,p=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),d=W(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),c=W(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),A(p.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${p.rank}.`),A(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),A(c.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${c.rank}.`),Cn("maxPool3dGrad",s,i);let m={dy:p,input:d,output:c},f={filterSize:a,strides:r,pad:s,dimRoundingMode:i},g=O.runKernel(Hc,m,f);return h?W(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var VV=L({maxPool3dGrad_:BV}),UV={kernelName:Ou,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>VV(e,a,r,s,i,o,l)}}};function GV(e,t,n,a,r,s,i){let o=_(e,"dy","maxPoolGrad"),l=_(t,"input","maxPoolGrad"),u=_(n,"output","maxPoolGrad");A(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),A(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),A(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Cn("maxPoolGrad",s,i);let p={dy:o,input:l,output:u},d={filterSize:a,strides:r,pad:s,dimRoundingMode:i};return O.runKernel(Gc,p,d)}var HV=L({maxPoolGrad_:GV}),qV={kernelName:co,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>HV(e,a,r,s,i,o)}}},jV={kernelName:ho,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=Ra(r,a.shape),i=UN(a.shape,s)[1],o=bt(i);return{x:()=>{let l=a.shape.slice();s.forEach(p=>{l[p]=1});let u=W(e,l);return he(z(u,Qn(a.shape,"float32")),o)}}}},KV={kernelName:mo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=Ra(r,s.shape),l=g2(e,i,s,o);return{x:()=>l.x()}}},XV={kernelName:fo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>z(e,se(As(n,a),"float32")),b:()=>z(e,se(_n(n,a),"float32"))}}},YV={kernelName:go,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>Ue(e,s,a.shape)}}},ZV={kernelName:bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=Ut(n.shape,r);return s.length>0?W(fe(e,s),n.shape):e},b:()=>{let s=z(e,yt(hp(he(n,a)))),i=Ut(a.shape,r);return i.length>0?W(fe(s,i),a.shape):s}}}},JV={kernelName:yo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=z(e,se(a,"float32")),i=Ut(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,se(n,"float32")),i=Ut(a.shape,r);return i.length>0?W(fe(s,i),a.shape):s}}}},QV={kernelName:zu,gradFunc:e=>({x:()=>yt(e)})},eU={kernelName:xo,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Nt(n.shape,"float32")}}},tU={kernelName:Gu,gradFunc:e=>({x:()=>qe(e)})},nU={kernelName:Hu,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return ct(e,a).map(r=>()=>r)}},NI={kernelName:vo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>Ue(e,s,a.shape)}}},aU={kernelName:wo,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=pt(s.shape,i.shape);return{a:()=>{let l=se(i,"float32"),u=z(e,z(l,Mr(s,pe(l,ve(1))))),p=Ut(s.shape,o);return p.length>0&&(u=fe(u,p)),W(u,s.shape)},b:()=>{let l=_n(s,0),u=rn(l,na(s),qe(s)),p=z(e,z(r,u)),d=Ut(i.shape,o);return d.length>0&&(p=fe(p,d)),W(p,i.shape)}}}},rU={kernelName:ko,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=_n(n,0);return{x:()=>rn(r,e,z(e,a)),alpha:()=>{let s=rn(r,qe(e),z(e,n)),i=Ut(a.shape,e.shape);return i.length>0&&(s=fe(s,i)),W(s,a.shape)}}}};function sU(e,t,n){let a=e.shape.slice();a[n]=1;let r=W(t,a),s=Nc(e,n,!0,!1),i=Nc(e,n,!0,!0),o=z(s,i);return z(r,o)}function iU(e,t,n){let a=e.shape.length,r=a-n.length,s=N.getAxesPermutation(n,a),i=e;s!=null&&(i=De(e,s));let o=i.shape.slice(),l=o.splice(a-n.length,n.length).reduce((d,c)=>d*c,1);o.push(l);let u=i.reshape(o),p=sU(u,t,r);if(p=p.reshape(i.shape),s!=null){let d=N.getUndoAxesPermutation(s);p=De(p,d)}return p}var oU={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=[];return r==null?s=a.shape.map((i,o)=>o):typeof r=="number"?s=[r]:s=r,{x:()=>iU(a,e,s)}}},lU={kernelName:qi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=he(e,se(a,"float32")),i=Ut(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,se(n,"float32")),i=Ut(a.shape,r);i.length>0&&(s=W(fe(s,i),a.shape));let o=ut(a);return yt(he(s,se(o,"float32")))}}}},uU={kernelName:So,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,yt(ut(n)))}}},pU={kernelName:_o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=z(As(n,6),jo(n));return{x:()=>z(e,se(a,"float32"))}}},cU={kernelName:No,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,se(jo(n),"float32"))}}},dU={kernelName:qu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n.shape)}}},hU={kernelName:Co,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>O.runKernel(Ku,r,n)}}},mU={kernelName:To,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>O.runKernel(ju,r,n)}}},fU={kernelName:Eo,gradFunc:(e,t,n)=>{let{dims:a}=n,r=Ra(a,e.shape);return{x:()=>ya(e,r)}}},gU={kernelName:Ao,gradFunc:e=>({x:()=>qe(e)})},bU={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>yt(he(e,z(Mr(n,1.5),2)))}}},yU={kernelName:Ju,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>se(qe(n),"float32"),t:()=>z(e,se(n,e.dtype)),e:()=>z(e,se(fd(n),e.dtype))}}},xU={kernelName:$o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=_n(n,ve(0)),r=ve(d2),s=ve(h2),i=z(e,s),o=z(z(e,r),yn(se(n,"float32")));return rn(a,i,o)}}}},vU={kernelName:Po,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,z(n,pe(ve(1),n)))}}},wU={kernelName:Mo,gradFunc:e=>({x:()=>qe(e)})},kU={kernelName:Do,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(cd(se(n,"float32")),e)}}},IU={kernelName:Ro,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(nf(se(n,"float32")),e)}}},SU={kernelName:Qu,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{begin:r,size:s}=n,i=a.shape,[o,l]=p2(a,r,s),u=[];for(let p=0;p<e.rank;p++)u.push([o[p],i[p]-o[p]-l[p]]);return{x:()=>va(e,u)}}},NU={kernelName:Wo,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=z(e,a);return{logits:()=>pe(i,z(fe(i,[r],s),a))}}},TU={kernelName:Oo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,fa(n))}}},TI={kernelName:ep,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>pd(e,a,r)}}},CI={kernelName:tp,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>et(e,a)}}},CU={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,z(mn(se(n,"float32")),2))}}},_U={kernelName:Zc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,z(se(n,"float32"),2))}}},EU={kernelName:Bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ve(2);return{a:()=>z(e,z(r,pe(n,a))),b:()=>z(e,z(r,pe(a,n)))}}},AU={kernelName:Ts,gradFunc:e=>({x:()=>qe(e)})},FU={kernelName:Vo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pt(n.shape,a.shape);return{a:()=>{let s=e,i=Ut(n.shape,r);return i.length>0&&(s=fe(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Ut(a.shape,r);return i.length>0&&(s=fe(s,i)),W(yt(s),a.shape)}}}},$U={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;Ra(s,a.shape).forEach(l=>{r[l]=1});let i=W(e,r),o=z(i,Qn(a.shape,"float32"));return{x:()=>o}}},DU={kernelName:Uo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ut(cd(n)))}}},RU={kernelName:Go,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(pe(ve(1),ut(n)),e)}}},MU={kernelName:Ns,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{reps:r}=n;return{x:()=>{let s=qe(a);if(a.rank===1)for(let i=0;i<r[0];++i)s=X(s,Ue(e,[i*a.shape[0]],[a.shape[0]]));else if(a.rank===2)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)s=X(s,Ue(e,[i*a.shape[0],o*a.shape[1]],[a.shape[0],a.shape[1]]));else if(a.rank===3)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)for(let l=0;l<r[2];++l)s=X(s,Ue(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2]],[a.shape[0],a.shape[1],a.shape[2]]));else if(a.rank===4)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)for(let l=0;l<r[2];++l)for(let u=0;u<r[3];++u)s=X(s,Ue(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2],u*a.shape[3]],[a.shape[0],a.shape[1],a.shape[2],a.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${a.rank} tensors yet.`);return s}}}},PU={kernelName:$r,gradFunc:(e,t,n)=>{let a=n,{perm:r}=a,s=dw(r);return{x:()=>De(e,s)}}},OU={kernelName:op,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>Dt(e,r)}}},LU={kernelName:ad,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>zU(e,n)}}};function zU(e,t){let n=fr(t,qe(t)),a=mp(e,n),r=Or(t,ve(0,"int32")),s=a.rank-r.rank;for(let o=0;o<s;++o)r=nn(r,o+1);r=Da(r,Qn(a.shape,"bool"));let i=qe(a);return rn(r,a,i)}var WU={kernelName:lp,gradFunc:e=>({x:()=>qe(e)})},BU=[f2,L4,z4,W4,B4,V4,U4,G4,H4,q4,j4,K4,Z4,eV,tV,nV,aV,rV,sV,iV,oV,lV,pV,uV,hV,mV,fV,gV,bV,yV,lU,xV,vV,wV,kV,IV,NV,SV,TV,CV,_V,EV,AV,FV,$V,DV,RV,MV,PV,zV,SI,SI,WV,UV,qV,jV,KV,XV,YV,ZV,JV,QV,eU,tU,nU,NI,NI,aU,rU,oU,uU,pU,cU,dU,hU,mU,fU,gU,bU,yU,xU,vU,wU,kU,IU,SU,NU,TU,TI,TI,CI,CI,CU,EU,_U,AU,FU,$U,DU,RU,MU,PU,OU,LU,WU];for(let e of BU)iN(e);Q().prototype.abs=function(){return this.throwIfDisposed(),Wt(this)};Q().prototype.acos=function(){return this.throwIfDisposed(),Lv(this)};Q().prototype.acosh=function(){return this.throwIfDisposed(),zv(this)};Q().prototype.add=function(e){return this.throwIfDisposed(),X(this,e)};Q().prototype.all=function(e,t){return this.throwIfDisposed(),Qm(this,e,t)};Q().prototype.any=function(e,t){return this.throwIfDisposed(),kc(this,e,t)};Q().prototype.argMax=function(e){return this.throwIfDisposed(),di(this,e)};Q().prototype.argMin=function(e){return this.throwIfDisposed(),Wv(this,e)};Q().prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),W(this,[])};Q().prototype.asType=function(e){return this.throwIfDisposed(),se(this,e)};Q().prototype.as1D=function(){return this.throwIfDisposed(),W(this,[this.size])};Q().prototype.as2D=function(e,t){return this.throwIfDisposed(),W(this,[e,t])};Q().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),W(this,[e,t,n])};Q().prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),W(this,[e,t,n,a])};Q().prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),W(this,[e,t,n,a,r])};Q().prototype.asin=function(){return this.throwIfDisposed(),Bv(this)};Q().prototype.asinh=function(){return this.throwIfDisposed(),Vv(this)};Q().prototype.atan=function(){return this.throwIfDisposed(),Uv(this)};Q().prototype.atan2=function(e){return this.throwIfDisposed(),Gv(this,e)};Q().prototype.atanh=function(){return this.throwIfDisposed(),Hv(this)};Q().prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),xa(this,e,t,n,a)};Q().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),pd(this,e,t)};Q().prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),_s(this,e,t,n,a,r)};Q().prototype.broadcastTo=function(e){return this.throwIfDisposed(),ri(this,e)};Q().prototype.cast=function(e){return this.throwIfDisposed(),se(this,e)};Q().prototype.ceil=function(){return this.throwIfDisposed(),Jv(this)};Q().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),sn(this,e,t)};Q().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Te&&(e=[e]),et([this,...e],t)};Q().prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),ef(this,e,t,n,a,r,s)};Q().prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),tf(this,e,t,n,a,r)};Q().prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Rt(this,e,t,n,a,r,s)};Q().prototype.cos=function(){return this.throwIfDisposed(),cd(this)};Q().prototype.cosh=function(){return this.throwIfDisposed(),nf(this)};Q().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Nc(this,e,t,n)};Q().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),af(this,e,t,n)};Q().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),iw(this,e,t)};Q().prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Es(this,e,t,n,a,r,s)};Q().prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),ow(this,e,t,n,a,r)};Q().prototype.divNoNan=function(e){return this.throwIfDisposed(),lw(this,e)};Q().prototype.div=function(e){return this.throwIfDisposed(),he(this,e)};Q().prototype.dot=function(e){return this.throwIfDisposed(),uw(this,e)};Q().prototype.elu=function(){return this.throwIfDisposed(),cp(this)};Q().prototype.equal=function(e){return this.throwIfDisposed(),ta(this,e)};Q().prototype.erf=function(){return this.throwIfDisposed(),pw(this)};Q().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),hw(this,e,t)};Q().prototype.exp=function(){return this.throwIfDisposed(),yn(this)};Q().prototype.expandDims=function(e){return this.throwIfDisposed(),nn(this,e)};Q().prototype.expm1=function(){return this.throwIfDisposed(),mw(this)};Q().prototype.fft=function(){return this.throwIfDisposed(),vd(this)};Q().prototype.flatten=function(){return this.throwIfDisposed(),W(this,[this.size])};Q().prototype.floor=function(){return this.throwIfDisposed(),hp(this)};Q().prototype.floorDiv=function(e){return this.throwIfDisposed(),Jm(this,e)};Q().prototype.gather=function(e,t,n){return this.throwIfDisposed(),mp(this,e,t,n)};Q().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Or(this,e)};Q().prototype.greater=function(e){return this.throwIfDisposed(),_n(this,e)};Q().prototype.ifft=function(){return this.throwIfDisposed(),Yl(this)};Q().prototype.irfft=function(){return this.throwIfDisposed(),xf(this)};Q().prototype.isFinite=function(){return this.throwIfDisposed(),fw(this)};Q().prototype.isInf=function(){return this.throwIfDisposed(),gw(this)};Q().prototype.isNaN=function(){return this.throwIfDisposed(),bw(this)};Q().prototype.leakyRelu=function(e){return this.throwIfDisposed(),hd(this,e)};Q().prototype.lessEqual=function(e){return this.throwIfDisposed(),As(this,e)};Q().prototype.less=function(e){return this.throwIfDisposed(),ql(this,e)};Q().prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),yw(this,e,t,n,a)};Q().prototype.logSigmoid=function(){return this.throwIfDisposed(),xw(this)};Q().prototype.logSoftmax=function(e){return this.throwIfDisposed(),of(this,e)};Q().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),lf(this,e,t)};Q().prototype.log=function(){return this.throwIfDisposed(),na(this)};Q().prototype.log1p=function(){return this.throwIfDisposed(),md(this)};Q().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Da(this,e)};Q().prototype.logicalNot=function(){return this.throwIfDisposed(),fd(this)};Q().prototype.logicalOr=function(e){return this.throwIfDisposed(),uf(this,e)};Q().prototype.logicalXor=function(e){return this.throwIfDisposed(),vw(this,e)};Q().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),$e(this,e,t,n)};Q().prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),Mt(this,e,t,n,a)};Q().prototype.max=function(e,t){return this.throwIfDisposed(),ga(this,e,t)};Q().prototype.maximum=function(e){return this.throwIfDisposed(),fr(this,e)};Q().prototype.mean=function(e,t){return this.throwIfDisposed(),Et(this,e,t)};Q().prototype.min=function(e,t){return this.throwIfDisposed(),Hl(this,e,t)};Q().prototype.minimum=function(e){return this.throwIfDisposed(),fs(this,e)};Q().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),kw(this,e,t)};Q().prototype.mod=function(e){return this.throwIfDisposed(),Iw(this,e)};Q().prototype.mul=function(e){return this.throwIfDisposed(),z(this,e)};Q().prototype.neg=function(){return this.throwIfDisposed(),yt(this)};Q().prototype.norm=function(e,t,n){return this.throwIfDisposed(),dp(this,e,t,n)};Q().prototype.notEqual=function(e){return this.throwIfDisposed(),gi(this,e)};Q().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),jl(this,e,t,n)};Q().prototype.onesLike=function(){return this.throwIfDisposed(),aa(this)};Q().prototype.pad=function(e,t){return this.throwIfDisposed(),va(this,e,t)};Q().prototype.pool=function(e,t,n,a,r,s){return this.throwIfDisposed(),Sw(this,e,t,n,a,r,s)};Q().prototype.pow=function(e){return this.throwIfDisposed(),Mr(this,e)};Q().prototype.prelu=function(e){return this.throwIfDisposed(),yd(this,e)};Q().prototype.prod=function(e,t){return this.throwIfDisposed(),Nw(this,e,t)};Q().prototype.reciprocal=function(){return this.throwIfDisposed(),Aw(this)};Q().prototype.relu=function(){return this.throwIfDisposed(),Ke(this)};Q().prototype.relu6=function(){return this.throwIfDisposed(),df(this)};Q().prototype.reshapeAs=function(e){return this.throwIfDisposed(),W(this,e.shape)};Q().prototype.reshape=function(e){return this.throwIfDisposed(),W(this,e)};Q().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),LT(this,e,t,n)};Q().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),zT(this,e,t,n)};Q().prototype.reverse=function(e){return this.throwIfDisposed(),ya(this,e)};Q().prototype.rfft=function(){return this.throwIfDisposed(),wd(this)};Q().prototype.round=function(){return this.throwIfDisposed(),hf(this)};Q().prototype.rsqrt=function(){return this.throwIfDisposed(),mf(this)};Q().prototype.selu=function(){return this.throwIfDisposed(),ff(this)};Q().prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),$s(this,e,t,n,a,r,s)};Q().prototype.sigmoid=function(){return this.throwIfDisposed(),fa(this)};Q().prototype.sign=function(){return this.throwIfDisposed(),Fw(this)};Q().prototype.sin=function(){return this.throwIfDisposed(),gf(this)};Q().prototype.sinh=function(){return this.throwIfDisposed(),bf(this)};Q().prototype.slice=function(e,t){return this.throwIfDisposed(),Ue(this,e,t)};Q().prototype.softmax=function(e){return this.throwIfDisposed(),Xa(this,e)};Q().prototype.softplus=function(){return this.throwIfDisposed(),Ho(this)};Q().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),bd(this,e,t)};Q().prototype.split=function(e,t){return this.throwIfDisposed(),zn(this,e,t)};Q().prototype.sqrt=function(){return this.throwIfDisposed(),mn(this)};Q().prototype.square=function(){return this.throwIfDisposed(),ut(this)};Q().prototype.squaredDifference=function(e){return this.throwIfDisposed(),vf(this,e)};Q().prototype.squeeze=function(e){return this.throwIfDisposed(),Ds(this,e)};Q().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Te?[this,e]:[this,...e];return Dt(n,t)};Q().prototype.step=function(e){return this.throwIfDisposed(),jo(this,e)};Q().prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),$w(this,e,t,n,a,r,s,i,o)};Q().prototype.sub=function(e){return this.throwIfDisposed(),pe(this,e)};Q().prototype.sum=function(e,t){return this.throwIfDisposed(),fe(this,e,t)};Q().prototype.tan=function(){return this.throwIfDisposed(),Dw(this)};Q().prototype.tanh=function(){return this.throwIfDisposed(),mi(this)};Q().prototype.tile=function(e){return this.throwIfDisposed(),Ln(this,e)};Q().prototype.toBool=function(){return this.throwIfDisposed(),se(this,"bool")};Q().prototype.toFloat=function(){return this.throwIfDisposed(),se(this,"float32")};Q().prototype.toInt=function(){return this.throwIfDisposed(),se(this,"int32")};Q().prototype.topk=function(e,t){return this.throwIfDisposed(),Mw(this,e,t)};Q().prototype.transpose=function(e){return this.throwIfDisposed(),De(this,e)};Q().prototype.unique=function(e){return this.throwIfDisposed(),Pw(this,e)};Q().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Sf(this,e,t)};Q().prototype.unstack=function(e){return this.throwIfDisposed(),ct(this,e)};Q().prototype.where=function(e,t){return this.throwIfDisposed(),rn(e,this,t)};Q().prototype.zerosLike=function(){return this.throwIfDisposed(),qe(this)};var Cr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Cr.prototype)}},Ba=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ba.prototype)}},V=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,V.prototype)}},Le=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Le.prototype)}},b2=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,b2.prototype)}},y2=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){let n=this.cache.keys().next().value;this.cache.delete(n)}this.maxEntries=e}};function yi(e,t){if(Array.isArray(e)){let n=[];for(let a=0;a<t;a++)n=n.concat(e);return n}else{let n=new Array(t);return n.fill(e),n}}function rr(e,t){if(!e)throw new b2(t)}function _I(e,t){let n=0;for(let a of e)a===t&&n++;return n}function On(e){return e.length===1?e[0]:e}function kt(e){return Array.isArray(e)?e:[e]}function _r(e){let t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function Js(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var Ta={};function t0(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Vx(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>Vx(t));else{let t=Object.keys(e);for(let n of t){let a=e[n];a!=null&&typeof a=="object"&&(!Array.isArray(a)&&a.type==="ndarray"&&typeof a.value=="number"?e[n]=a.value:Vx(a))}}}function Id(e,t={},n={},a="object",r=!1){if(typeof e=="string"){let s=e,i;if(s in n)i=n[s];else if(s in Ta)i=Ta[s];else if(i=t[s],i==null)throw new V(`Unknown ${a}: ${e}. This may be due to one of the following reasons:
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new V(`${a}: Improper config format: ${JSON.stringify(s)}.
'className' and 'config' must set.`);let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in Ta?[o,l]=Ta.className:i in t&&([o,l]=t[i]),o==null)throw new V(`Unknown ${a}: ${i}. This may be due to one of the following reasons:
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let h of Object.keys(Ta))u[h]=Ta[h];for(let h of Object.keys(n))u[h]=n[h];let p=s.config;p.customObjects=u;let d=Object.assign({},Ta);for(let h of Object.keys(n))Ta[h]=n[h];Vx(s.config);let c=l(o,s.config,n,r);return Ta=Object.assign({},d),c}else{let u=Object.assign({},Ta);for(let d of Object.keys(n))Ta[d]=n[d];let p=new o(s.config);return Ta=Object.assign({},u),p}}}function VU(e,t){return e<t?-1:e>t?1:0}function Ph(e,t){return-1*VU(e,t)}function us(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function UU(e){if(e==null)throw new V(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Xo(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new V(`${n} is not a valid ${t}.  Valid values are ${e} or null/undefined.`)}function n0(e,t,n=0,a=1/0){return rr(n>=0),rr(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function an(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>an(n,`element ${a+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${x2(e)}.`)}function x2(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>x2(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function GU(e,t,n){let a=n!=null?n():w.now(),r;return(...s)=>{let i=n!=null?n():w.now();return i-a<t||(a=i,r=e(...s)),r}}function v2(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var HU=0;function w2(){return HU++}var Oh={};function Ff(e=""){return e in Oh||(Oh[e]=0),Oh[e]+=1,e+Oh[e].toString()}var qU=["channelsFirst","channelsLast"],jU=["nearest","bilinear"],KU=["valid","same","causal"],XU=["max","avg"],YU=["sum","mul","concat","ave"],Dl=new Map;function Pt(e){Xo(qU,"DataFormat",e)}function ZU(e){Xo(jU,"InterpolationFormat",e)}function wa(e){Xo(KU,"PaddingMode",e)}function k2(e){Xo(XU,"PoolMode",e)}var mc=[],EI="/";function si(e,t){mc.push(e);try{let n=t();return mc.pop(),n}catch(n){throw mc.pop(),n}}function JU(){return mc.length===0?"":mc.join(EI)+EI}function I2(e){if(!N2(e))throw new Error("Not a valid tensor name: '"+e+"'");return JU()+e}function S2(e){if(!N2(e))throw new Error("Not a valid tensor name: '"+e+"'");Dl.has(e)||Dl.set(e,0);let t=Dl.get(e);if(Dl.set(e,Dl.get(e)+1),t>0){let n=`${e}_${t}`;return Dl.set(n,1),n}else return e}var QU=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function N2(e){return!!e.match(QU)}function eG(e){return e===parseInt(e.toString(),10)}function ps(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let a=1;for(let r=t;r<n;++r)a*=e[r];return a}function Ql(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let a=e[n];a<t&&(t=a)}return t}function gs(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let a=e[n];a>t&&(t=a)}return t}function qa(e,t){if(t<e)throw new V(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let a=e;a<t;++a)n.push(a);return n}var gx;function Kt(){return gx==null&&(gx=EN().epsilon()),gx}function ja(){return"channelsLast"}function lr(e,t){return se(e,t)}function Sd(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),W(e,n)}function tG(e,t){return P(()=>{if(e.shape.length!==2)throw new V(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Sd(e,1);return Ux(n,[1,t,1])})}function nG(e){let t=[ps(e.shape)];return W(e,t)}function aG(e){if(e.rank<=1)throw new V(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],ps(e.shape,1)];return W(e,t)}function ii(e,t,n){return P(()=>{switch(e.rank){case 1:return xd(e,t,n);case 2:return yf(e,[t,0],[n,e.shape[1]]);case 3:return qo(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Xl(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Ue(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Ue(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new V(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function bx(e,t,n){return P(()=>{switch(e.rank){case 1:return xd(e,t,n);case 2:return yf(e,[0,t],[e.shape[0],n]);case 3:return qo(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Xl(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Lh(e,t,n,a){return P(()=>{switch(e.rank){case 1:return xd(e,t,n);case 2:switch(a){case 1:return ii(e,t,n);case 2:return bx(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return ii(e,t,n);case 2:return qo(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return bx(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return ii(e,t,n);case 2:return Xl(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Xl(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return bx(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function a0(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),et(e,t)}function AI(e,t){switch(e.rank){case 1:return Qv([e,t]);case 2:return ew([e,t],0);case 3:return tw([e,t],0);case 4:return nw([e,t],0);default:throw new V(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ux(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new V(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ln(e,t)}function $f(e,t=0,n=1,a,r){return cf(e,t,n,a,r)}function ur(e,t,n,a){if(e.rank<2||t.rank<2)throw new Le(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(r!==s)throw new Le(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and  y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2)return Zl.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:a?Gx(e.rank,a,ja()):null,activation:n});{let r=e.shape.slice(),s=r.pop();e=W(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],p=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=W(De(t,p),[l,-1]);let d=[...r,...u],c=!1,h=!1;return W(Zl.matMul({a:e,b:t,transposeA:c,transposeB:h,bias:a?Gx(e.rank,a,ja()):null,activation:n}),d)}}function T2(e,t,n){return P(()=>(Array.isArray(t)?t=je(t,"int32"):t=se(t,"int32"),mp(e,t,n)))}function Nd(e){return z(e,e)}function Gx(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new V(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1,1,1]):W(t,[1,a[3],a[0],a[1],a[2]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,1,1,a[0]]):W(t,[1].concat(a))}else if(e===4){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1,1]):W(t,[1,a[2],a[0],a[1]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,1,a[0]]):W(t,[1].concat(a))}else if(e===3){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1]):W(t,[1,a[1],a[0]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,a[0]]):W(t,[1].concat(a))}else if(e<3)return t;throw new V(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ya(e,t,n){return P(()=>(n==null&&(n=ja()),Pt(n),X(e,Gx(e.rank,t,n))))}function rG(e,t=1){if(t!==1)throw new Le(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return cp(e)}function sG(e){return P(()=>he(e,X(Wt(e),1)))}function C2(e,t,n,a){return P(()=>zw(e,t,n,a))}function iG(e){return P(()=>{let t=X(.5,z(.2,e));return sn(t,0,1)})}function Td(e,t,n=!1){return n?e():t()}var oG=["fanIn","fanOut","fanAvg"],lG=["normal","uniform","truncatedNormal"];function uG(e){Xo(oG,"FanMode",e)}function pG(e){Xo(lG,"Distribution",e)}var Pa=class extends ne.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},r0=class extends Pa{apply(e,t){return Nt(e,t)}};r0.className="Zeros";ne.registerClass(r0);var Df=class extends Pa{apply(e,t){return Qn(e,t)}};Df.className="Ones";ne.registerClass(Df);var s0=class extends Pa{constructor(e){if(super(),typeof e!="object")throw new V(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new V(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return P(()=>z(ve(this.value),Qn(e,t)))}getConfig(){return{value:this.value}}};s0.className="Constant";ne.registerClass(s0);var i0=class extends Pa{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Fs(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};i0.className="RandomUniform";ne.registerClass(i0);var o0=class extends Pa{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`randomNormal does not support dType ${t}.`);return $f(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};o0.className="RandomNormal";ne.registerClass(o0);var l0=class extends Pa{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`truncatedNormal does not support dType ${t}.`);return If(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};l0.className="TruncatedNormal";ne.registerClass(l0);var u0=class extends Pa{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return P(()=>{if(e.length!==2||e[0]!==e[1])throw new V("Identity matrix initializer can only be used for 2D square matrices.");return z(this.gain,rf(e[0]))})}getConfig(){return{gain:this.gain}}};u0.className="Identity";ne.registerClass(u0);function cG(e,t="channelsLast"){let n,a;if(Pt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=ps(e,2);n=e[1]*r,a=e[0]*r}else if(t==="channelsLast"){let r=ps(e,0,e.length-2);n=e[e.length-2]*r,a=e[e.length-1]*r}}else{let r=ps(e);n=Math.sqrt(r),a=Math.sqrt(r)}return[n,a]}var Vn=class extends Pa{constructor(e){if(super(),e.scale<0)throw new V(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,uG(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,pG(this.distribution),this.seed=e.seed}apply(e,t){let n=cG(e),a=n[0],r=n[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,a):this.mode==="fanOut"?s/=Math.max(1,r):s/=Math.max(1,(a+r)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`${this.getClassName()} does not support dType ${t}.`);return If(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Fs(e,-i,i,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Vn.className="VarianceScaling";ne.registerClass(Vn);var Rf=class extends Vn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Vn.className}};Rf.className="GlorotUniform";ne.registerClass(Rf);var Mf=class extends Vn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Vn.className}};Mf.className="GlorotNormal";ne.registerClass(Mf);var Pf=class extends Vn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Vn.className}};Pf.className="HeNormal";ne.registerClass(Pf);var Of=class extends Vn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Vn.className}};Of.className="HeUniform";ne.registerClass(Of);var Lf=class extends Vn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Vn.className}};Lf.className="LeCunNormal";ne.registerClass(Lf);var zf=class extends Vn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Vn.className}};zf.className="LeCunUniform";ne.registerClass(zf);var p0=class extends Pa{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return P(()=>{if(e.length<2)throw new Le("Shape must be at least 2D.");if(t!=="int32"&&t!=="float32"&&t!==void 0)throw new TypeError(`Unsupported data type ${t}.`);t=t;let n=w.sizeFromShape(e.slice(0,-1)),a=e[e.length-1],r=n*a;r>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${r}) elements: Slowness may result.`);let s=[Math.max(a,n),Math.min(a,n)],i=$f(s,0,1,t,this.seed),o=Uw.qr(i,!1),l=o[0],u=o[1].flatten().stridedSlice([0],[Math.min(a,n)*Math.min(a,n)],[Math.min(a,n)+1]);return l=z(l,u.sign()),n<a&&(l=l.transpose()),z(ve(this.gain),l.reshape(e))})}getConfig(){return{gain:this.gain,seed:this.seed}}};p0.className="Orthogonal";ne.registerClass(p0);var FI={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 $I(e,t={}){return Id(e,ne.SerializationMap.getMap().classNameMap,t,"initializer")}function At(e){return t0(e)}function Tt(e){if(typeof e=="string"){let t=e in FI?FI[e]:e;if(t==="GlorotNormal")return new Mf;if(t==="GlorotUniform")return new Rf;if(t==="HeNormal")return new Pf;if(t==="HeUniform")return new Of;if(t==="LeCunNormal")return new Lf;if(t==="LeCunUniform")return new zf;{let n={};return n.className=t,n.config={},$I(n)}}else return e instanceof Pa?e:$I(e)}function Hx(e){return Array.isArray(e)&&Array.isArray(e[0])}function hm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ce(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new V(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Je(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new V(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function mm(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((a,r)=>a*r);return t}var DI="Variable",_2=class{constructor(e,t="float32",n=DI,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=w2(),n=n==null?DI:n,this.originalName=I2(n),this.name=S2(this.originalName),this.trainable_=a,this.constraint=r,this.val=Ow(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),dG(this.val,e),this.val.id!==e.id&&(this.val.assign(e),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(e){this.trainable_=e,this.val.trainable=e}};function dG(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function qx(e){return e.map(t=>t.read())}function c0(e){e.forEach(t=>{t[0].write(t[1])})}var Bt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},Va=class{constructor(e,t,n,a,r,s,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=a,this.callArgs=r,this.outputTensorIndex=i,this.id=w2(),s!=null&&(this.originalName=I2(s),this.name=S2(this.originalName)),this.rank=t.length}},hG=0,Wf=class{constructor(e,t){this.callArgs=t,this.id=hG++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},mG=0,Be=class extends ne.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=mG++,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 t=e.name;if(!t){let n=this.getClassName();t=_r(n)+"_"+Ff(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let a=e.dtype;a==null&&(a=e.inputDType),a==null&&(a="float32"),this.dtype=a}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Ba(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new V(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return On(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return On(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Cr(`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 Cr(`Layer ${this.name} is not connected, no input to return.`);return On(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Cr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Cr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return On(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}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(e){if(e=kt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=kt(this.inputSpec);if(e.length!==t.length)throw new V(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let a=e[n],r=t[n];if(r==null)continue;let s=a.rank;if(r.ndim!=null&&s!==r.ndim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${s}`);if(r.maxNDim!=null&&s>r.maxNDim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${s}`);if(r.minNDim!=null&&s<r.minNDim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${s}.`);if(r.dtype!=null&&a.dtype!==r.dtype)throw new V(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${a.dtype}.`);if(r.axes){let i=a.shape;for(let o in r.axes){let l=Number(o),u=r.axes[o],p=l>=0?i[l]:i[i.length+l];if(u!=null&&[u,null].indexOf(p)===-1)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} but got shape ${i}.`)}}if(r.shape!=null)for(let i=0;i<r.shape.length;++i){let o=r.shape[i],l=a.shape[i];if(o!=null&&l!=null&&o!==l)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${a.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let n=kt(e),a=!0;for(let s of n)if(!(s instanceof Va)){a=!1;break}let r=!0;for(let s of n)if(s instanceof Va){r=!1;break}if(a===r)throw new V("Arguments to apply() must be all SymbolicTensors or all Tensors");return si(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of kt(e))s.push(i.shape);this.build(On(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t),i=kt(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=On(o),this.activityRegularizer!=null)throw new Le("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=fG(e),i=this.computeOutputShape(s),o,l=gG(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((u,p)=>new Va(l,u,this,kt(e),t,this.name,p)):o=new Va(l,i,this,kt(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new Le("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,a)=>{n!=null&&e[a]!=null&&e[a]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) 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 Cr(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new Cr(`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 Ba(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return mm(this.weights)}build(e){this.built=!0}getWeights(e=!1){return qx(e?this.trainableWeights:this.weights)}setWeights(e){P(()=>{let t=this.weights;if(t.length!==e.length)throw new V(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],a=qx(t);for(let r=0;r<a.length;++r){let s=a[r],i=t[r],o=e[r];if(!w.arraysEqual(s.shape,o.shape))throw new V(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}c0(n)})}addWeight(e,t,n,a,r,s,i,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new V(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(a=o!=null?o():Tt("zeros"));let l=a.apply(t,n),u=new _2(l,n,e,s,i);return l.dispose(),r!=null&&this.addLoss(()=>r.apply(u.read())),s==null&&(s=!0),s?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=kt(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.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 t}addInboundNode(e,t,n,a,r,s,i=null){let o=kt(e);t=kt(t),n=kt(n),a=kt(a),r=hm(r),s=hm(s);let l=[],u=[],p=[];for(let d of o)l.push(d.sourceLayer),u.push(d.nodeIndex),p.push(d.tensorIndex);new Wf({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:p,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:a,inputShapes:r,outputShapes:s},i);for(let d=0;d<t.length;d++)t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d}getConfig(){let e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.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 e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function fG(e){e=kt(e);let t=[];for(let n of e)t.push(n.shape);return On(t)}function gG(e){return"float32"}function E2(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let a=t.inboundNodes[n];if(a.inboundLayers.length===0)return a.inputTensors;{let r=[];for(let s=0;s<a.inboundLayers.length;s++){let i=a.inputTensors[s],o=a.inboundLayers[s],l=a.nodeIndices[s],u=E2(i,o,l);for(let p of u)r.indexOf(p)===-1&&r.push(p)}return r}}}var gp=class extends Be{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:Ff("input").toString()}),e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new V("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new V("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new V("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let a=new Va(this.dtype,this.batchInputShape,this,[],{},this.name);a.nodeIndex=0,a.tensorIndex=0,new Wf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new V(`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}}};gp.className="InputLayer";ne.registerClass(gp);function A2(e){if(e.batchShape==null&&e.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(e.batchShape!=null&&e.shape!=null)throw new V("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let n=e.dtype;return n==null&&(n="float32"),new gp({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function bG(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return se(t,e.dtype)}catch(n){throw new V(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var ni=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof ni)for(let t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(let t of e)this.add(t.key,t.value)}}add(e,t,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=bG(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new V(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof Va){if(this.id2Value[e.id]==null)throw new V(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new V(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Va){if(this.id2Value[e.id]==null)throw new V(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new V(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&_e(this.id2Mask)}},fm=new y2,gm=new y2;function yG(e){fm!=null&&fm.setMaxEntries(e),gm!=null&&gm.setMaxEntries(e)}function sc(e,t,n,a){let r=n==null?!1:n.training,s=Array.isArray(e),i=s?e:[e],o=i.map(m=>m.name),l=[],u=t.names();for(let m of o)u.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);a!=null&&(a.maxNumTensors=-1/0,a.minNumTensors=1/0);let p=o.join(",")+"|"+t.names().sort().join(","),d=fm.get(p),c;if(d==null){let m=xG(i,t);d=m.sorted,c=m.recipientCounts,fm.put(p,d),gm.put(p,c)}c={},r||Object.assign(c,gm.get(p));let h=new ni(t);for(let m=0;m<d.length;++m){if(a!=null){let F=cm().numTensors;F>a.maxNumTensors&&(a.maxNumTensors=F),F<a.minNumTensors&&(a.minNumTensors=F)}let f=d[m],g=f.sourceLayer;if(g instanceof gp)continue;let b=[],y=[],x=[],v=!1;for(let F of f.inputs){let D=h.getValue(F),$=h.getMask(F);b.push(D),y.push($),$!=null&&(v=!0),r||(c[F.name]--,c[F.name]===0&&!t.hasKey(F)&&o.indexOf(F.name)===-1&&!D.isDisposed&&F.sourceLayer.stateful!==!0&&x.push(D))}v&&(n=n||{},n.mask=y[0]);let I=kt(g.apply(b,n)),T=null;g.supportsMasking&&(T=g.computeMask(b,y));let C=wG(f),E=Array.isArray(C)?C:[C];for(let F=0;F<E.length;++F){h.hasKey(E[F])||h.add(E[F],I[F],Array.isArray(T)?T[0]:T);let D=o.indexOf(E[F].name);D!==-1&&(l[D]=I[F])}r||_e(x)}return h.disposeMasks(),s?l:l[0]}function xG(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],a={};if(e.length===1){let r=RI(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=RI(s,t);for(let l of i)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in o)a[l]==null&&(a[l]=new Set),o[l].forEach(u=>a[l].add(u))}}return{sorted:n,recipientCounts:vG(a)}}function vG(e){let t={};for(let n in e)t[n]=e[n].size;return t}function RI(e,t){let n=new Set,a=[],r={};for(let o of t.names())n.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(n.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),a.push(o),n.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let u of o.inputs)r[u.name]==null&&(r[u.name]=new Set),r[u.name].add(o.name),!n.has(u.name)&&s.push(u)}}return{sorted:a,recipientMap:r}}function wG(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let a=0;a<e.sourceLayer.inboundNodes.length;++a)for(let r of e.sourceLayer.inboundNodes[a].outputTensors)if(r.id===e.id){n=a;break}t=e.sourceLayer.getOutputAt(n)}return t}var kG=G();kG.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,yG);var F2={};Ee(F2,{maxNorm:()=>IG,minMaxNorm:()=>TG,nonNeg:()=>NG,unitNorm:()=>SG});function d0(e,t){return P(()=>mn(fe(z(e,e),t,!0)))}var Cd=class extends ne.Serializable{getConfig(){return{}}},h0=class extends Cd{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return P(()=>{let t=d0(e,this.axis),n=sn(t,0,this.maxValue);return z(e,he(n,X(Kt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};h0.className="MaxNorm";ne.registerClass(h0);var m0=class extends Cd{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return P(()=>he(e,X(Kt(),d0(e,this.axis))))}getConfig(){return{axis:this.axis}}};m0.className="UnitNorm";ne.registerClass(m0);var f0=class extends Cd{apply(e){return Ke(e)}};f0.className="NonNeg";ne.registerClass(f0);var g0=class extends Cd{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return P(()=>{let t=d0(e,this.axis),n=X(z(this.rate,sn(t,this.minValue,this.maxValue)),z(1-this.rate,t));return z(e,he(n,X(Kt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};g0.className="MinMaxNorm";ne.registerClass(g0);var MI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Yt(e){return t0(e)}function PI(e,t={}){return Id(e,ne.SerializationMap.getMap().classNameMap,t,"constraint")}function Zt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in MI?MI[e]:e,config:{}};return PI(t)}else return e instanceof Cd?e:PI(e)}function IG(e){return new h0(e)}function SG(e){return new m0(e)}function NG(){return new f0}function TG(e){return new g0(e)}var $2={};Ee($2,{constant:()=>EG,glorotNormal:()=>PG,glorotUniform:()=>MG,heNormal:()=>OG,heUniform:()=>LG,identity:()=>DG,leCunNormal:()=>zG,leCunUniform:()=>WG,ones:()=>_G,orthogonal:()=>BG,randomNormal:()=>FG,randomUniform:()=>AG,truncatedNormal:()=>$G,varianceScaling:()=>RG,zeros:()=>CG});function CG(){return new r0}function _G(){return new Df}function EG(e){return new s0(e)}function AG(e){return new i0(e)}function FG(e){return new o0(e)}function $G(e){return new l0(e)}function DG(e){return new u0(e)}function RG(e){return new Vn(e)}function MG(e){return new Rf(e)}function PG(e){return new Mf(e)}function OG(e){return new Pf(e)}function LG(e){return new Of(e)}function zG(e){return new Lf(e)}function WG(e){return new zf(e)}function BG(e){return new p0(e)}var D2={};Ee(D2,{Layer:()=>Be,RNN:()=>br,RNNCell:()=>$d,activation:()=>f6,add:()=>S6,alphaDropout:()=>oq,average:()=>N6,averagePooling1d:()=>C1,averagePooling2d:()=>_1,averagePooling3d:()=>E1,avgPool1d:()=>R6,avgPool2d:()=>P6,avgPool3d:()=>L6,avgPooling1d:()=>M6,avgPooling2d:()=>O6,avgPooling3d:()=>z6,batchNormalization:()=>F6,bidirectional:()=>Q6,categoryEncoding:()=>dq,centerCrop:()=>pq,concatenate:()=>T6,conv1d:()=>i6,conv2d:()=>o6,conv2dTranspose:()=>l6,conv3d:()=>u6,conv3dTranspose:()=>p6,convLstm2d:()=>X6,convLstm2dCell:()=>Y6,cropping2D:()=>d6,dense:()=>g6,depthwiseConv2d:()=>m6,dot:()=>A6,dropout:()=>b6,elu:()=>e6,embedding:()=>I6,flatten:()=>x6,gaussianDropout:()=>iq,gaussianNoise:()=>sq,globalAveragePooling1d:()=>W6,globalAveragePooling2d:()=>B6,globalMaxPool1d:()=>tq,globalMaxPool2d:()=>nq,globalMaxPooling1d:()=>TC,globalMaxPooling2d:()=>CC,gru:()=>U6,gruCell:()=>G6,input:()=>Z2,inputLayer:()=>QH,layerNormalization:()=>$6,leakyReLU:()=>n6,lstm:()=>H6,lstmCell:()=>q6,masking:()=>lq,maxPool1d:()=>aq,maxPool2d:()=>rq,maxPooling1d:()=>_C,maxPooling2d:()=>EC,maxPooling3d:()=>V6,maximum:()=>C6,minimum:()=>_6,multiply:()=>E6,permute:()=>k6,prelu:()=>a6,randomWidth:()=>hq,reLU:()=>t6,repeatVector:()=>v6,rescaling:()=>uq,reshape:()=>w6,resizing:()=>cq,rnn:()=>Z6,separableConv2d:()=>c6,simpleRNN:()=>j6,simpleRNNCell:()=>K6,softmax:()=>r6,spatialDropout1d:()=>y6,stackedRNNCells:()=>J6,thresholdedReLU:()=>s6,timeDistributed:()=>eq,upSampling2d:()=>h6,zeroPadding2d:()=>D6});async function ts(e){if(e==null)return;let t=[],n=[],a=[];for(let r in e){let s=e[r];if(typeof s!="number"){let i=s;t.push(i.data()),n.push(r),a.push(i)}}if(t.length>0){let r=await Promise.all(t);for(let s=0;s<r.length;++s)e[n[s]]=r[s][0];_e(a)}}function R2(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var OI;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(OI||(OI={}));var VG=125,eu=class{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}},M2=class{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(let t of this.callbacks)t.setParams(e)}setModel(e){for(let t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainEnd(e)}},UG=class extends eu{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let a in t){let r=t[a];if(typeof r=="number")this.totals.hasOwnProperty(a)||(this.totals[a]=0),this.totals[a]=this.totals[a]+r*n;else{let s;a in this.totals?s=this.totals[a]:this.totals[a]=0;let i=P(()=>X(this.totals[a],z(r,n)));this.totals[a]=i,s!=null&&s.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:P(()=>{let a=z(he(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),qt(t[n])}))}},P2=class extends eu{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let s=this.history[r];for(let i=0;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(r),n.push(i)}}let a=await Promise.all(e);for(let r=0;r<a.length;++r)this.history[t[r]][n[r]].dispose(),this.history[t[r]][n[r]]=a[r][0]}},O2=class extends eu{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Qw,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=VG),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");w.isNumber(this.yieldEvery)&&(this.maybeWait=GU(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){let a=[];this.yield!=null&&(await ts(n),a.push(this.yield(e,t,n))),a.push(this.nextFrameFunc()),await Promise.all(a)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await ts(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await ts(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await ts(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await ts(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(this.nextFrameFunc()):w.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await ts(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await ts(e),await this.trainEnd(e))}};function L2(e,t){return e==null&&(e={}),e instanceof eu?[e]:Array.isArray(e)&&e[0]instanceof eu?e:kt(e).map(n=>new O2(n,t))}var Ea=class{constructor(){}static registerCallbackConstructor(e,t){w.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Ea.checkForDuplicate(t),Ea.constructors[e]==null&&(Ea.constructors[e]=[]),Ea.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Ea.constructors)Ea.constructors[+t].forEach(n=>{if(n===e)throw new V("Duplicate callback constructor.")})}static clear(){Ea.constructors={}}static createCallbacks(e){let t=[];for(let n in Ea.constructors){let a=+n;e>=a&&t.push(...Ea.constructors[a])}return t.map(n=>new n)}};Ea.constructors={};function z2(e,t,n,a,r,s,i,o,l){let u=new P2,p=[new UG,...Ea.createCallbacks(t)];e!=null&&p.push(...e),p.push(u);let d=new M2(p);return d.setParams({epochs:n,initialEpoch:a,samples:r,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:d,history:u}}function Ga(e,t={},n=!1){return Id(e,ne.SerializationMap.getMap().classNameMap,t,"layer",n)}function bm(e,t){return P(()=>{e.dtype!=="float32"&&(e=se(e,"float32"));let n=fe(Nd(e),t,!0),a=xn(n.shape,Kt()),r=mn(fr(n,a));return he(e,r)})}function Yo(e,t){return P(()=>Et(Nd(pe(t,e)),-1))}function Bf(e,t){return P(()=>Et(Wt(pe(t,e)),-1))}function bp(e,t){return P(()=>{let n=pe(e,t),a=sn(Wt(e),Kt(),Number.MAX_VALUE),r=Wt(he(n,a));return z(100,Et(r,-1))})}function GG(e,t){return P(()=>{let n=sn(t,Kt(),Number.MAX_VALUE),a=na(X(1,n)),r=sn(e,Kt(),Number.MAX_VALUE),s=na(X(1,r));return Et(Nd(pe(a,s)),-1)})}function HG(e,t){return P(()=>{let n=fr(0,pe(1,z(e,t)));return Et(Nd(n),-1)})}function qG(e,t){return P(()=>{let n=fr(0,pe(1,z(e,t)));return Et(n,-1)})}function jG(e,t){return P(()=>{let n=fe(z(e,t),-1),a=ga(z(pe(1,e),t),-1);return fr(0,X(1,pe(a,n)))})}function KG(e,t){return P(()=>{let n=Math.log(2),a=pe(t,e),r=pe(X(a,Ho(z(-2,a))),n);return Et(r,-1)})}function Tc(e,t,n=!1){return P(()=>{if(n)t=Xa(t);else{let a=fe(t,t.shape.length-1,!0);t=he(t,a)}return t=sn(t,Kt(),1-Kt()),yt(fe(z(se(e,"float32"),na(t)),t.shape.length-1))})}function ym(e,t,n=!1){return P(()=>{let a=se(hp(nG(e)),"int32");t=sn(t,Kt(),1-Kt());let r=t.shape,s=W(jl(a,r[r.length-1]),r);return Tc(s,t,n)})}function XG(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new V(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return P(()=>{let n=Ke(t),a=yt(Wt(t));return X(pe(n,z(t,e)),md(yn(a)))})}function Vf(e,t){return P(()=>{let n;return n=sn(t,Kt(),1-Kt()),n=na(he(n,pe(1,n))),Et(XG(e,n),-1)})}function YG(e,t){return P(()=>{let n=sn(e,Kt(),1),a=sn(t,Kt(),1);return fe(z(e,na(he(n,a))),-1)})}function ZG(e,t){return P(()=>{let n=na(X(Kt(),t));return Et(pe(t,z(e,n)),-1)})}function b0(e,t){return P(()=>{let n=bm(e,-1),a=bm(t,-1),r=z(n,a);return yt(fe(r,-1))})}var xm={meanSquaredError:Yo,meanAbsoluteError:Bf,meanAbsolutePercentageError:bp,meanSquaredLogarithmicError:GG,squaredHinge:HG,hinge:qG,categoricalHinge:jG,logcosh:KG,categoricalCrossentropy:Tc,sparseCategoricalCrossentropy:ym,binaryCrossentropy:Vf,kullbackLeiblerDivergence:YG,poisson:ZG,cosineProximity:b0};function yx(e){if(typeof e=="string"){if(e in xm)return xm[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new V(t)}else return e}function y0(e,t){return P(()=>{let n=z(.5,aa(t)),a=lr(_n(t,n),e.dtype);return Et(ta(e,a),-1)})}function x0(e,t){return P(()=>lr(ta(di(e,-1),di(t,-1)),"float32"))}function W2(e,t){return P(()=>se(fe(Da(ta(e,1),ta(t,1))),"float32"))}function JG(e,t){return P(()=>se(fe(Da(ta(e,1),ta(t,0))),"float32"))}function QG(e,t){return P(()=>se(fe(Da(ta(e,0),ta(t,1))),"float32"))}function B2(e,t){return P(()=>{let n=W2(e,t),a=QG(e,t),r=X(n,a);return se(rn(_n(r,0),he(n,r),0),"float32")})}function eH(e,t){return P(()=>{let n=W2(e,t),a=JG(e,t),r=X(n,a);return se(rn(_n(r,0),he(n,r),0),"float32")})}function V2(e,t){return Vf(e,t)}function U2(e,t){return e.rank===t.rank&&(e=Ds(e,[e.rank-1])),t=di(t,-1),t.dtype!==e.dtype&&(t=se(t,e.dtype)),se(ta(e,t),"float32")}var tH=Yo,nH=Yo,aH=Bf,rH=Bf,sH=bp,iH=bp,v0=Tc,oH=b0,G2=ym,vm={binaryAccuracy:y0,categoricalAccuracy:x0,precision:B2,categoricalCrossentropy:v0,sparseCategoricalCrossentropy:G2,mse:tH,MSE:nH,mae:aH,MAE:rH,mape:sH,MAPE:iH,cosine:oH};function lH(e){if(typeof e=="string"&&e in vm)return vm[e];if(typeof e!="string"&&e!=null)return e;throw new V(`Unknown metric ${e}`)}function zh(e){if(rr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(xm))if(xm[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(vm))if(vm[n]===e){t=n;break}return t!==void 0?t:e.name}}function uH(e){let t={Adagrad:()=>Xs.adagrad(.01),Adadelta:()=>Xs.adadelta(1,.95,Kt()),Adam:()=>Xs.adam(.001,.9,.999,Kt()),Adamax:()=>Xs.adamax(.002,.9,.999,Kt(),0),RMSProp:()=>Xs.rmsprop(.001,.9,0,Kt()),SGD:()=>Xs.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,e in t)return t[e]();throw new V(`Unknown Optimizer ${e}`)}function LI(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!jx(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let a=JSON.stringify(e);a.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${a.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 jx(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!jx(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!jx(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function pH(e,t,n,a=console.log){let r=dH(e),s=["Layer (type)","Input Shape","Output shape","Param #"];r?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map(p=>Math.floor(t*p)));let i;if(!r){s.push("Receives inputs"),i=[];for(let p in e.nodesByDepth)i.push(...e.nodesByDepth[p])}a("_".repeat(t)),wm(s,n,a),a("=".repeat(t));let o=e.layers;for(let p=0;p<o.length;++p)r?hH(o[p],n,a):mH(o[p],n,i,a),a((p===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=cH(e),u=mm(e.nonTrainableWeights);a(`Total params: ${l+u}`),a(`Trainable params: ${l}`),a(`Non-trainable params: ${u}`),a("_".repeat(t))}function cH(e){let t;return e.collectedTrainableWeights!=null?t=mm(e.collectedTrainableWeights):t=mm(e.trainableWeights),t}function dH(e){let t=!0,n=[],a=[];for(let r in e.nodesByDepth)n.push(e.nodesByDepth[r]);for(let r of n){if(r.length>1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}a.push(...r)}if(t)for(let r of e.layers){let s=!1;for(let i of r.inboundNodes)if(a.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function wm(e,t,n=console.log){let a="";for(let r=0;r<e.length;++r)r>0&&(a=a.slice(0,a.length-1)+" "),a+=e[r],a=a.slice(0,t[r]),a+=" ".repeat(t[r]-a.length);n(a)}function hH(e,t,n){let a,r;try{r=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){r="multiple"}try{a=JSON.stringify(e.outputShape)}catch(l){a="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,r,a,e.countParams().toString()];wm(o,t,n)}function mH(e,t,n,a){let r,s;try{s=e.inboundNodes.map(d=>JSON.stringify(d.inputShapes)).join(",")}catch(d){s="multiple"}try{r=JSON.stringify(e.outputShape)}catch(d){r="multiple"}let i=[];for(let d of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(d)===-1))for(let c=0;c<d.inboundLayers.length;++c){let h=d.inboundLayers[c].name,m=d.nodeIndices[c],f=d.tensorIndices[c];i.push(`${h}[${m}][${f}]`)}let o=e.name,l=e.getClassName(),u=i.length===0?"":i[0],p=[`${o} (${l})`,s,r,e.countParams().toString(),u];wm(p,t,a);for(let d=1;d<i.length;++d)wm(["","","","",i[d]],t,a)}function H2(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Cc(e,t){if(e===null)return null;if(typeof e=="string")return Js(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],a=e.length;for(let r=0;r<a;++r){let s=e[r];H2(t,r,s)?n.push(s):n.push(Cc(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a];if(a==="name"&&typeof r=="string")n[a]=r;else{let s=Js(a);n[s]=Cc(r,s)}}return n}}function Kx(e,t){if(e==null)return null;if(typeof e=="string")return _r(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],a=e.length;for(let r=0;r<a;++r){let s=e[r];H2(t,r,s)?n.push(s):n.push(Kx(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a],s=_r(a);(a==="name"||a==="className")&&typeof r=="string"?n[s]=r:n[s]=Kx(r,a)}return n}}var w0="4.7.0",nr=class extends Be{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=Ff(b)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],us(this.inputs).length!==this.inputs.length)throw new V(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);us(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 y=b.sourceLayer,x=b.nodeIndex,v=b.tensorIndex;this.outputLayers.push(y),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(v)}for(let b of this.inputs){let y=b.sourceLayer,x=b.nodeIndex,v=b.tensorIndex;rr(x===0,"input layer has >1 nodes"),rr(v===0,"input layer has >1 tensors"),this.inputLayers.push(y),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(v)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let y=this.inputLayers[b];if(!(y instanceof gp))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${y.getClassName()}.`);this.inputNames.push(y.name),this.feedInputShapes.push(y.batchInputShape),this.feedInputNames.push(y.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 t={},n={},a={},r={},s={},i=[],o=(b,y,x,v,I,T)=>{(v==null||I==null||T==null)&&(v=b.sourceLayer,I=b.nodeIndex,T=b.tensorIndex);let C=v.inboundNodes[I];if(x.indexOf(C)!==-1)throw new Ba(`The tensor ${b.name} at layer "${v.name}" is part of a cycle.`);if(y.indexOf(C)!==-1)return;this.containerNodes.add(nr.nodeKey(v,I)),v.id in s||(s[v.id]=Object.keys(s).length),x.indexOf(C)===-1&&x.push(C);let E=C.inboundLayers.length;for(let F=0;F<E;F++){let D=C.inputTensors[F],$=C.inboundLayers[F],S=C.nodeIndices[F],M=C.tensorIndices[F];o(D,y,x,$,S,M)}for(y.push(C);x.indexOf(C)>=0;)x.splice(x.indexOf(C),1);i.push(C)},l=[],u=[];for(let b of this.outputs)o(b,l,u);let p=i.slice().reverse();for(let b of p){n[b.id]=b,b.id in t||(t[b.id]=0);let y=t[b.id],x=a[b.outboundLayer.id]==null?0:a[b.outboundLayer.id];y=Math.max(y,x),a[b.outboundLayer.id]=y,r[b.outboundLayer.id]=b.outboundLayer,t[b.id]=y;for(let v=0;v<b.inboundLayers.length;v++){let I=b.inboundLayers[v],T=b.nodeIndices[v],C=I.inboundNodes[T],E=t[C.id]==null?0:t[C.id];t[C.id]=Math.max(y+1,E),n[C.id]=C}}let d={};for(let b in t){let y=t[b];y in d||(d[y]=[]),d[y].push(n[b])}let c={};for(let b in a){let y=a[b];y in c||(c[y]=[]),c[y].push(r[b])}let h=Object.keys(c).map(b=>parseInt(b,10)).sort(Ph);this.layers=[];for(let b of h){let y=c[b];y.sort((x,v)=>{let I=s[x.id],T=s[v.id];return I<T?-1:I>T?1:0});for(let x of y)x instanceof nr&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=c,h=Object.keys(d).map(b=>parseInt(b,10)).sort(Ph);let m=this.inputs.slice(),f=[];for(let b of h)for(let y of d[b]){let x=y.outboundLayer;if(x!=null){for(let v of y.inputTensors)if(m.indexOf(v)===-1)throw new Ba(`Graph disconnected: cannot obtain value for tensor ${v} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(let v of y.outputTensors)m.push(v);f.push(x.name)}}this.nodesByDepth=d;let g=this.layers.map(b=>b.name);for(let b of g){let y=g.filter(x=>x===b).length;if(y!==1)throw new Ba(`The name "${b}" is used ${y} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Wf({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 e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new V("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 e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},a=0;for(let s of this.layers)for(let i of s.weights){if(n[i.originalName]!=null)throw new V(`Duplicate weight name: ${i.originalName}`);n[i.originalName]=i,a++}let r=[];for(let s in e){let i=s;if(n[s]==null){let o=s.split("/");i=o.slice(0,-2).concat([o[o.length-1]]).join("/")}if(n[i]!=null)r.push([n[i],e[s]]);else if(t)throw new V(`Provided weight data has no target variable: ${s}`);delete n[i]}if(t){let s=[];for(let i in n)s.push(i);if(s.length>0)throw new V(`${s.length} of ${a} weights are not set: ${s}`)}c0(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${w0}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=Kx(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return P(()=>{e=kt(e);let n=new ni;for(let a=0;a<this.inputs.length;++a)n.add(this.inputs[a],e[a]);return sc(this.outputs,n,t)})}computeMask(e,t){return P(()=>{e=kt(e);let n;return t==null?n=yi(null,e.length):n=kt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=hm(e);if(t.length!==this.inputLayers.length)throw new V(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let i=0;i<t.length;i++){let o=this.inputLayers[i],l=t[i],u=o.name+"_0_0";n[u]=l}let a=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(Ph);if(a.length>1)for(let i of a){let o=this.nodesByDepth[i];for(let l of o){let u=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;let p=[];for(let m=0;m<l.inboundLayers.length;m++){let f=l.inboundLayers[m],g=l.nodeIndices[m],b=l.tensorIndices[m],y=`${f.name}_${g}_${b}`,x=n[y];p.push(x)}let d=u.computeOutputShape(On(p)),c=hm(d),h=u.inboundNodes.indexOf(l);for(let m=0;m<c.length;m++){let f=`${u.name}_${h}_${m}`;n[f]=c[m]}}}let r=[],s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],u=this.outputLayersTensorIndices[i],p=`${o.name}_${l}_${u}`;s.push(p)}for(let i=0;i<s.length;i++){let o=s[i];rr(o in n),r.push(n[o])}return On(r)}runInternalGraph(e,t){t==null&&(t=yi(null,e.length));let n={};for(let o=0;o<this.inputs.length;++o){let l=this.inputs[o],u=e[o],p=t[o];n[l.id]=[u,p]}let a=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Ph);for(let o of a){let l=this.nodesByDepth[o];for(let u of l){let p=u.outboundLayer,d=u.inputTensors,c=u.outputTensors,h=new Array;for(let m of d)m.id in n&&h.push(n[m.id]);if(h.length===d.length){let m={},f,g,b,y;if(u.callArgs!=null&&(m=u.callArgs),h.length===1){let[x,v]=h[0];m.mask==null&&(m.mask=v),b=kt(p.call(x,m)),y=kt(p.computeMask(x,v)),f=[x],g=[v]}else f=h.map(x=>x[0]),g=h.map(x=>x[1]),m.mask==null&&(m.mask=g),b=kt(p.call(f,m)),y=kt(p.computeMask(f,g));if(p.activityRegularizer)throw new Le("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x<c.length;++x){let v=c[x],I=b[x],T=y[x];n[v.id]=[I,T]}}}}let r=[],s=[],i=[];for(let o of this.outputs){rr(o.id in n,`Could not compute output ${o.name} : ${o.id}`);let[l,u]=n[o.id];i.push(l.shape),r.push(l),s.push(u)}return[r,s,i]}buildNodeConversionMap(e){let t={},n;for(let a of this.layers){n=a instanceof nr?1:0;for(let r=0;r<a.inboundNodes.length;r++){let s=nr.nodeKey(a,r);this.containerNodes.has(s)&&(t[s]=n,n+=1)}}return t}getLayer(e,t){if(t!=null)return this.findLayer(t);if(e==null)throw new V("Provide either a layer name or layer index");if(typeof e=="number")return this.findLayer(e);for(let n of this.layers)if(n.name===e)return n;throw new V(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new V(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return P(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let a=nr.nodeKey(t,n);this.containerNodes.has(a)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let s of this.layers){let i=s.getClassName(),o=s.getConfig(),l=[];for(let p=0;p<s.inboundNodes.length;p++){let d=s.inboundNodes[p],c=nr.nodeKey(s,p),h={};if(this.containerNodes.has(c)){if(d.callArgs)try{JSON.stringify(d.callArgs),h=d.callArgs}catch(m){console.warn(`Layer ${s.name} was passed non-serializable keyword arguments: ${d.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),h={}}if(d.inboundLayers.length>0){let m=[];for(let f=0;f<d.inboundLayers.length;f++){let g=d.inboundLayers[f],b=d.nodeIndices[f],y=d.tensorIndices[f],x=nr.nodeKey(g,b),v=t[x];v==null&&(v=0),m.push([g.name,v,y,h])}l.push(m)}}}let u={};u.name=s.name,u.className=i,u.config=o,u.inboundNodes=l,n.push(u)}e.layers=n;let a=[];for(let s=0;s<this.inputLayers.length;s++){let i=this.inputLayers[s],o=this.inputLayersNodeIndices[s],l=nr.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let p=this.inputLayersTensorIndices[s];a.push([i.name,u,p])}e.inputLayers=a;let r=[];for(let s=0;s<this.outputLayers.length;s++){let i=this.outputLayers[s],o=this.outputLayersNodeIndices[s],l=nr.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let p=this.outputLayersTensorIndices[s];r.push([i.name,u,p])}return e.outputLayers=r,e}static fromConfig(e,t,n={},a=!1){let r={},s={};function i(f,g){f.name in s?s[f.name].push(g):s[f.name]=[g]}function o(f,g){let b=[],y;for(let x of g){let v=x[0],I=x[1],T=x[2];if(y=x[3]==null?{}:x[3],!(v in r)){i(f,g);return}let C=r[v];if(C.inboundNodes.length<=I){i(f,g);return}let E=C.inboundNodes[I];b.push(E.outputTensors[T])}b.length>0&&f.apply(On(b),y)}function l(f){let g=f.name,b=Ga(f,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(a),r[g]=b,f.inboundNodes.forEach(y=>{if(!(y instanceof Array))throw new V(`Corrupted configuration, expected array for nodeData: ${y}`);i(b,y)})}let u=t.name,p=t.layers;for(let f of p)l(f);for(;!UU(s);)for(let f of p){let g=r[f.name];if(g.name in s){let b=s[g.name];delete s[g.name];for(let y of b)o(g,y)}}let d=[],c=[],h=t.inputLayers;for(let f of h){let g=f[0],b=f[1],y=f[2];rr(g in r);let x=r[g].inboundNodes[b].outputTensors;d.push(x[y])}let m=t.outputLayers;for(let f of m){let g=f[0],b=f[1],y=f[2];rr(g in r);let x=r[g].inboundNodes[b].outputTensors;c.push(x[y])}return new e({inputs:d,outputs:c,name:u})}get stateful(){if(this._stateful)throw new V("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 e of this.layers)if(e.stateful)return!0;return!1}resetStates(){P(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function fH(e,t,n){let a=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(a===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==a)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${a} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(s=>{s in e?r.push(e[s]):r.push(null)}),r}else throw new Error(`The model has multiple (${a}) outputs, so ${n} must be either an array with ${a} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function q2(e,t){return fH(e,t,"classWeight")}async function j2(e,t,n,a){if(t!=null||a!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=P(()=>{if(e.shape.length===1)return or(e);if(e.shape.length===2){if(e.shape[1]>1)return di(e,1);if(e.shape[1]===1)return W(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),s=Array.from(await r.data());_e(r);let i=[];return s.forEach(o=>{if(n[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(n[o])}),je(i,"float32")}else return null}function gH(e,t){return z(e,t)}var bH=32;function K2(e,t){let n,a,r=t;n=r.xs,a=r.ys,w.assert(n!=null&&a!=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=zI("input",e.inputNames,n),i=zI("output",e.outputNames,a),o=s[0].shape[0];w.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs.  (Expected input keys: ${JSON.stringify(e.inputNames)})`),w.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs.  (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<s.length;l++)w.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)w.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function zI(e,t,n){if(n instanceof Te)return[n];if(Array.isArray(n))return w.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let a=[];for(let r of t){if(n[r]==null)throw new V(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function yH(e){if(e.length===3)throw new Le("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function xH(e,t,n){let a=n.batchesPerEpoch!=null;if(w.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),w.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),w.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),w.assert(!a||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),w.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,s,i;if(r)if(WI(n.validationData))w.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=yH(n.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;r?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let p=L2(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:c,history:h}=z2(p,d,n.epochs,null,null,vH(t,n),null,r,u);c.setModel(e),e.history=h,await c.onTrainBegin(),e.stopTraining_=!1;let m=n.initialEpoch==null?0:n.initialEpoch,f=await t.iterator();for(;m<n.epochs;){let g={};await c.onEpochBegin(m);let b=0,y=0;for(a||(f=await t.iterator());!a||b<n.batchesPerEpoch;){let x=await f.next();if(a&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${b} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){let{xs:v,ys:I}=K2(e,x.value),T={};T.batch=y,T.size=v[0].shape[0],await c.onBatchBegin(y,T);let C=[];if(n.classWeight!=null){let D=q2(n.classWeight,e.outputNames);for(let $=0;$<D.length;++$)C.push(await j2(I[$],null,D[$]))}let E=v.concat(I).concat(C),F=o(E);_e(E);for(let D=0;D<l.length;++D){let $=l[D],S=F[D];T[$]=S,qt(S)}await c.onBatchEnd(y,T),R2(T),y++,b++}if(a?b>=n.batchesPerEpoch:x.done){if(r){let v;WI(n.validationData)?v=kt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):v=kt(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?bH:n.validationBatchSize,verbose:0}));for(let I=0;I<e.metricsNames.length;++I)g[`val_${e.metricsNames[I]}`]=v[I]}break}if(e.stopTraining_)break}if(await c.onEpochEnd(m,g),m++,e.stopTraining_)break}return await c.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function vH(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function WI(e){return typeof e.iterator=="function"}function wH(e){return typeof e.next=="function"}async function kH(e,t,n){n=n||{};let a=n.batches!=null,r=e.testFunction,s=[];if(n.verbose>0)throw new Le("Verbose mode is not implemented yet.");w.assert(!a||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let i=wH(t)?t:await t.iterator(),o=0,l=0;for(;!a||l<n.batches;){let u=await i.next();if(s=P(()=>{if(u.value){let{xs:p,ys:d}=K2(e,u.value),c=p.concat(d),h=P(()=>r(c));if(_e(c),l===0)for(let f=0;f<h.length;++f)s.push(ve(0));let m=c[0].shape[0];for(let f=0;f<h.length;++f){let g=h[f],b=s[f];s[f]=P(()=>X(s[f],z(m,g))),l>0&&_e(b)}_e(h),o+=m,++l}return s}),u.done){a&&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, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u<s.length;++u){let p=s[u];s[u]=he(s[u],o),_e(p)}return On(s)}function xx(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Qp(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(a=>ii(a,t,n-t)):ii(e,t,n-t)}function Xx(e,t){return P(()=>e==null?null:Array.isArray(e)?e.map(n=>Xx(n,t)):T2(e,t.dtype==="int32"?t:se(t,"int32")))}function vx(e,t){let n=[],a=0,r=null;for(;a<e;)r=a+t,r>=e&&(r=e),n.push([a,r]),a=r;return n}function X2(e){let t=[];e instanceof Te&&(e=[e]);for(let n=0;n<e.length;++n){let a=e[n];if(a.rank===1)t.push(Sd(a,1));else{if(a.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(a)}}return t}function za(e,t){if(e==null)return;let n=[];if(t instanceof Te)n.push(t.id);else if(Array.isArray(t))t.forEach(r=>n.push(r.id));else if(t!=null)for(let r in t){let s=t[r];n.push(s.id)}let a=[];if(e instanceof Te)n.indexOf(e.id)===-1&&a.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&a.push(r)});else if(e!=null)for(let r in e){let s=e[r];n.indexOf(s.id)===-1&&a.push(s)}a.forEach(r=>{r.isDisposed||r.dispose()})}function IH(e){return e instanceof Te}function Yx(e){return Array.isArray(e)}function BI(e){return!IH(e)&&!Yx(e)}function VI(e,t,n,a=!0,r=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(Yx(e)&&e.length>0)i=!0;else if(BI(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new V(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(BI(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new V(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(Yx(e)){if(e=e,e.length!==t.length)throw new V(`Error when checking model ${r}: 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): ${e}`);s=e}else{if(e=e,t.length>1)throw new V(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=X2(s),n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new V(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let u=o.shape[l],p=n[i][l];if(p!=null&&p>=0&&u!==p)throw new V(`${r} expected a batch of elements where each example has shape [${n[i].slice(1,n[i].length)}] (i.e.,tensor shape [*,${n[i].slice(1,n[i].length)}]) but the ${r} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return s}function SH(e,t,n){let a=us(e.map(s=>s.shape[0]));a.sort();let r=us(t.map(s=>s.shape[0]));if(r.sort(),a.length>1)throw new V(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(r.length>1)throw new V(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(a.length>0&&r.length>0&&!w.arraysEqual(a,r))throw new V(`Input Tensors should have the same number of samples as target Tensors. Found ${a[0]} input sample(s) and ${r[0]} target sample(s).`)}function NH(e,t,n){let a=[Yo,Vf,Tc];for(let r=0;r<e.length;++r){let s=e[r],i=t[r],o=n[r];if(i!=null){if(i===Tc&&s.shape[s.shape.length-1]===1)throw new V(`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(a.indexOf(i)!==-1){let l=s.shape.slice(1),u=o.slice(1);for(let p=0;p<l.length;++p){let d=l[p],c=u[p];if(c!=null&&d!==c)throw new V(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function UI(e,t,n,a=!0,r=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new V(`Error when checking model ${r}: 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 ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new V(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new V(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let u=o.shape[l],p=n[i][l];if(p!=null&&p!==u)throw new V(`Error when checking ${r}: expected ${t[i]} to have shape ${JSON.stringify(n[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function TH(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(a=>n);{let a=[];for(let r of t){let s=n.hasOwnProperty(r)?n[r]:[];Array.isArray(s)||(s=[s]),a.push(s)}return a}}var CH="layers-model",Dr=class extends nr{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new V("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).");pH(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=uH(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof zr))throw new V("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new V(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(yx(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new V(`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=${e.loss}.`);t=e.loss.map(s=>yx(s))}else{let s=yx(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){let i=this.internalOutputShapes[s],o=this.outputNames[s];this.feedOutputNames.push(o),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[s])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],si("loss",()=>{for(let s=0;s<this.outputs.length;++s){if(n.indexOf(s)!==-1)continue;let i=this.lossFunctions[s];this.outputs.length>1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let a=TH(e.metrics,this.outputNames),r=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};si("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(n.indexOf(s)!==-1)continue;let i=a[s];(o=>{let l="",u,p,d;for(let c of o){if(typeof c=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(c)!==-1){let m=this.internalOutputShapes[s];m[m.length-1]===1||this.lossFunctions[s]===Vf?["accuracy","acc"].indexOf(c)!==-1?p=y0:["crossentropy","ce"].indexOf(c)!==-1&&(p=V2):this.lossFunctions[s]===ym?["accuracy","acc"].indexOf(c)!==-1?p=U2:["crossentropy","ce"].indexOf(c)!==-1&&(p=G2):["accuracy","acc"].indexOf(c)!==-1?p=x0:["crossentropy","ce"].indexOf(c)!==-1&&(p=v0);let f;["accuracy","acc"].indexOf(c)!==-1?f="acc":["crossentropy","ce"].indexOf(c)!==-1&&(f="ce"),d=p,u=l+f}else d=lH(c),u=l+zh(c);let h;si(u,()=>{h=d}),r(s,u,h)}})(i)}}),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(e,t,n={}){let a=n.batchSize==null?32:n.batchSize;xx(a);let r=!0,s=this.standardizeUserDataXY(e,t,r,a);try{let i=s[0].concat(s[1]);this.makeTestFunction();let o=this.testFunction,l=this.testLoop(o,i,a,n.verbose,n.steps);return On(l)}finally{za(s[0],e),za(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),kH(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new V(`If ${a} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new V(`Either the input data should have a defined shape, or ${a} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new V("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new ni;if(e instanceof Te&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new V(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new V(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=sc(r,s);return n?i:i[0]}retrieveSymbolicTensors(e){let t=yi(null,e.length),n=e.length;for(let a of this.layers){let r=Array.isArray(a.output)?a.output:[a.output],s=r.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=r[o],n--),n===0)break}if(n===0)break}if(n>0){let a=[];throw t.forEach((r,s)=>{r==null&&a.push(e[s])}),new V(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,n=!1){return P(()=>{let a=this.checkNumSamples(e);if(n)throw new Le("Verbose predictLoop() is not implemented yet.");let r=vx(a,t),s=this.outputs.map(i=>[]);for(let i=0;i<r.length;++i)P(()=>{let o=r[i][0],l=r[i][1],u=Qp(e,o,l),p=[];if(Array.isArray(u))for(let c=0;c<u.length;++c)p.push({key:this.inputs[c],value:u[c]});else p.push({key:this.inputs[0],value:u});let d=new ni(p);return sc(this.outputs,d)}).forEach((o,l)=>s[l].push(o));return On(s.map(i=>et(i,0)))})}predict(e,t={}){let n=X2(e);UI(n,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return xx(a),this.predictLoop(n,a)}finally{za(n,e)}}predictOnBatch(e){UI(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,a){if(this.optimizer_==null)throw new Ba("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===ym?r.push(i.slice(0,i.length-1).concat([1])):r.push(i)}if(e=VI(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=VI(t,this.feedOutputNames,r,!1,"target"),SH(e,t,null),NH(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&a!=null&&a>0&&e[0].shape[0]%a!==0)throw new V(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${a}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,a,r=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,r,s);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(a!=null){let u=q2(a,this.outputNames);l=[];for(let p=0;p<u.length;++p)l.push(await j2(o[p],null,u[p]))}return[i,o,l]}testLoop(e,t,n,a=0,r){return P(()=>{let s=this.checkNumSamples(t,n,r,"steps"),i=[];if(a>0)throw new Le("Verbose mode is not implemented yet.");if(r!=null)throw new Le("steps mode in testLoop() is not implemented yet");{let o=vx(s,n),l=je(qa(0,s));for(let u=0;u<o.length;++u){let p=o[u][0],d=o[u][1],c=ii(l,p,d-p),h=Xx(t,c),m=e(h);if(u===0)for(let f=0;f<m.length;++f)i.push(ve(0));for(let f=0;f<m.length;++f){let g=m[f];i[f]=X(i[f],z(d-p,g))}}for(let u=0;u<i.length;++u)i[u]=he(i[u],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let a=e[n],r=a;if(_I(e,a)>1){let s=_I(e.slice(0,n),a);r+=`_${s}`}t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let u=[];for(let h=0;h<this.inputs.length;++h)u.push({key:this.inputs[h],value:n[h]});let p=new ni(u),d=sc(this.outputs,p,{training:!0}),c;for(let h=0;h<this.lossFunctions.length;++h){let m=this.lossFunctions[h],f=m(a[h],d[h]);r[h]!=null&&(f=gH(f,r[h]));let g=Et(f);t.push(g),h===0?c=f:c=X(c,f)}for(let h=0;h<this.metricsTensors.length;++h){let m;if(this.outputs.length>1&&h<this.outputs.length)m=t[h];else{let f=this.metricsTensors[h][0],g=this.metricsTensors[h][1];m=Et(f(a[g],d[g]))}qt(m),s.push(m)}return c=Et(c),this.calculateLosses().forEach(h=>{c=X(c,h)}),c},o=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>P(()=>{let t=[],n,a=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;l<this.inputs.length;++l)s.push({key:this.inputs[l],value:a[l]});let i=new ni(s),o=sc(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let u=this.lossFunctions[l],p=Et(u(r[l],o[l]));l===0?n=p:n=X(n,p),t.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let u=this.metricsTensors[l][0],p=this.metricsTensors[l][1],d=Et(u(r[p],o[p]));t.push(d)}return t})}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");this.isTraining=!0;let a,r,s,i,o,l,u,p,d;try{let c=n.batchSize==null?32:n.batchSize;xx(c);let h=!1,m=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,h,c);a=m[0],r=m[1],d=m[2];let f=!1,g;if(n.validationData!=null&&n.validationData.length>0){if(f=!0,n.validationData.length===2)o=n.validationData[0],l=n.validationData[1];else throw n.validationData.length===3?new Le("validationData including sample weights is not supported yet."):new V(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);let C=!0,E=await this.standardizeUserData(o,l,null,null,C,c);u=E[0],p=E[1],g=u.concat(p)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){f=!0;let C=Math.floor(a[0].shape[0]*(1-n.validationSplit)),E=a[0].shape[0];u=Qp(a,C,E),s=a,a=Qp(a,0,C),p=Qp(r,C,E),i=r,r=Qp(r,0,C),g=u.concat(p)}else n.validationSteps!=null&&(f=!0);let b=a.concat(r).concat(d);this.checkTrainableWeightsConsistency();let y=this.makeTrainFunction(),x=this.getDedupedMetricsNames(),v,I;f?(this.makeTestFunction(),v=this.testFunction,I=x.slice().concat(x.map(C=>"val_"+C))):(v=null,g=[],I=x.slice());let T=L2(n.callbacks,n.yieldEvery);return await this.fitLoop(y,b,x,c,n.epochs,n.verbose,T,v,g,n.shuffle,I,n.initialEpoch,null,null)}finally{this.isTraining=!1,za(a,e),za(r,t),za(s,e),za(i,t),za(u,o),za(p,l),d!=null&&_e(d)}}async fitLoop(e,t,n,a,r,s,i,o,l,u,p,d,c,h){a==null&&(a=32),r==null&&(r=1),u==null&&(u=!0),d==null&&(d=0);let m=!1;if(o!=null&&l!=null&&(m=!0),h!=null&&(m=!0,c==null))throw new V("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let f=this.checkNumSamples(t,a,c,"steps_per_epoch"),g;f!=null&&(g=qa(0,f)),s==null&&(s=1);let{callbackList:b,history:y}=z2(i,s,r,d,f,c,a,m,p);b.setModel(this),this.history=y,await b.onTrainBegin(),this.stopTraining_=!1;for(let x=d;x<r;++x){await b.onEpochBegin(x);let v={};if(c!=null)throw new Le("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new Le("batch shuffling is not implemneted yet");u&&w.shuffle(g);let I=je(g),T=vx(f,a);for(let C=0;C<T.length;++C){let E={};if(await b.onBatchBegin(C,E),P(()=>{let F=T[C][0],D=T[C][1],$=ii(I,F,D-F);E.batch=C,E.size=D-F;let S=Xx(t,$),M=e(S);for(let B=0;B<n.length;++B){let U=n[B],H=M[B];E[U]=H,qt(H)}if(C===T.length-1&&m){let B=this.testLoop(o,l,a);for(let U=0;U<n.length;++U){let H=n[U],j=B[U];qt(j),v["val_"+H]=j}}}),await b.onBatchEnd(C,E),R2(E),this.stopTraining_)break}I.dispose()}if(await b.onEpochEnd(x,v),this.stopTraining_)break}return await b.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return xH(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),a=n[0],r=n[1],s=this.makeTrainFunction()(a.concat(r)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return _e(s),za(n[0],e),za(n[1],t),On(i)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,a=n?this.trainableWeights:this.weights,r=this.getWeights(n);for(let s=0;s<a.length;++s)n&&!a[s].trainable||t.push({name:a[s].originalName,tensor:r[s]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=cm().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-cm().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=_r(this.loss);else if(Array.isArray(this.loss)){for(let t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>_r(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let a of t)if(typeof n[a]=="string")e[a]=_r(n[a]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[_r(zh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>_r(zh(e)));{let e={};for(let t in this.metrics)e[t]=_r(zh(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let t=Cc(e.optimizer_config),n=Ga(t),a;if(typeof e.loss=="string")a=Js(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>Js(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=Js(e.loss[s])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(s=>Js(s));else if(e.metrics!=null){r={};for(let s in e.metrics)r[s]=Js(e.metrics[s])}this.compile({loss:a,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let i=jt.getSaveHandlers(e);if(i.length===0)throw new V(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new V(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new V("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await jt.encodeWeights(this.getNamedWeights(t)),a=!1,r=null,s={modelTopology:this.toJSON(r,a),format:CH,generatedBy:`TensorFlow.js tfjs-layers v${w0}`,convertedBy:null};if(t!=null&&t.includeOptimizer&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await jt.encodeWeights(await this.optimizer.getWeights(),i);n.specs.push(...l),n.data=jt.concatenateArrayBuffers([n.data,o])}return this.userDefinedMetadata!=null&&(LI(this.userDefinedMetadata,this.name,!0),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){LI(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Dr.className="Model";ne.registerClass(Dr);var Y2=class extends Dr{};Y2.className="Functional";ne.registerClass(Y2);async function _H(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=Cc(n),r=Ga(a,t);if(e.weightsManifest!=null){let s=await jt.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(o=>o.originalName)),i={};for(let o of r.weights)i[o.originalName]=s[o.originalName];r.loadWeights(i),_e(s)}return r}async function EH(e,t){if(t==null&&(t={}),typeof e=="string"){let n=jt.getLoadHandlers(e,t);if(n.length===0)n.push(jt.browserHTTPRequest(e,t));else if(n.length>1)throw new V(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return AH(e,void 0,t)}async function AH(e,t,n){if(n==null&&(n={}),e.load==null)throw new V("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let a=await e.load(),r=a.modelTopology;r.model_config!=null&&(r=r.model_config);let s=n.strict==null?!0:n.strict,i=a.weightData!=null&&a.weightSpecs!=null&&s,o=Ga(Cc(r),t,i),l=a.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),a.userDefinedMetadata!=null&&o.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new V("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:p}=FH(a.weightData,a.weightSpecs);o.loadWeights(u,s),o.optimizer!=null&&p.length>0&&await o.optimizer.setWeights(p),_e(u),_e(p.map(d=>d.tensor))}return o}function FH(e,t){let n=jt.decodeWeights(e,t),a={},r=[];return t.forEach(s=>{s.group==="optimizer"?r.push({name:s.name,tensor:n[s.name]}):a[s.name]=n[s.name]}),{modelWeights:a,optimizerWeights:r}}var tu=class extends Dr{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Ff("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<0))throw new V(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof tu||e instanceof Dr,n;if(t){if(n=e,n.outputs.length!==1)throw new V("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 V("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(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new V("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=A2({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(a)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new V(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new V("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=E2(this.outputs[0])}this.inboundNodes=[],new Wf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:yi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(a=>a.shape),outputShapes:this.outputs[0].shape})}else{let a=e.apply(this.outputs[0]);if(Array.isArray(a))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(e),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),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 e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(Je(e),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 Dr({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(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Ba("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Ba("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),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(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Ba("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Ba("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},a=!1){let r,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new V("Legacy serialization format not supported yet.");r=t}else w.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof tu))throw new Le(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of r){let l=Ga(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new V("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new V("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}};tu.className="Sequential";ne.registerClass(tu);function $H(e){return new Dr(e)}function DH(e){return new tu(e)}function Z2(e){return A2(e)}function RH(e,t){Ea.registerCallbackConstructor(e,t)}var Gn=class extends ne.Serializable{getConfig(){return{}}},J2=class extends Gn{apply(e,t=1){return rG(e,t)}};J2.className="elu";ne.registerClass(J2);var Q2=class extends Gn{apply(e){return ff(e)}};Q2.className="selu";ne.registerClass(Q2);var eC=class extends Gn{apply(e){return Ke(e)}};eC.className="relu";ne.registerClass(eC);var tC=class extends Gn{apply(e){return P(()=>fs(6,Ke(e)))}};tC.className="relu6";ne.registerClass(tC);var nC=class extends Gn{apply(e){return e}};nC.className="linear";ne.registerClass(nC);var aC=class extends Gn{apply(e){return fa(e)}};aC.className="sigmoid";ne.registerClass(aC);var rC=class extends Gn{apply(e){return iG(e)}};rC.className="hardSigmoid";ne.registerClass(rC);var sC=class extends Gn{apply(e){return Ho(e)}};sC.className="softplus";ne.registerClass(sC);var iC=class extends Gn{apply(e){return sG(e)}};iC.className="softsign";ne.registerClass(iC);var oC=class extends Gn{apply(e){return mi(e)}};oC.className="tanh";ne.registerClass(oC);var k0=class extends Gn{apply(e,t=-1){return Xa(e,t)}};k0.className="softmax";ne.registerClass(k0);var lC=class extends Gn{apply(e,t=-1){return of(e,t)}};lC.className="logSoftmax";ne.registerClass(lC);var uC=class extends Gn{apply(e,t=1){return P(()=>z(fa(z(e,t)),e))}};uC.className="swish";ne.registerClass(uC);var pC=class extends Gn{apply(e){return P(()=>z(e,mi(Ho(e))))}};pC.className="mish";ne.registerClass(pC);function bs(e){return e.getClassName()}function wx(e,t={}){return Id(e,ne.SerializationMap.getMap().classNameMap,t,"activation")}function ys(e){if(e==null){let t={};return t.className="linear",t.config={},wx(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},wx(t)}else return e instanceof Gn?e:wx(e)}function I0(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var cC=class extends ne.Serializable{},_d=class extends cC{constructor(e){super(),I0(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return P(()=>{let t=Nt([1]);return this.hasL1&&(t=X(t,fe(z(this.l1,Wt(e))))),this.hasL2&&(t=X(t,fe(z(this.l2,Nd(e))))),W(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};_d.className="L1L2";ne.registerClass(_d);function MH(e){return I0(e),new _d({l1:e!=null?e.l1:null,l2:0})}function PH(e){return I0(e),new _d({l2:e!=null?e.l2:null,l1:0})}var GI={l1l2:"L1L2"};function mt(e){return t0(e)}function HI(e,t={}){return Id(e,ne.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ct(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in GI?GI[e]:e,config:{}};return HI(t)}else return e instanceof cC?e:HI(e)}var S0=class extends Be{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ce(e);let n=Ke(e);return this.maxValue!=null&&(n=sn(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};S0.className="ReLU";ne.registerClass(S0);var N0=class extends Be{constructor(e){super(e==null?{}:e),this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ce(e);return hd(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};N0.className="LeakyReLU";ne.registerClass(N0);var T0=class extends Be{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Tt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Ct(e.alphaRegularizer),this.alphaConstraint=Zt(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new V(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Je(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let a=1;a<e.length;++a)n[a]=e[a];this.inputSpec=[new Bt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Ce(e),yd(e,this.alpha.read())}getConfig(){let e={alphaInitializer:At(this.alphaInitializer),alphaRegularizer:mt(this.alphaRegularizer),alphaConstraint:Yt(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};T0.className="PReLU";ne.registerClass(T0);var C0=class extends Be{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Le(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ce(e);return cp(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};C0.className="ELU";ne.registerClass(C0);var _0=class extends Be{constructor(e){super(e==null?{}:e),this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let n=Ce(e);return z(n,se(_n(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};_0.className="ThresholdedReLU";ne.registerClass(_0);var E0=class extends Be{constructor(e){super(e==null?{}:e),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new k0().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Ce(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};E0.className="Softmax";ne.registerClass(E0);function Wl(e,t,n){if(typeof e=="number")return yi(e,t);if(e.length!==t)throw new V(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){let r=e[a];if(!eG(r))throw new V(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${r}`)}return e}function Ha(e,t,n,a,r=1){if(e==null)return e;let s=t+(t-1)*(r-1),i;return n==="same"?i=e:i=e-s+1,Math.floor((i+a-1)/a)}function sr(e,t,n,a){if(e==null)return null;if(a==="valid")e=e*t+gs([n-t,0]);else if(a==="same")e=e*t;else throw new V(`Unsupport padding mode: ${a}.`);return e}function A0(e,t){return P(()=>(Pt(t),t==="channelsFirst"?De(e,[0,2,3,1]):e))}function dC(e,t){return P(()=>(Pt(t),t==="channelsFirst"?De(e,[0,2,3,4,1]):e))}function OH(e,t,n,a=1,r="valid",s,i=1){return P(()=>{if(s==null&&(s=ja()),Pt(s),e.shape.length!==3)throw new V(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new V(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new V(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=De(e,[0,2,1])),r==="causal")throw new Le("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=ef(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=Ya(o,n)),o})}function qI(e,t,n,a=[1,1],r="valid",s,i,o=null){return P(()=>{if(s==null&&(s=ja()),Pt(s),e.rank!==3&&e.rank!==4)throw new V(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new V(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=A0(e,s);if(r==="causal")throw new Le("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Zl.conv2d({x:l,filter:t,strides:a,pad:r==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),s==="channelsFirst"&&(l=De(l,[0,3,1,2])),l})}function LH(e,t,n,a=[1,1,1],r="valid",s,i){return P(()=>{if(s==null&&(s=ja()),Pt(s),e.rank!==4&&e.rank!==5)throw new V(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new V(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=dC(e,s);if(r==="causal")throw new Le("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=rw(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=Ya(o,n)),s==="channelsFirst"&&(o=De(o,[0,4,1,2,3])),o})}var F0=class extends Be{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",F0.verifyArgs(t),this.rank=e,an(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Le(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Wl(t.kernelSize,e,"kernelSize"),this.strides=Wl(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,wa(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Pt(this.dataFormat),this.activation=ys(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Tt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Zt(t.biasConstraint),this.biasRegularizer=Ct(t.biasRegularizer),this.activityRegularizer=Ct(t.activityRegularizer),this.dilationRate=Wl(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new V(`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 V(`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 V(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(rr("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!n0(e.kernelSize,"number",1,3))throw new V(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:bs(this.activation),useBias:this.useBias,biasInitializer:At(this.biasInitializer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),biasConstraint:Yt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},Ed=class extends F0{constructor(e,t){super(e,t),this.kernel=null,Ed.verifyArgs(t),this.filters=t.filters,an(this.filters,"filters"),this.kernelInitializer=Tt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Zt(t.kernelConstraint),this.kernelRegularizer=Ct(t.kernelRegularizer)}build(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],a=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",a,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:{[t]:n}}],this.built=!0}call(e,t){return P(()=>{e=Ce(e);let n,a=this.bias==null?null:this.bias.read(),r=v2(this.activation.getClassName());if(r!=null&&this.rank===2)n=qI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=OH(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=qI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=LH(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Le("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=Je(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r<n.length;++r){let s=Ha(n[r],this.kernelSize[r],this.padding,this.strides[r],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[r]);t.push(s)}let a=[e[0]];return this.dataFormat==="channelsLast"?(a=a.concat(t),a.push(this.filters)):(a.push(this.filters),a=a.concat(t)),a}getConfig(){let e={filters:this.filters,kernelInitializer:At(this.kernelInitializer),kernelRegularizer:mt(this.kernelRegularizer),kernelConstraint:Yt(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new V(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},Ad=class extends Ed{constructor(e){super(2,e),Ad.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!n0(e.kernelSize,"number",1,2))throw new V(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};Ad.className="Conv2D";ne.registerClass(Ad);var Fd=class extends Ed{constructor(e){super(3,e),Fd.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new V(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};Fd.className="Conv3D";ne.registerClass(Fd);var $0=class extends Ad{constructor(e){if(super(e),this.inputSpec=[new Bt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Je(e),e.length!==4)throw new V("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"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 Bt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return P(()=>{let n=Ce(e);if(n.shape.length!==4)throw new V(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=a[s],l=a[i],u=this.kernelSize[0],p=this.kernelSize[1],d=this.strides[0],c=this.strides[1],h=sr(o,d,u,this.padding),m=sr(l,c,p,this.padding),f=[r,h,m,this.filters];this.dataFormat!=="channelsLast"&&(n=De(n,[0,2,3,1]));let g=tf(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=De(g,[0,3,1,2])),this.bias!=null&&(g=Ya(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Je(e);let t=e.slice(),n,a,r;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3):(n=3,a=1,r=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[a]=sr(t[a],o,s,this.padding),t[r]=sr(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};$0.className="Conv2DTranspose";ne.registerClass($0);var D0=class extends Fd{constructor(e){if(super(e),this.inputSpec=[new Bt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Je(e),e.length!==5)throw new V("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"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 Bt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return P(()=>{let n=Ce(e);if(n.shape.length!==5)throw new V(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=a[o],u=a[s],p=a[i],d=this.kernelSize[0],c=this.kernelSize[1],h=this.kernelSize[2],m=this.strides[0],f=this.strides[1],g=this.strides[2],b=sr(l,m,d,this.padding),y=sr(u,f,c,this.padding),x=sr(p,g,h,this.padding),v=[r,b,y,x,this.filters];this.dataFormat!=="channelsLast"&&(n=De(n,[0,2,3,4,1]));let I=sw(n,this.kernel.read(),v,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(I=De(I,[0,4,1,2,3])),this.bias!==null&&(I=Ya(I,this.bias.read(),this.dataFormat)),this.activation!==null&&(I=this.activation.apply(I)),I})}computeOutputShape(e){e=Je(e);let t=e.slice(),n,a,r,s;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3,s=4):(n=4,a=1,r=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],p=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[a]=sr(t[a],u,i,this.padding),t[r]=sr(t[r],p,o,this.padding),t[s]=sr(t[s],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};D0.className="Conv3DTranspose";ne.registerClass(D0);var hC=class extends Ed{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new V("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new V("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new V(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Tt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Ct(t.depthwiseRegularizer),this.depthwiseConstraint=Zt(t.depthwiseConstraint),this.pointwiseInitializer=Tt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ct(t.pointwiseRegularizer),this.pointwiseConstraint=Zt(t.pointwiseConstraint)}build(e){if(e=Je(e),e.length<this.rank+2)throw new V(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new V(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],a=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let i=0;i<this.rank;++i)r.push(1);r.push(n*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Bt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return P(()=>{e=Ce(e);let n;if(this.rank===1)throw new Le("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=De(e,[0,2,3,1])),n=$s(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Ya(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=De(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=At(this.depthwiseInitializer),e.pointwiseInitializer=At(this.pointwiseInitializer),e.depthwiseRegularizer=mt(this.depthwiseRegularizer),e.pointwiseRegularizer=mt(this.pointwiseRegularizer),e.depthwiseConstraint=Yt(this.depthwiseConstraint),e.pointwiseConstraint=Yt(this.pointwiseConstraint),e}};hC.className="SeparableConv";var R0=class extends hC{constructor(e){super(2,e)}};R0.className="SeparableConv2D";ne.registerClass(R0);var Uf=class extends Ed{constructor(e){super(1,e),Uf.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!n0(e.kernelSize,"number",1,1))throw new V(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};Uf.className="Conv1D";ne.registerClass(Uf);var M0=class extends Be{constructor(e){super(e),typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return P(()=>{if(e=Ce(e),this.dataFormat==="channelsLast"){let n=Lh(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Lh(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Lh(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Lh(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};M0.className="Cropping2D";ne.registerClass(M0);var P0=class extends Be{constructor(e){super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,ZU(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return P(()=>{let n=Ce(e),a=n.shape;if(this.dataFormat==="channelsFirst"){n=De(n,[0,2,3,1]);let r=this.size[0]*a[2],s=this.size[1]*a[3],i=this.interpolation==="nearest"?ea.resizeNearestNeighbor(n,[r,s]):ea.resizeBilinear(n,[r,s]);return De(i,[0,3,1,2])}else{let r=this.size[0]*a[1],s=this.size[1]*a[2];return this.interpolation==="nearest"?ea.resizeNearestNeighbor(n,[r,s]):ea.resizeBilinear(n,[r,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}};P0.className="UpSampling2D";ne.registerClass(P0);function zH(e,t,n=[1,1],a="valid",r,s){return P(()=>{r==null&&(r=ja()),Pt(r);let i=A0(e,r);if(e.rank!==4)throw new V(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new V(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Es(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=De(i,[0,3,1,2])),i})}var O0=class extends F0{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Tt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Zt(e.depthwiseConstraint),this.depthwiseRegularizer=Ct(e.depthwiseRegularizer)}build(e){if(e=Je(e),e.length<4)throw new V(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new V(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],a=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",a,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(e,t){return P(()=>{e=Ce(e);let n=zH(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Ya(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Ha(t,this.kernelSize[0],this.padding,this.strides[0]),s=Ha(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],a,r,s]:[e[0],r,s,a]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=At(this.depthwiseInitializer),e.depthwiseRegularizer=mt(this.depthwiseRegularizer),e.depthwiseConstraint=Yt(this.depthwiseRegularizer),e}};O0.className="DepthwiseConv2D";ne.registerClass(O0);function mC(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new V("When inputs is an array, neither initialState or constants should be provided");a!=null&&(n=e.slice(e.length-a,e.length),e=e.slice(0,e.length-a)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(s){return s==null||Array.isArray(s)?s:[s]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function fC(e,t,n,a=!1,r,s,i=!1,o=!1){return P(()=>{let l=t.shape.length;if(l<3)throw new V(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(qa(2,l));if(t=De(t,u),s!=null)throw new Le("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."),r!=null&&(r=se(se(r,"bool"),"float32"),r.rank===l-1&&(r=nn(r,-1)),r=De(r,u)),a&&(t=ya(t,0),r!=null&&(r=ya(r,0)));let p=[],d,c=n,h=t.shape[0],m=ct(t),f;r!=null&&(f=ct(r));for(let b=0;b<h;++b){let y=m[b],x=P(()=>e(y,c));if(r==null)d=x[0],c=x[1];else{let v=P(()=>{let I=f[b],T=pe(aa(I),I),C=X(z(x[0],I),z(c[0],T)),E=c.map((F,D)=>X(z(x[1][D],I),z(F,T)));return{output:C,newStates:E}});d=v.output,c=v.newStates}o&&p.push(d)}let g;return o&&(g=Dt(p,1)),[d,g,c]})}var br=class extends Be{constructor(e){super(e);let t;if(e.cell==null)throw new V("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new qf({cells:e.cell}):t=e.cell,t.stateSize==null)throw new V("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Bt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return qa(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Hx(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],a;if(this.returnSequences?a=[e[0],e[1],n]:a=[e[0],n],this.returnState){let r=[];for(let s of t)r.push([e[0],s]);return[a].concat(r)}else return a}computeMask(e,t){return P(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let a=this.states.map(r=>null);return[n].concat(a)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){if(this.numConstants!=null)throw new Le("Constants support is not implemented in RNN yet.");Hx(e)&&(e=e[0]),e=e;let t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Bt({shape:[t,null,...n]});let a=[e[0]].concat(e.slice(2));this.cell.build(a);let r;if(Array.isArray(this.cell.stateSize)?r=this.cell.stateSize:r=[this.cell.stateSize],this.stateSpec!=null){if(!w.arraysEqual(this.stateSpec.map(s=>s.shape[s.shape.length-1]),r))throw new V(`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=r.map(s=>new Bt({shape:[null,s]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){P(()=>{if(!this.stateful)throw new Cr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new V("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(a=>Nt([n,a])):this.states_=[Nt([n,this.cell.stateSize])];else if(e==null)_e(this.states_),this.keptStates!=null&&(_e(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>Nt([n,a])):this.states_[0]=Nt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new V(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):_e(this.states_);for(let a=0;a<this.states_.length;++a){let r=e[a],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[a]:this.cell.stateSize,i=[n,s];if(!w.arraysEqual(r.shape,i))throw new V(`State ${a} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${r.shape}`);this.states_[a]=r}}this.states_=this.states_.map(a=>qt(a.clone()))})}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=mC(e,n,a,this.numConstants);e=r.inputs,n=r.initialState,a=r.constants;let s=[],i=[];if(n!=null){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(let o of n)this.stateSpec.push(new Bt({shape:o.shape}));i=i.concat(this.stateSpec)}if(a!=null&&(t.constants=a,s=s.concat(a),this.numConstants=a.length),s[0]instanceof Va){let o=[e].concat(s),l=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=l;let p=super.apply(o,t);return this.inputSpec=u,p}else return super.apply(e,t)}call(e,t){return P(()=>{let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;e=Ce(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==s)throw new V(`RNN Layer has ${s} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:a},o=fC((c,h)=>{let m=this.cell.call([c].concat(h),i);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],p=o[2];this.stateful&&this.resetStates(p,a);let d=this.returnSequences?u:l;return this.returnState?[d].concat(p):d})}getInitialState(e){return P(()=>{let t=Nt(e.shape);return t=fe(t,[1,2]),t=Sd(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Ux(t,[1,n]):t):this.cell.stateSize>1?[Ux(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===br.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){let a=t.cell,r=Ga(a,n);return new e(Object.assign(t,{cell:r}))}};br.className="RNN";ne.registerClass(br);var $d=class extends Be{},Gf=class extends $d{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,an(this.units,"units"),this.activation=ys(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Tt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Tt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Tt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ct(e.kernelRegularizer),this.recurrentRegularizer=Ct(e.recurrentRegularizer),this.biasRegularizer=Ct(e.biasRegularizer),this.kernelConstraint=Zt(e.kernelConstraint),this.recurrentConstraint=Zt(e.recurrentConstraint),this.biasConstraint=Zt(e.biasConstraint),this.dropout=Ql([1,gs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ql([1,gs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Je(e),this.kernel=this.addWeight("kernel",[e[e.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(e,t){return P(()=>{if(e=e,e.length!==2)throw new V(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let a=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xs({ones:()=>aa(e),rate:this.dropout,training:a,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xs({ones:()=>aa(n),rate:this.recurrentDropout,training:a,dropoutFunc:this.dropoutFunc}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=ur(z(e,s),this.kernel.read()):r=ur(e,this.kernel.read()),this.bias!=null&&(r=Ya(r,this.bias.read())),i!=null&&(n=z(n,i));let o=X(r,ur(n,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),recurrentInitializer:At(this.recurrentInitializer),biasInitializer:At(this.biasInitializer),kernelRegularizer:mt(this.kernelRegularizer),recurrentRegularizer:mt(this.recurrentRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Yt(this.kernelConstraint),recurrentConstraint:Yt(this.recurrentConstraint),biasConstraint:Yt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}};Gf.className="SimpleRNNCell";ne.registerClass(Gf);var L0=class extends br{constructor(e){e.cell=new Gf(e),super(e)}call(e,t){return P(()=>{this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return new e(t)}};L0.className="SimpleRNN";ne.registerClass(L0);var Hf=class extends $d{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new V("GRUCell does not support reset_after parameter set to true.");this.units=e.units,an(this.units,"units"),this.activation=ys(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ys(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Tt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Tt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Tt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ct(e.kernelRegularizer),this.recurrentRegularizer=Ct(e.recurrentRegularizer),this.biasRegularizer=Ct(e.biasRegularizer),this.kernelConstraint=Zt(e.kernelConstraint),this.recurrentConstraint=Zt(e.recurrentConstraint),this.biasConstraint=Zt(e.biasConstraint),this.dropout=Ql([1,gs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ql([1,gs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Je(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,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(e,t){return P(()=>{if(e=e,e.length!==2)throw new V(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,a=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xs({ones:()=>aa(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xs({ones:()=>aa(a),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let r=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=z(e,r[0]));let u=ur(e,this.kernel.read());this.useBias&&(u=Ya(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(a=z(a,s[0]));let p=this.recurrentKernel.read(),[d,c]=zn(p,[2*this.units,this.units],p.rank-1),h=ur(a,d),[m,f,g]=zn(u,3,u.rank-1),[b,y]=zn(h,2,h.rank-1);i=this.recurrentActivation.apply(X(m,b)),o=this.recurrentActivation.apply(X(f,y));let x=ur(z(o,a),c);l=this.activation.apply(X(g,x));let v=X(z(i,a),z(X(1,yt(i)),l));return[v,v]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:bs(this.activation),recurrentActivation:bs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),recurrentInitializer:At(this.recurrentInitializer),biasInitializer:At(this.biasInitializer),kernelRegularizer:mt(this.kernelRegularizer),recurrentRegularizer:mt(this.recurrentRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Yt(this.kernelConstraint),recurrentConstraint:Yt(this.recurrentConstraint),biasConstraint:Yt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}};Hf.className="GRUCell";ne.registerClass(Hf);var z0=class extends br{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Hf(e),super(e)}call(e,t){return P(()=>{this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};z0.className="GRU";ne.registerClass(z0);var Dd=class extends $d{constructor(e){super(e),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=e.units,an(this.units,"units"),this.activation=ys(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ys(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Tt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Tt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Tt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Ct(e.kernelRegularizer),this.recurrentRegularizer=Ct(e.recurrentRegularizer),this.biasRegularizer=Ct(e.biasRegularizer),this.kernelConstraint=Zt(e.kernelConstraint),this.recurrentConstraint=Zt(e.recurrentConstraint),this.biasConstraint=Zt(e.biasConstraint),this.dropout=Ql([1,gs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ql([1,gs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=Je(e);let n=e[e.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 a;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,s=this.units;a=new(t=class extends Pa{apply(i,o){let l=r.apply([s]),u=new Df().apply([s]),p=r.apply([s*2]);return AI(AI(l,u),p)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return P(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new V(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xs({ones:()=>aa(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xs({ones:()=>aa(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,u,p;0<this.dropout&&this.dropout<1&&(e=z(e,s[0]));let d=ur(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(a=z(a,i[0])),d=X(d,ur(a,this.recurrentKernel.read())),this.useBias&&(d=Ya(d,this.bias.read()));let[c,h,m,f]=zn(d,4,d.rank-1);o=this.recurrentActivation.apply(c),l=this.recurrentActivation.apply(h),u=X(z(l,r),z(o,this.activation.apply(m))),p=this.recurrentActivation.apply(f);let g=z(p,this.activation.apply(u));return[g,g,u]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:bs(this.activation),recurrentActivation:bs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),recurrentInitializer:At(this.recurrentInitializer),biasInitializer:At(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:mt(this.kernelRegularizer),recurrentRegularizer:mt(this.recurrentRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Yt(this.kernelConstraint),recurrentConstraint:Yt(this.recurrentConstraint),biasConstraint:Yt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}};Dd.className="LSTMCell";ne.registerClass(Dd);var W0=class extends br{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Dd(e),super(e)}call(e,t){return P(()=>{this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};W0.className="LSTM";ne.registerClass(W0);var qf=class extends $d{constructor(e){super(e),this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return P(()=>{e=e;let n=e.slice(1),a=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?a.push(n.splice(0,i.stateSize.length)):a.push(n.splice(0,1));a.reverse();let r=[],s;for(let i=0;i<this.cells.length;++i){let o=this.cells[i];n=a[i],i===0?s=[e[0]].concat(n):s=[s[0]].concat(n),s=o.call(s,t),r.push(s.slice(1))}n=[];for(let i of r.slice().reverse())n.push(...i);return[s[0]].concat(n)})}build(e){Hx(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,a)=>{si(`RNNCell_${a}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=a=>({className:a.getClassName(),config:a.getConfig()}),n={cells:this.cells.map(t)};return Object.assign(Object.assign({},e),n)}static fromConfig(e,t,n={}){let a=[];for(let r of t.cells)a.push(Ga(r,n));return new e({cells:a})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return qx(e)}setWeights(e){let t=[];for(let n of this.cells){let a=n.weights.length,r=e.splice(a);for(let s=0;s<n.weights.length;++s)t.push([n.weights[s],r[s]])}c0(t)}};qf.className="StackedRNNCells";ne.registerClass(qf);function xs(e){let{ones:t,rate:n,training:a=!1,count:r=1,dropoutFunc:s}=e,i=()=>s!=null?s(t(),n):C2(t(),n),o=()=>Td(i,t,a);return!r||r<=1?qt(o().clone()):Array(r).fill(void 0).map(o).map(l=>qt(l.clone()))}var WH=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,a=Object.getOwnPropertySymbols(e);r<a.length;r++)t.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n},gC=class extends br{constructor(e){if(e.unroll)throw new Le("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Le("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Bt({ndim:5})]}call(e,t){return P(()=>{if(this.cell.dropoutMask!=null&&(_e(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(_e(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new V("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return P(()=>{let{stateSize:t}=this.cell,n=e.shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)],s=Nt(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){P(()=>{if(!this.stateful)throw new Cr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)];if(n[0]==null)throw new V("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(()=>Nt(r)):this.states_=[Nt(r)];else if(e==null)_e(this.states_),this.keptStates!=null&&(_e(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Nt(r)):this.states_[0]=Nt(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new V(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):_e(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=r;if(!w.arraysEqual(i.shape,o))throw new V(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>qt(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:a,padding:r,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],u=e[o?4:3],p=Ha(l,a[0],r,s[0],i[0]),d=Ha(u,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,p,d]:[p,d,n]]}};gC.className="ConvRNN2D";var jf=class extends Dd{constructor(e){let{filters:t,kernelSize:n,strides:a,padding:r,dataFormat:s,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,an(this.filters,"filters"),this.kernelSize=Wl(n,2,"kernelSize"),this.kernelSize.forEach(o=>an(o,"kernelSize")),this.strides=Wl(a||1,2,"strides"),this.strides.forEach(o=>an(o,"strides")),this.padding=r||"valid",wa(this.padding),this.dataFormat=s||"channelsLast",Pt(this.dataFormat),this.dilationRate=Wl(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>an(o,"dilationRate"))}build(e){var t;e=Je(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new V(`The channel dimension of the input should be defined. Found ${e[n]}`);let a=e[n],r=4,s=this.kernelSize.concat([a,this.filters*r]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,u=this.filters;o=new(t=class extends Pa{apply(p,d){let c=l.apply([u]),h=Qn([u]),m=l.apply([u*2]);return a0([c,h,m])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return P(()=>{if(e.length!==3)throw new V(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,a=e[0],r=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xs({ones:()=>aa(a),rate:this.dropout,training:n,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(Z,J,ee)=>!J||!J[ee]?Z:z(J[ee],Z),u=l(a,o,0),p=l(a,o,1),d=l(a,o,2),c=l(a,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xs({ones:()=>aa(r),rate:this.recurrentDropout,training:n,count:i,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,m=l(r,h,0),f=l(r,h,1),g=l(r,h,2),b=l(r,h,3),y=3,[x,v,I,T]=zn(this.kernel.read(),i,y),[C,E,F,D]=this.useBias?zn(this.bias.read(),i):[null,null,null,null];u=this.inputConv(u,x,C,this.padding),p=this.inputConv(p,v,E,this.padding),d=this.inputConv(d,I,F,this.padding),c=this.inputConv(c,T,D,this.padding);let[$,S,M,B]=zn(this.recurrentKernel.read(),i,y);m=this.recurrentConv(m,$),f=this.recurrentConv(f,S),g=this.recurrentConv(g,M),b=this.recurrentConv(b,B);let U=this.recurrentActivation.apply(X(u,m)),H=this.recurrentActivation.apply(X(p,f)),j=X(z(H,s),z(U,this.activation.apply(X(d,g)))),K=z(this.recurrentActivation.apply(X(c,b)),this.activation.apply(j));return[K,K,j]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=WH(e,["units"]),a={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),a)}inputConv(e,t,n,a){let r=Rt(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Ya(r,n,this.dataFormat):r}recurrentConv(e,t){return Rt(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};jf.className="ConvLSTM2DCell";ne.registerClass(jf);var B0=class extends gC{constructor(e){let t=new jf(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}};B0.className="ConvLSTM2D";ne.registerClass(B0);var Kf=class extends Be{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let a=0;a<this.noiseShape.length;++a)n.push(this.noiseShape[a]==null?t[a]:this.noiseShape[a]);return n}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e);if(0<this.rate&&this.rate<1){let a=t.training==null?!1:t.training,r=this.getNoiseShape(n);return Td(()=>C2(n,this.rate,r,this.seed),()=>n,a)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Kf.className="Dropout";ne.registerClass(Kf);var V0=class extends Kf{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};V0.className="SpatialDropout1D";ne.registerClass(V0);var U0=class extends Be{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,an(this.units,"units"),this.activation=ys(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Tt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Tt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Zt(e.kernelConstraint),this.biasConstraint=Zt(e.biasConstraint),this.kernelRegularizer=Ct(e.kernelRegularizer),this.biasRegularizer=Ct(e.biasRegularizer),this.activityRegularizer=Ct(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Je(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,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]:t}}],this.built=!0}computeOutputShape(e){e=Je(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e),a=v2(this.activation.getClassName()),r;return a!=null?r=ur(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=ur(n,this.kernel.read()),this.bias!=null&&(r=Ya(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),biasInitializer:At(this.biasInitializer),kernelRegularizer:mt(this.kernelRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Yt(this.kernelConstraint),biasConstraint:Yt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};U0.className="Dense";ne.registerClass(U0);var G0=class extends Be{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Je(e);for(let t of e.slice(1))if(t==null)throw new V(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],ps(e,1)]}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let a=[0];for(let r=2;r<n.rank;++r)a.push(r);a.push(1),n=De(n,a)}return aG(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};G0.className="Flatten";ne.registerClass(G0);var H0=class extends Be{constructor(e){super(e),this.supportsMasking=!0,this.activation=ys(e.activation)}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e);return this.activation.apply(n)})}getConfig(){let e={activation:bs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};H0.className="Activation";ne.registerClass(H0);var q0=class extends Be{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return P(()=>(e=Ce(e),tG(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};q0.className="RepeatVector";ne.registerClass(q0);var j0=class extends Be{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let n="Total size of new array must be unchanged.",a=t.slice(),r=1,s=null;for(let o=0;o<a.length;++o){let l=a[o];if(this.isUnknown(l))if(s===null)s=o;else throw new V("Can only specifiy one unknown dimension.");else r*=l}let i=ps(e);if(s!==null){if(r===0||i%r!==0)throw new V(n);a[s]=i/r}else if(i!==r)throw new V(n);return a}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e),a=n.shape,r=a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape));return W(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};j0.className="Reshape";ne.registerClass(j0);var K0=class extends Be{constructor(e){if(super(e),e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=qa(1,e.dims.length+1);if(!w.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Bt({ndim:this.dims.length+1})]}computeOutputShape(e){e=Je(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return De(Ce(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};K0.className="Permute";ne.registerClass(K0);var X0=class extends Be{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ce(e),a=-1;return kc(gi(n,this.maskValue),a)}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e),a=-1,r=!0,s=kc(gi(n,this.maskValue),a,r);return z(n,se(s,n.dtype))})}};X0.className="Masking";ne.registerClass(X0);var Y0=class extends Be{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(kt(e.inputLength))}this.inputDim=e.inputDim,an(this.inputDim,"inputDim"),this.outputDim=e.outputDim,an(this.outputDim,"outputDim"),this.embeddingsInitializer=Tt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ct(e.embeddingsRegularizer),this.activityRegularizer=Ct(e.activityRegularizer),this.embeddingsConstraint=Zt(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return P(()=>this.maskZero?(e=Ce(e),gi(e,qe(e))):null)}computeOutputShape(e){if(e=Je(e),this.inputLength==null)return[...e,this.outputDim];let t=kt(this.inputLength);if(t.length!==e.length-1)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let a=0;a<t.length;++a){let r=t[a],s=e[a+1];if(r!=null&&s!=null&&r!==s)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);r==null&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e);n.dtype!=="int32"&&(n=lr(n,"int32"));let a=T2(this.embeddings.read(),W(n,[n.size]));return W(a,Je(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:At(this.embeddingsInitializer),embeddingsRegularizer:mt(this.embeddingsRegularizer),activityRegularizer:mt(this.activityRegularizer),embeddingsConstraint:Yt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Y0.className="Embedding";ne.registerClass(Y0);var Zo=class extends Be{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Le}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let n=e.slice(0,e.length-t.length);for(let a=0;a<t.length;++a){let r=e[e.length-t.length+a],s=t[a];if(r==null||s==null||r<0||s<0)n.push(null);else if(r===1)n.push(s);else if(s===1)n.push(r);else{if(r!==s)throw new V("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(r)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Je(e)]),e=e,e.length<2)throw new V(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let r of e)r!=null&&r[0]!==null&&t.push(r[0]);if(t=us(t),t.length>1)throw new V(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;r<e.length;++r){let s=e[r]==null?null:e[r].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}let a=e.map(r=>r.length);e.indexOf(null)===-1&&us(a).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return P(()=>{if(e=e,this.reshapeRequired){let n=[],a=e.map(r=>r.rank);if(a.indexOf(null)===-1){let r=gs(a);for(let s of e){let i=s.rank;for(let o=0;o<r-i;++o)s=Sd(s,1);n.push(s)}return this.mergeFunction(n)}else{let r=!1;for(let o of e){let l=o.rank;if(l==null){let u=o.shape,p=u[0],d=u.slice(1).concat([p]),c=W(o,[p].concat(ps(u.slice(1))));c=De(c,[1,0]),c=W(c,d),n.push(c),r=!0}else if(l>1){let u=qa(1,l).concat([0]);n.push(De(o,u)),r=!0}else n.push(o)}let s=this.mergeFunction(n),i=s.rank;if(r){if(i==null){let o=s.shape,l=o.length,u=o[l-1],p=[u].concat(o.slice(0,o.length-1));s=W(De(W(s,[-1,u]),[1,0]),p)}else if(i>1){let o=[i-1].concat(qa(0,i-1));s=De(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let a=1;a<e.length;++a){let r=e[a]==null?null:e[a].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}let n=[];for(let a of e)a!=null&&a[0]!==null&&n.push(a[0]);return n=us(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return P(()=>{if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an Array");if(!Array.isArray(e))throw new V("`inputs` should be an Array");if(t.length!==e.length)throw new V(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(a=>a==null))return null;t=t.map(a=>a==null?a:nn(a,0));let n=t[0];for(let a=1;a<t.length-1;++a)n=Da(n,t[a]);return n})}},Z0=class extends Zo{constructor(e){super(e)}mergeFunction(e){return P(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return t})}};Z0.className="Add";ne.registerClass(Z0);var J0=class extends Zo{constructor(e){super(e)}mergeFunction(e){return P(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=z(t,e[n]);return t})}};J0.className="Multiply";ne.registerClass(J0);var Q0=class extends Zo{constructor(e){super(e)}mergeFunction(e){return P(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return z(1/e.length,t)})}};Q0.className="Average";ne.registerClass(Q0);var e1=class extends Zo{constructor(e){super(e)}mergeFunction(e){return P(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=fr(t,e[n]);return t})}};e1.className="Maximum";ne.registerClass(e1);var t1=class extends Zo{constructor(e){super(e)}mergeFunction(e){return P(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=fs(t,e[n]);return t})}};t1.className="Minimum";ne.registerClass(t1);var n1=class extends Zo{constructor(e){super(e),this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new V("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let a of e)if(a!=null){t=!1;break}if(t)return;let n=[];for(let a=0;a<e.length;++a){let r=e[a].slice();r.splice(this.axis,1);let s=!1;for(let i of n)if(w.arraysEqual(i,r)){s=!0;break}s||n.push(r)}if(n.length>1)throw new V("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return P(()=>a0(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new V("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),a=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[a]==null||r[a]==null){n[a]=null;break}n[a]+=r[a]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new V("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new V(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return P(()=>{let n=!0;if(t.forEach(s=>{if(s!=null){n=!1;return}}),n)return null;let a=[];for(let s=0;s<e.length;++s)t[s]==null?a.push(se(aa(e[s]),"bool")):t[s].rank<e[s].rank?a.push(nn(t[s],-1)):a.push(t[s]);let r=et(a,this.axis);return Qm(r,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};n1.className="Concatenate";ne.registerClass(n1);function ec(e,t){for(;e<0;)e+=t;return e}function BH(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Le("batchDot is not implemented for tensors of 4D or higher rank yet");if(w.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),w.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new Le("batchDot is not implemented for complex64-type Tensors yet.");let a=e.shape.length,r=t.shape.length;n==null&&(n=[a-1,r-2]);let s=n;return P(()=>{let i;if(a>r){i=a-r;let l=[];for(let u=0;u<i;++u)l.push(1);t=W(t,t.shape.concat(l))}else if(r>a){i=r-a;let l=[];for(let u=0;u<i;++u)l.push(1);e=W(e,e.shape.concat(l))}else i=0;let o;if(e.shape.length===2&&t.shape.length===2)s[0]===s[1]?o=fe(z(e,t),s[0]):o=fe(z(De(e,[1,0]),t),s[1]);else{let l=s[0]!==e.shape.length-1,u=s[1]===t.shape.length-1;o=$e(e,t,l,u)}if(i>0){let l;a>r?l=a+r-3:l=a-1;let u=[];for(let p=l;p<l+i;++p)u.push(p);o=Ds(o,u)}return o.shape.length===1&&(o=nn(o,1)),o})}var a1=class extends Zo{constructor(e){super(e),this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){w.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Le("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);if(t[a[0]]!==n[a[1]])throw new V(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new V(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],a;return Array.isArray(this.axes)?a=this.axes.map((r,s)=>ec(r,e[s].shape.length)):a=[ec(this.axes,t.shape.length),ec(this.axes,n.shape.length)],this.normalize&&(t=bm(t,a[0]),n=bm(n,a[1])),BH(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[ec(this.axes,e.length),ec(this.axes,t.length)],n}computeOutputShape(e){w.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Le("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);t.splice(a[0],1),n.splice(a[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};a1.className="Dot";ne.registerClass(a1);var r1=class extends Be{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e);return Td(()=>X($f(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};r1.className="GaussianNoise";ne.registerClass(r1);var s1=class extends Be{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return P(()=>{this.invokeCallHook(e,t);let n=Ce(e);return this.rate>0&&this.rate<1?Td(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return z(n,$f(n.shape,1,a))},()=>n,t.training||!1):n})}};s1.className="GaussianDropout";ne.registerClass(s1);var i1=class extends Be{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ce(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return P(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Td(()=>{let a=Ce(e),r=1.6732632423543772,s=1.0507009873554805,i=-r*s,o=Or(Fs(n),this.rate);o=lr(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-l*i*this.rate,p=X(z(a,o),z(X(o,-1),i));return X(z(p,l),u)},()=>Ce(e),t.training||!1)}return e})}};i1.className="AlphaDropout";ne.registerClass(i1);function _c(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=Kv(e,t,n,a,r,s);else if(e.rank===3)i=Xv(e,t,n,a,r,s);else if(e.rank===4)i=Yv(e,t,n,a,r,s);else throw new Le(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function VH(e,t,n,a,r=.001){return P(()=>{let s=gd(e,a),i=s.mean,o=s.variance;return[_c(e,i,o,n,t,r),i,o]})}function UH(e,t,n,a,r=.001){return P(()=>{let s=gd(e,a),i=s.mean,o=s.variance,l=[];for(let h of qa(0,e.rank))a.indexOf(h)!==-1?l.push(1):l.push(e.shape[h]);let u=W(i,l),p=W(o,l),d=t==null?null:W(t,l),c=n==null?null:W(n,l);return[_c(e,u,p,c,d,r),i,o]})}function GH(e,t,n,a,r=.001){return w.arraysEqual(a.slice().sort(),qa(0,e.rank-1))?VH(e,t,n,a,r):UH(e,t,n,a,r)}var o1=class extends Be{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Tt(e.betaInitializer||"zeros"),this.gammaInitializer=Tt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Tt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Tt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Zt(e.betaConstraint),this.gammaConstraint=Zt(e.gammaConstraint),this.betaRegularizer=Ct(e.betaRegularizer),this.gammaRegularizer=Ct(e.gammaRegularizer)}build(e){e=Je(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new V(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Bt({ndim:e.length,axes:{[t]:n}})];let a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return P(()=>{let n=t.training==null?!1:t.training,a=Ce(e),r=a.shape,s=r.length,i=qa(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=yi(1,s);l[o]=r[o];let u=i.slice();u.sort();let p=!w.arraysEqual(u,qa(0,s).slice(0,s-1)),d=()=>{if(p){let g=W(this.movingMean.read(),l),b=W(this.movingVariance.read(),l),y=this.center?W(this.beta.read(),l):null,x=this.scale?W(this.gamma.read(),l):null;return _c(a,g,b,y,x,this.epsilon)}else return _c(a,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 d();let[c,h,m]=GH(a,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,b,y)=>{P(()=>{let x=1-y,v=g.read(),I=z(pe(v,b),x);g.write(pe(v,I))})};return f(this.movingMean,h,this.momentum),f(this.movingVariance,m,this.momentum),c})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:At(this.betaInitializer),gammaInitializer:At(this.gammaInitializer),movingMeanInitializer:At(this.movingMeanInitializer),movingVarianceInitializer:At(this.movingVarianceInitializer),betaRegularizer:mt(this.betaRegularizer),gammaRegularizer:mt(this.gammaRegularizer),betaConstraint:Yt(this.betaConstraint),gammaConstraint:Yt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};o1.className="BatchNormalization";ne.registerClass(o1);var l1=class extends Be{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.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 t of this.axis)if(!Number.isInteger(t))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=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Tt(e.betaInitializer||"zeros"),this.gammaInitializer=Tt(e.gammaInitializer||"ones"),this.betaRegularizer=Ct(e.betaRegularizer),this.gammaRegularizer=Ct(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Je(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r<this.axis.length;++r)this.axis[r]<0&&(this.axis[r]+=t);for(let r of this.axis)if(r<0||r>=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==us(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),a=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,a):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,a):this.beta=null,this.built=!0}call(e,t){let n=Ce(e),a=n.shape,r=a.length;return P(()=>{let{mean:s,variance:i}=gd(n,this.axis,!0),o=yi(1,r);for(let h of this.axis)o[h]=a[h];let l=h=>h!=null&&h.shape.length!==r?W(h,o):h,u=this.scale?l(this.gamma.read()):null,p=this.center?l(this.beta.read()):null,d=[],c=[];for(let h=0;h<r;++h)this.axis.indexOf(h)!==-1?(d.push(a[h]),c.push(1)):(d.push(1),c.push(a[h]));return s=Ln(s,d),i=Ln(i,d),u!=null&&(u=Ln(u,c)),p!=null&&(p=Ln(p,c)),_c(n,s,i,p,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:At(this.betaInitializer),gammaInitializer:At(this.gammaInitializer),betaRegularizer:mt(this.betaRegularizer),gammaRegularizer:mt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};l1.className="LayerNormalization";ne.registerClass(l1);function HH(e,t,n){return P(()=>{if(e.rank!==4)throw new V(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new V("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=ja()),n!=="channelsLast"&&n!=="channelsFirst")throw new V(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let a;return n==="channelsFirst"?a=[[0,0],[0,0],t[0],t[1]]:a=[[0,0],t[0],t[1],[0,0]],va(e,a)})}var u1=class extends Be{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ja():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new V(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new V(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new V(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Bt({ndim:4})]}computeOutputShape(e){e=Je(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return P(()=>HH(Ce(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};u1.className="ZeroPadding2D";ne.registerClass(u1);function Xf(e,t,n,a,r,s){return P(()=>{Pt(r),k2(s),wa(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=ja()),s==null&&(s="max"),e=A0(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Mt(e,t,n,o):i=xa(e,t,n,o),r==="channelsFirst"&&(i=De(i,[0,3,1,2])),i})}function bC(e,t,n,a,r,s){return P(()=>{Pt(r),k2(s),wa(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=ja()),s==null&&(s="max"),e=dC(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=ww(e,t,n,o):i=jv(e,t,n,o),r==="channelsFirst"&&(i=De(i,[0,4,1,2,3])),i})}var yC=class extends Be{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new V(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(an(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new V(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);an(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,wa(this.padding),this.inputSpec=[new Bt({ndim:3})]}computeOutputShape(e){e=Je(e);let t=Ha(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return P(()=>{this.invokeCallHook(e,t),e=Sd(Ce(e),2);let n=this.poolingFunction(Ce(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Ds(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},p1=class extends yC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Pt(r),wa(a),Xf(e,t,n,a,r,"max")}};p1.className="MaxPooling1D";ne.registerClass(p1);var c1=class extends yC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Pt(r),wa(a),Xf(e,t,n,a,r,"avg")}};c1.className="AveragePooling1D";ne.registerClass(c1);var xC=class extends Be{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new V(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];an(this.poolSize,"poolSize"),an(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),wa(this.padding),this.inputSpec=[new Bt({ndim:4})]}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Ha(t,this.poolSize[0],this.padding,this.strides[0]),n=Ha(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return P(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ce(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},d1=class extends xC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Pt(r),wa(a),Xf(e,t,n,a,r,"max")}};d1.className="MaxPooling2D";ne.registerClass(d1);var h1=class extends xC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Pt(r),wa(a),Xf(e,t,n,a,r,"avg")}};h1.className="AveragePooling2D";ne.registerClass(h1);var vC=class extends Be{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new V(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];an(this.poolSize,"poolSize"),an(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),wa(this.padding),this.inputSpec=[new Bt({ndim:5})]}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Ha(t,this.poolSize[0],this.padding,this.strides[0]),n=Ha(n,this.poolSize[1],this.padding,this.strides[1]),a=Ha(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,a]:[e[0],t,n,a,e[4]]}call(e,t){return P(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ce(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},m1=class extends vC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Pt(r),wa(a),bC(e,t,n,a,r,"max")}};m1.className="MaxPooling3D";ne.registerClass(m1);var f1=class extends vC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Pt(r),wa(a),bC(e,t,n,a,r,"avg")}};f1.className="AveragePooling3D";ne.registerClass(f1);var wC=class extends Be{constructor(e){super(e),this.inputSpec=[new Bt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Le}},g1=class extends wC{constructor(e){super(e||{})}call(e,t){return P(()=>{let n=Ce(e);return Et(n,1)})}};g1.className="GlobalAveragePooling1D";ne.registerClass(g1);var b1=class extends wC{constructor(e){super(e||{})}call(e,t){return P(()=>{let n=Ce(e);return ga(n,1)})}};b1.className="GlobalMaxPooling1D";ne.registerClass(b1);var kC=class extends Be{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),this.inputSpec=[new Bt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Le}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},y1=class extends kC{call(e,t){return P(()=>{let n=Ce(e);return this.dataFormat==="channelsLast"?Et(n,[1,2]):Et(n,[2,3])})}};y1.className="GlobalAveragePooling2D";ne.registerClass(y1);var x1=class extends kC{call(e,t){return P(()=>{let n=Ce(e);return this.dataFormat==="channelsLast"?ga(n,[1,2]):ga(n,[2,3])})}};x1.className="GlobalMaxPooling2D";ne.registerClass(x1);var IC=class extends Be{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}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(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let a=t.layer,r=Ga(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},v1=class extends IC{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=Je(e),e.length<3)throw new V(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=Je(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),a=e[1];return[n[0],a].concat(n.slice(1))}call(e,t){return P(()=>(e=Ce(e),fC((n,a)=>[Ce(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};v1.className="TimeDistributed";ne.registerClass(v1);function qH(e){Xo(YU,"BidirectionalMergeMode",e)}var jH="concat",w1=class extends IC{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Ga(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=Ga(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?jH:e.mergeMode,qH(this.mergeMode),e.weights)throw new Le("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,a,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,a=[n]):this.mergeMode==null?a=[n,n.slice()]:a=[n],this.returnState?this.mergeMode==null?a.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):On(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=mC(e,n,a,this.numConstants);if(e=r.inputs,n=r.initialState,a=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&a==null)return super.apply(e,t);let s=[],i=[];if(n!=null){let l=n.length;if(l%2>0)throw new V("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);let u=n.map(p=>new Bt({shape:p.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),i.push(...u)}if(a!=null)throw new Le("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof Va;for(let l of s)if(l instanceof Va!==o)throw new V("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),u=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=u;let d=super.apply(l,t);return this.inputSpec=p,d}else return super.apply(e,t)}call(e,t){return P(()=>{let n=t.initialState,a,r;if(n==null)a=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let o=n.slice(0,n.length/2),l=n.slice(n.length/2);a=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(a)&&(s=a.slice(1).concat(r.slice(1))),a=a[0],r=r[0]),this.returnSequences&&(r=ya(r,1));let i;return this.mergeMode==="concat"?i=a0([a,r]):this.mergeMode==="sum"?i=X(a,r):this.mergeMode==="ave"?i=z(.5,X(a,r)):this.mergeMode==="mul"?i=z(a,r):this.mergeMode==null&&(i=[a,r]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){si(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),si(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let a=this.forwardLayer.states.map(r=>null);return Array.isArray(n)?n.concat(a).concat(a):[n].concat(a).concat(a)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=Ga(t.layer);if(delete t.layer,t.numConstants!=null)throw new Le("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=n,new e(a)}};w1.className="Bidirectional";ne.registerClass(w1);var k1=class extends Be{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){let e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return P(()=>(e=Ce(e),e.dtype!=="float32"&&(e=lr(e,"float32")),X(z(e,this.scale),this.offset)))}};k1.className="Rescaling";ne.registerClass(k1);var{resizeBilinear:KH,cropAndResize:XH}=ea,I1=class extends Be{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,a,r,s,i,o){return P(()=>{let l,u=!1,p=t/s,d=n/i,c=(a+t)/s,h=(r+n)/i,m=[p,d,c,h],f=[];e.rank===3?(u=!0,l=Dt([e])):l=e;for(let x=0;x<l.shape[0];x++)f.push(m);let g=bn(f,[f.length,4]),b=bi(0,f.length,1,"int32"),y=XH(l,g,b,[a,r],"nearest");return lr(u?Ce(ct(y)):y,o)})}upsize(e,t,n,a){return P(()=>{let r=KH(e,[t,n]);return lr(r,a)})}call(e,t){return P(()=>{let n=Ce(e),a=n.dtype,r=n.shape,s=r[r.length-3],i=r[r.length-2],o=0;s!==this.height&&(o=Math.floor((s-this.height)/2));let l=0;return i!==this.width&&(l=Math.floor((i-this.width)/2),l===0&&(l=1)),o>=0&&l>=0?this.centerCrop(n,o,l,this.height,this.width,s,i,a):this.upsize(e,this.height,this.width,a)})}getConfig(){let e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Je(e);let t=e.length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}};I1.className="CenterCrop";ne.registerClass(I1);function YH(e,t,n,a){let r=Ce(e);if(r.dtype!=="int32"&&(r=lr(r,"int32")),t==="int")return r;let s=r.shape;if(r.rank===0&&(r=nn(r,-1)),t==="oneHot"&&r.shape[r.shape.length-1]!==1&&(r=nn(r,-1)),r.rank>2)throw new V(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${s} which would result in output rank ${r.rank}.`);let i=["multiHot","oneHot"].includes(t),o=r,l;if(typeof a!="undefined"&&t==="count"?l=dm(o,a,n,i):l=dm(o,[],n,i),t!=="tfIdf")return l;if(a)return z(l,a);throw new V("When outputMode is 'tfIdf', weights must be provided.")}var S1=class extends Be{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){let e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return e=Je(e),e==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return P(()=>{e=Ce(e),e.dtype!=="int32"&&(e=lr(e,"int32"));let n;if(typeof t.countWeights!="undefined"){if(this.outputMode!=="count")throw new V(`countWeights is not used when outputMode !== count.
              Received countWeights=${t.countWeights}`);n=Ce(t.countWeights)}let a=ga(e),r=Hl(e),s=_n(this.numTokens,a).bufferSync().get(0),i=Or(r,0).bufferSync().get(0);if(!(s&&i))throw new V(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return YH(e,this.outputMode,this.numTokens,n)})}};S1.className="CategoryEncoding";ne.registerClass(S1);var ZH=["bilinear","nearest"],jI=new Set(ZH),N1=class extends Be{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation)if(jI.has(e.interpolation))this.interpolation=e.interpolation;else throw new V(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){e=Je(e);let t=e[2];return[this.height,this.width,t]}getConfig(){let e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return P(()=>{let n=[this.height,this.width];if(this.interpolation==="bilinear")return ea.resizeBilinear(e,n,!this.cropToAspectRatio);if(this.interpolation==="nearest")return ea.resizeNearestNeighbor(e,n,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...jI]} are supported`)})}};N1.className="Resizing";ne.registerClass(N1);var SC=class{constructor(e){this.seed=e}next(){if(this.seed!==void 0)return this.seed++}};SC.className="RandomSeed";var NC=class extends Be{constructor(e){super(e),this.randomGenerator=new SC(e.seed)}getConfig(){let e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}};NC.className="BaseRandomLayer";var JH=["bilinear","nearest"],KI=new Set(JH),T1=class extends NC{constructor(e){super(e);let{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,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 V(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new V(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new V(`factor cannot have upper bound less than lower bound.
        Got upper bound: ${this.widthUpper}.
        Got lower bound: ${this.widthLower}
      `);if(n)if(KI.has(n))this.interpolation=n;else throw new V(`Invalid interpolation parameter: ${n} is not implemented`)}getConfig(){let e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Je(e);let t=e[2];return[this.imgHeight,-1,t]}call(e,t){return P(()=>{let n=Ce(e);this.imgHeight=n.shape[n.shape.length-3];let a=n.shape[n.shape.length-2];this.widthFactor=Fs([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*a;r=Math.round(r);let s=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return ea.resizeBilinear(e,s);case"nearest":return ea.resizeNearestNeighbor(e,s);default:throw new Error(`Interpolation is ${this.interpolation}
          but only ${[...KI]} are supported`)}})}};T1.className="RandomWidth";ne.registerClass(T1);function QH(e){return new gp(e)}function e6(e){return new C0(e)}function t6(e){return new S0(e)}function n6(e){return new N0(e)}function a6(e){return new T0(e)}function r6(e){return new E0(e)}function s6(e){return new _0(e)}function i6(e){return new Uf(e)}function o6(e){return new Ad(e)}function l6(e){return new $0(e)}function u6(e){return new Fd(e)}function p6(e){return new D0(e)}function c6(e){return new R0(e)}function d6(e){return new M0(e)}function h6(e){return new P0(e)}function m6(e){return new O0(e)}function f6(e){return new H0(e)}function g6(e){return new U0(e)}function b6(e){return new Kf(e)}function y6(e){return new V0(e)}function x6(e){return new G0(e)}function v6(e){return new q0(e)}function w6(e){return new j0(e)}function k6(e){return new K0(e)}function I6(e){return new Y0(e)}function S6(e){return new Z0(e)}function N6(e){return new Q0(e)}function T6(e){return new n1(e)}function C6(e){return new e1(e)}function _6(e){return new t1(e)}function E6(e){return new J0(e)}function A6(e){return new a1(e)}function F6(e){return new o1(e)}function $6(e){return new l1(e)}function D6(e){return new u1(e)}function C1(e){return new c1(e)}function R6(e){return C1(e)}function M6(e){return C1(e)}function _1(e){return new h1(e)}function P6(e){return _1(e)}function O6(e){return _1(e)}function E1(e){return new f1(e)}function L6(e){return E1(e)}function z6(e){return E1(e)}function W6(e){return new g1(e)}function B6(e){return new y1(e)}function TC(e){return new b1(e)}function CC(e){return new x1(e)}function _C(e){return new p1(e)}function EC(e){return new d1(e)}function V6(e){return new m1(e)}function U6(e){return new z0(e)}function G6(e){return new Hf(e)}function H6(e){return new W0(e)}function q6(e){return new Dd(e)}function j6(e){return new L0(e)}function K6(e){return new Gf(e)}function X6(e){return new B0(e)}function Y6(e){return new jf(e)}function Z6(e){return new br(e)}function J6(e){return new qf(e)}function Q6(e){return new w1(e)}function eq(e){return new v1(e)}var tq=TC,nq=CC,aq=_C,rq=EC;function sq(e){return new r1(e)}function iq(e){return new s1(e)}function oq(e){return new i1(e)}function lq(e){return new X0(e)}function uq(e){return new k1(e)}function pq(e){return new I1(e)}function cq(e){return new N1(e)}function dq(e){return new S1(e)}function hq(e){return new T1(e)}var AC={};Ee(AC,{MAPE:()=>Sq,MSE:()=>Cq,binaryAccuracy:()=>mq,binaryCrossentropy:()=>fq,categoricalAccuracy:()=>bq,categoricalCrossentropy:()=>yq,cosineProximity:()=>wq,mape:()=>Nq,meanAbsoluteError:()=>kq,meanAbsolutePercentageError:()=>Iq,meanSquaredError:()=>Tq,mse:()=>_q,precision:()=>xq,recall:()=>vq,sparseCategoricalAccuracy:()=>gq});function mq(e,t){return y0(e,t)}function fq(e,t){return V2(e,t)}function gq(e,t){return U2(e,t)}function bq(e,t){return x0(e,t)}function yq(e,t){return v0(e,t)}function xq(e,t){return B2(e,t)}function vq(e,t){return eH(e,t)}function wq(e,t){return b0(e,t)}function kq(e,t){return Bf(e,t)}function Iq(e,t){return bp(e,t)}function Sq(e,t){return bp(e,t)}function Nq(e,t){return bp(e,t)}function Tq(e,t){return Yo(e,t)}function Cq(e,t){return Yo(e,t)}function _q(e,t){return Yo(e,t)}var FC={};Ee(FC,{modelFromJSON:()=>_H});var $C={};Ee($C,{l1:()=>Aq,l1l2:()=>Eq,l2:()=>Fq});function Eq(e){return new _d(e)}function Aq(e){return MH(e)}function Fq(e){return PH(e)}var DC=class extends eu{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Dr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Wh(e,t){return e<t}function XI(e,t){return e>t}var RC=class extends DC{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new Le("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.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=Wh:this.mode==="max"?this.monitorFunc=XI:this.monitor.indexOf("acc")!==-1?this.monitorFunc=XI:this.monitorFunc=Wh,this.monitorFunc===Wh&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Wh?1/0:-1/0}async onEpochEnd(e,t){await ts(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function $q(e){return new RC(e)}var Dq={earlyStopping:$q},Rq=G();Rq.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&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 _a;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"})(_a||(_a={}));var YI;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(YI||(YI={}));var A1={};function Mq(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};A1[e]=n}function MC(e){return A1[e]}function Pq(e){delete A1[e]}function k(e,t,n,a,r){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd,u=o<0?t.inputNames.length+o:o;if(s.type==="tensor")return dn(t.inputNames[u],n,a,r);if(s.type==="tensors"){let c=t.inputs.slice(o,l);return t.inputNames.slice(o,l).filter((h,m)=>{var f;return((f=c[m])===null||f===void 0?void 0:f.op)!=="NoOp"}).map(h=>dn(h,n,a,r))}let p=dn(t.inputNames[u],n,a,r),d=p.dataSync();return s.type==="number"?d[0]:w.toNestedArray(p.shape,d)}let i=t.attrParams[e];return i&&i.value}function dn(e,t,n,a){let[r,s]=Zn(e,n);if(a!=null){let o=a.getHashTableHandleByName(r);if(o!=null)return o}let i=n.currentContextIds.find(o=>!!t[km(r,o)]);return i!==void 0?t[km(r,i)][s]:void 0}function ZI(e,t,n){return t[km(e,n.currentContextId)]}function Er(e,t){let[n,a,r]=Zn(e,t);return[km(n,t&&t.currentContextId),a,r]}function km(e,t){return t?`${e}-${t}`:e}function Zn(e,t){if(e==="")return["",0,void 0];let n=t!=null&&t.parseNodeNameCache!=null;if(n){let s=t.parseNodeNameCache.get(e);if(s!=null)return s}let a=e.split(":"),r;if(a.length===1)r=[e,0,void 0];else{let s=a[0],i=a.length===3?a[1]:void 0,o=Number(a[a.length-1]);r=[s,o,i]}return n&&t.parseNodeNameCache.set(e,r),r}function Yh(e,t,n){let a=k("pad",e,t,n);if(a==="explicit"){a=k("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)r[s][0]=a[s*2],r[s][1]=a[s*2+1];return r}return a}function Ar(e){return e.kept?e:or(e)}var PC={};Ee(PC,{json:()=>Oq});var Oq=[{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}]}],OC={};Ee(OC,{json:()=>Lq});var Lq=[{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}]}],LC={};Ee(LC,{json:()=>zq});var zq=[{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"}]}],zC={};Ee(zC,{json:()=>Wq});var Wq=[{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"}]}],WC={};Ee(WC,{json:()=>Bq});var Bq=[{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"}]}],BC={};Ee(BC,{json:()=>Vq});var Vq=[{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}]}],VC={};Ee(VC,{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"}]}],UC={};Ee(UC,{json:()=>Gq});var Gq=[{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"}]}],GC={};Ee(GC,{json:()=>Hq});var Hq=[{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"}]}],HC={};Ee(HC,{json:()=>qq});var qq=[{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"}]}],qC={};Ee(qC,{json:()=>jq});var jq=[{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"}]}],jC={};Ee(jC,{json:()=>Kq});var Kq=[{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"}]}],KC={};Ee(KC,{json:()=>Xq});var Xq=[{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"}]}],XC={};Ee(XC,{json:()=>Yq});var Yq=[{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"}]}],YC={};Ee(YC,{json:()=>Zq});var Zq=[{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"}]}],ZC={};Ee(ZC,{json:()=>Jq});var Jq=[{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"}]}],JC={};Ee(JC,{json:()=>Qq});var Qq=[{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}]}],QC={};Ee(QC,{json:()=>ej});var ej=[{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"}]}],e_={};Ee(e_,{json:()=>tj});var tj=[{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:[]}],JI=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[PC,OC,LC,zC,WC,BC,VC,UC,GC,HC,qC,jC,KC,XC,YC,ZC,JC,QC,e_],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,a)=>(n[a.tfOpName]=a,n),{})}transformGraph(e,t={}){let n=e.node,a=[],r=[],s=[],i=n.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?a.push(m[f.name]):f.op==="Const"?r.push(m[f.name]):(f.input==null||f.input.length===0)&&s.push(m[f.name]),m),{}),o=[],l=[],u={},p={};t!=null&&(u=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));let d=Object.keys(i);d.forEach(m=>{let f=i[m];f.inputNames.forEach((g,b)=>{let[y,,x]=Er(g),v=i[y];if(v.outputs!=null){let I=v.outputs.indexOf(x);if(I!==-1){let T=`${y}:${I}`;f.inputNames[b]=T}}f.inputs.push(v),v.children.push(f)})}),Object.keys(p).length===0?d.forEach(m=>{let f=i[m];f.children.length===0&&l.push(f)}):Object.keys(p).forEach(m=>{let[f]=Er(m),g=i[f];g!=null&&(g.signatureKey=p[m],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(m=>{let[f]=Er(m),g=i[f];g&&(g.signatureKey=u[m],o.push(g))}):o=a;let c={};e.library!=null&&e.library.function!=null&&(c=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));let h={nodes:i,inputs:o,outputs:l,weights:r,placeholders:a,signature:t,functions:c};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=MC(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(a=>a.startsWith("^")?a.slice(1):a),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((a,r)=>(a[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},a),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((a,r)=>{let s=r.type,i;switch(r.type){case"string":i=Zx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Zx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=rv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=rv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=Qx(e.attr,r.tfName,r.defaultValue||0),i===void 0&&r.tfDeprecatedName&&(i=Qx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=av(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=av(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=Jx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Jx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=iv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=iv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":i=nv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=nv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":i=sv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=sv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":i=ev(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=ev(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=tv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=tv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=QI(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=QI(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return a[r.name]={value:i,type:s},a},{})),n}mapFunction(e){let t=e.nodeDef,n=[],a=[],r={};t!=null&&(r=t.reduce((u,p)=>(u[p.name]=this.mapNode(p),p.op==="Const"&&a.push(u[p.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[p]=Er(u.name),d={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:F1(u.type),type:"dtype"}},children:[]};d.signatureKey=u.name,s.push(d),r[p]=d}),Object.keys(r).forEach(u=>{let p=r[u];p.inputNames.forEach((d,c)=>{let[h,,m]=Er(d),f=r[h];if(f.outputs!=null){let g=f.outputs.indexOf(m);if(g!==-1){let b=`${h}:${g}`;p.inputNames[c]=b}}p.inputs.push(f),f.children.push(p)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[p,d]=Er(o[u.name]),c=r[p];c!=null&&(c.defaultOutput=d,i.push(c))});let l=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:i,weights:a,placeholders:n,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function nj(e){let t=G().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function t_(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):nj(e);return t?n:n.toLowerCase()}function Zx(e,t,n,a=!1){let r=e[t];return r!=null?t_(r.s,a):n}function Jx(e,t,n){let a=e[t];return a?a.b:n}function Qx(e,t,n){let a=e[t]||{},r=a.i!=null?a.i:a.f!=null?a.f:n;return typeof r=="number"?r:parseInt(r,10)}function F1(e){switch(typeof e=="string"&&(e=_a[e]),e){case _a.DT_FLOAT:case _a.DT_HALF:return"float32";case _a.DT_INT32:case _a.DT_INT64:case _a.DT_INT8:case _a.DT_UINT8:return"int32";case _a.DT_BOOL:return"bool";case _a.DT_DOUBLE:return"float32";case _a.DT_STRING:return"string";default:return null}}function QI(e,t,n){let a=e[t];return a&&a.func?a.func.name:n}function ev(e,t,n){let a=e[t];return a&&a.type?F1(a.type):n}function tv(e,t,n){let a=e[t];return a&&a.list&&a.list.type?a.list.type.map(r=>F1(r)):n}function n_(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function nv(e,t,n){let a=e[t];return a&&a.shape?n_(a.shape):n}function av(e,t,n){let a=e[t];return a?((a.list.f&&a.list.f.length?a.list.f:a.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function rv(e,t,n,a=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>t_(s,a)):n}function sv(e,t,n){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(r=>n_(r)):n}function iv(e,t,n){let a=e[t];return a&&a.list&&a.list.b?a.list.b:n}var aj=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(a=>this.getInput(a)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((a,r)=>(a[r]=this.getAttr(r),a),{}))}getInput(e){return dn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return dn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return Qx(this.node.rawAttrs,e,t);if(n.s!=null)return Zx(this.node.rawAttrs,e,t);if(n.b!=null)return Jx(this.node.rawAttrs,e,t);if(n.shape!=null)return nv(this.node.rawAttrs,e,t);if(n.type!=null)return ev(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return av(this.node.rawAttrs,e,t);if(n.list.s!=null)return rv(this.node.rawAttrs,e,t);if(n.list.shape!=null)return sv(this.node.rawAttrs,e,t);if(n.list.b!=null)return iv(this.node.rawAttrs,e,t);if(n.list.type!=null)return tv(this.node.rawAttrs,e,t)}return t}},ln={};Ee(ln,{OP_SCOPE_SUFFIX:()=>Dv,abs:()=>Wt,acos:()=>Lv,acosh:()=>zv,add:()=>X,addN:()=>AN,all:()=>Qm,any:()=>kc,argMax:()=>di,argMin:()=>Wv,asin:()=>Bv,asinh:()=>Vv,atan:()=>Uv,atan2:()=>Gv,atanh:()=>Hv,avgPool:()=>xa,avgPool3d:()=>jv,basicLSTMCell:()=>RN,batchNorm:()=>_s,batchNorm2d:()=>Kv,batchNorm3d:()=>Xv,batchNorm4d:()=>Yv,batchToSpaceND:()=>pd,bincount:()=>Zv,bitwiseAnd:()=>MN,booleanMaskAsync:()=>NT,broadcastArgs:()=>PN,broadcastTo:()=>ri,buffer:()=>ze,cast:()=>se,ceil:()=>Jv,clipByValue:()=>sn,clone:()=>or,complex:()=>Rr,concat:()=>et,concat1d:()=>Qv,concat2d:()=>ew,concat3d:()=>tw,concat4d:()=>nw,conv1d:()=>ef,conv2d:()=>Rt,conv2dTranspose:()=>tf,conv3d:()=>rw,conv3dTranspose:()=>sw,cos:()=>cd,cosh:()=>nf,cosineWindow:()=>Nf,cumprod:()=>Nc,cumsum:()=>af,denseBincount:()=>dm,depthToSpace:()=>iw,depthwiseConv2d:()=>Es,diag:()=>LN,dilation2d:()=>ow,div:()=>he,divNoNan:()=>lw,dot:()=>uw,dropout:()=>zw,einsum:()=>WN,elu:()=>cp,enclosingPowerOfTwo:()=>Ww,ensureShape:()=>BN,equal:()=>ta,erf:()=>pw,euclideanNorm:()=>hw,exp:()=>yn,expandDims:()=>nn,expm1:()=>mw,eye:()=>rf,fft:()=>vd,fill:()=>xn,floor:()=>hp,floorDiv:()=>Jm,fused:()=>Zl,gather:()=>mp,gatherND:()=>ET,greater:()=>_n,greaterEqual:()=>Or,ifft:()=>Yl,imag:()=>dd,image:()=>ea,inTopKAsync:()=>AT,irfft:()=>xf,isFinite:()=>fw,isInf:()=>gw,isNaN:()=>bw,leakyRelu:()=>hd,less:()=>ql,lessEqual:()=>As,linalg:()=>Uw,linspace:()=>qN,localResponseNormalization:()=>yw,log:()=>na,log1p:()=>md,logSigmoid:()=>xw,logSoftmax:()=>of,logSumExp:()=>lf,logicalAnd:()=>Da,logicalNot:()=>fd,logicalOr:()=>uf,logicalXor:()=>vw,losses:()=>VT,lowerBound:()=>KN,matMul:()=>$e,max:()=>ga,maxPool:()=>Mt,maxPool3d:()=>ww,maxPoolWithArgmax:()=>XN,maximum:()=>fr,mean:()=>Et,meshgrid:()=>YN,min:()=>Hl,minimum:()=>fs,mirrorPad:()=>kw,mod:()=>Iw,moments:()=>gd,movingAverage:()=>TT,mul:()=>z,multiRNNCell:()=>ZN,multinomial:()=>JN,neg:()=>yt,norm:()=>dp,notEqual:()=>gi,oneHot:()=>jl,ones:()=>Qn,onesLike:()=>aa,op:()=>L,outerProduct:()=>QN,pad:()=>va,pad1d:()=>eT,pad2d:()=>tT,pad3d:()=>nT,pad4d:()=>aT,pool:()=>Sw,pow:()=>Mr,prelu:()=>yd,print:()=>Pv,prod:()=>Nw,raggedGather:()=>rT,raggedRange:()=>sT,raggedTensorToTensor:()=>iT,rand:()=>oT,randomGamma:()=>cT,randomNormal:()=>cf,randomStandardNormal:()=>dT,randomUniform:()=>Fs,randomUniformInt:()=>hT,range:()=>bi,real:()=>Kl,reciprocal:()=>Aw,relu:()=>Ke,relu6:()=>df,reshape:()=>W,reverse:()=>ya,reverse1d:()=>mT,reverse2d:()=>fT,reverse3d:()=>gT,reverse4d:()=>bT,rfft:()=>wd,round:()=>hf,rsqrt:()=>mf,scalar:()=>ve,scatterND:()=>CT,searchSorted:()=>pf,selu:()=>ff,separableConv2d:()=>$s,setdiff1dAsync:()=>yT,sigmoid:()=>fa,sign:()=>Fw,signal:()=>BT,sin:()=>gf,sinh:()=>bf,slice:()=>Ue,slice1d:()=>xd,slice2d:()=>yf,slice3d:()=>qo,slice4d:()=>Xl,softmax:()=>Xa,softplus:()=>Ho,spaceToBatchND:()=>bd,sparse:()=>UT,sparseToDense:()=>_T,spectral:()=>WT,split:()=>zn,sqrt:()=>mn,square:()=>ut,squaredDifference:()=>vf,squeeze:()=>Ds,stack:()=>Dt,step:()=>jo,stridedSlice:()=>$w,string:()=>GT,sub:()=>pe,sum:()=>fe,tan:()=>Dw,tanh:()=>mi,tensor:()=>bn,tensor1d:()=>je,tensor2d:()=>$a,tensor3d:()=>kd,tensor4d:()=>Ma,tensor5d:()=>xT,tensor6d:()=>vT,tensorScatterUpdate:()=>kT,tile:()=>Ln,topk:()=>Mw,transpose:()=>De,truncatedNormal:()=>If,unique:()=>Pw,unsortedSegmentSum:()=>Sf,unstack:()=>ct,upperBound:()=>IT,variable:()=>Ow,where:()=>rn,whereAsync:()=>Lw,zeros:()=>Nt,zerosLike:()=>qe});var rj=(e,t,n,a=ln)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[a.add(k("a",e,t,n),k("b",e,t,n))];case"AddN":return[a.addN(k("tensors",e,t,n))];case"FloorMod":case"Mod":return[a.mod(k("a",e,t,n),k("b",e,t,n))];case"Mul":return[a.mul(k("a",e,t,n),k("b",e,t,n))];case"RealDiv":case"Div":return[a.div(k("a",e,t,n),k("b",e,t,n))];case"DivNoNan":return[a.divNoNan(k("a",e,t,n),k("b",e,t,n))];case"FloorDiv":return[a.floorDiv(k("a",e,t,n),k("b",e,t,n))];case"Sub":return[a.sub(k("a",e,t,n),k("b",e,t,n))];case"Minimum":return[a.minimum(k("a",e,t,n),k("b",e,t,n))];case"Maximum":return[a.maximum(k("a",e,t,n),k("b",e,t,n))];case"Pow":return[a.pow(k("a",e,t,n),k("b",e,t,n))];case"SquaredDifference":return[a.squaredDifference(k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},sj=(e,t,n,a=ln)=>{switch(e.op){case"Abs":case"ComplexAbs":return[a.abs(k("x",e,t,n))];case"Acos":return[a.acos(k("x",e,t,n))];case"Acosh":return[a.acosh(k("x",e,t,n))];case"Asin":return[a.asin(k("x",e,t,n))];case"Asinh":return[a.asinh(k("x",e,t,n))];case"Atan":return[a.atan(k("x",e,t,n))];case"Atan2":return[a.atan2(k("x",e,t,n),k("y",e,t,n))];case"Atanh":return[a.atanh(k("x",e,t,n))];case"Ceil":return[a.ceil(k("x",e,t,n))];case"Complex":return[a.complex(k("real",e,t,n),k("imag",e,t,n))];case"Cos":return[a.cos(k("x",e,t,n))];case"Cosh":return[a.cosh(k("x",e,t,n))];case"Elu":return[a.elu(k("x",e,t,n))];case"Erf":return[a.erf(k("x",e,t,n))];case"Exp":return[a.exp(k("x",e,t,n))];case"Expm1":return[a.expm1(k("x",e,t,n))];case"Floor":return[a.floor(k("x",e,t,n))];case"Log":return[a.log(k("x",e,t,n))];case"Log1p":return[a.log1p(k("x",e,t,n))];case"Imag":return[a.imag(k("x",e,t,n))];case"Neg":return[a.neg(k("x",e,t,n))];case"Reciprocal":return[a.reciprocal(k("x",e,t,n))];case"Real":return[a.real(k("x",e,t,n))];case"Relu":return[a.relu(k("x",e,t,n))];case"Round":return[a.round(k("x",e,t,n))];case"Selu":return[a.selu(k("x",e,t,n))];case"Sigmoid":return[a.sigmoid(k("x",e,t,n))];case"Sin":return[a.sin(k("x",e,t,n))];case"Sign":return[a.sign(k("x",e,t,n))];case"Sinh":return[a.sinh(k("x",e,t,n))];case"Softplus":return[a.softplus(k("x",e,t,n))];case"Sqrt":return[a.sqrt(k("x",e,t,n))];case"Square":return[a.square(k("x",e,t,n))];case"Tanh":return[a.tanh(k("x",e,t,n))];case"Tan":return[a.tan(k("x",e,t,n))];case"ClipByValue":return[a.clipByValue(k("x",e,t,n),k("clipValueMin",e,t,n),k("clipValueMax",e,t,n))];case"Relu6":return[a.relu6(k("x",e,t,n))];case"Rsqrt":return[a.rsqrt(dn(e.inputNames[0],t,n))];case"LeakyRelu":return[a.leakyRelu(k("x",e,t,n),k("alpha",e,t,n))];case"Prelu":return[a.prelu(k("x",e,t,n),k("alpha",e,t,n))];case"IsNan":return[a.isNaN(dn(e.inputNames[0],t,n))];case"IsInf":return[a.isInf(dn(e.inputNames[0],t,n))];case"IsFinite":return[a.isFinite(dn(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Fa(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){w.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let a=0;a<e.length;a++){let r=e[a],s=t[a];w.assert(r<0||s<0||r===s,()=>n+` Shapes ${e} and ${t} must match`)}}}function eS(e){return!(typeof e=="number"||e.some(t=>t<0))}function tc(e,t,n){let a=ov(e,n),r=!eS(a);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${a}`);if(r&&t.forEach(s=>{a=ov(s.shape,a)}),!eS(a))throw new Error(`Non-fully-defined elementShape: ${a}`);return a}function ov(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let a=0;a<e.length;++a){let r=e[a],s=t[a];if(r>=0&&s>=0&&r!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[a]=r>=0?r:s}return n}var ij=class{constructor(e,t,n,a,r,s,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=a,this.identicalElementShapes=r,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=ve(0),qt(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
          because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Fa(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,qt(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,a)=>this.write(n,t[a]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let a=0;a<this.size();a++)e.push(a)}if(e.length===0)return bn([],[0].concat(this.elementShape));let n=this.readMany(e);return Fa(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Dt(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return bn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return Fa(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),et(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n}  vs. ${this.maxSize})`);this.writeMany(e,ct(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,a=e.map(o=>(n+=o,n));if(n!==t.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: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let r=n===0?0:t.size/n,s=[];P(()=>{t=W(t,[1,n,r]);for(let o=0;o<e.length;++o){let l=[0,o===0?0:a[o-1],0],u=[1,e[o],r];s[o]=W(Ue(t,l,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},nu=class{get id(){return this.idTensor.id}constructor(e,t,n,a=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(r=>{if(n!==r.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);Fa(t,r.shape,"TensorList shape mismatch: "),qt(r)}),this.idTensor=ve(0),this.maxNumElements=a,qt(this.idTensor)}copy(){return new nu([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, 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.`);Fa(e,this.elementShape,"TensorList shape mismatch: ");let a=tc(this.elementShape,this.tensors,e);return P(()=>{let r=this.tensors.map(s=>W(s,a));return Dt(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=tc(this.elementShape,this.tensors,e),a=this.tensors.pop();return a.kept=!1,Fa(a.shape,e,"TensorList shape mismatch: "),W(a,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Fa(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");qt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);let t=new nu([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);Fa(this.tensors[e].shape,t,"TensorList shape mismatch: ");let a=tc(this.elementShape,this.tensors,t);return W(this.tensors[e],a)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Fa(this.elementShape,t.shape,"TensorList shape mismatch: "),qt(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Fa(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let a=tc(this.elementShape,this.tensors,n);return e.length===0?bn([],[0].concat(a)):P(()=>{let r=e.map(s=>W(this.tensors[s],a));return Dt(r,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Fa(this.elementShape,t,"TensorList shape mismatch: ");let n=tc(this.elementShape,this.tensors,t);return this.size()===0?bn([],[0].concat(n)):P(()=>{let a=this.tensors.map(r=>W(r,n));return et(a,0)})}};function oj(e,t,n){let a=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let r=e.shape.slice(1);Fa(r,t,"TensorList shape mismatch: ");let s=ct(e);return new nu(s,t,a)}function lj(e,t,n,a){return new nu([],e,t,a)}function uj(e,t,n,a){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(a!=null&&a!==-1&&r>=a)throw new Error(`Max index must be < array size (${r}  vs. ${a})`);let s=new nu([],n,e.dtype,a),i=ct(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function pj(e,t,n){let a=0,r=t.map(p=>(a+=p,a));if(a!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
          tensor.shape[0], but sum of lengths is
        ${a}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=ov(s,n),o=a===0?0:e.size/a,l=P(()=>{let p=[];e=W(e,[1,a,o]);for(let d=0;d<t.length;++d){let c=[0,d===0?0:r[d-1],0],h=[1,t[d],o];p[d]=W(Ue(e,c,h),i)}return e.dispose(),p}),u=new nu([],n,e.dtype,t.length);for(let p=0;p<l.length;p++)u.setItem(p,l[p]);return u}var cj=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let a=k("thenBranch",e,t,n),r=k("elseBranch",e,t,n),s=k("cond",e,t,n),i=k("args",e,t,n);return(await s.data())[0]?n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let a=k("body",e,t,n),r=k("cond",e,t,n),s=k("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map(p=>p.id),l=await i[0].data();i.forEach(p=>{!p.kept&&o.indexOf(p.id)===-1&&p.dispose()});let u=s;for(;l[0];){let p=u;u=await n.functionMap[a].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let d=u.map(h=>h.id);p.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let c=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await c[0].data(),c.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let a=k("pred",e,t,n);return[Ar(a)]}case"Switch":{let a=k("pred",e,t,n),r=k("data",e,t,n);return r.kept||(r=Ar(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>dn(r,t,n)!==void 0);if(a){let r=dn(a,t,n);return[Ar(r)]}return}case"Enter":{let a=k("frameName",e,t,n),r=k("tensor",e,t,n);return n.enterFrame(a),[Ar(r)]}case"Exit":{let a=k("tensor",e,t,n);return n.exitFrame(),[Ar(a)]}case"NextIteration":{let a=k("tensor",e,t,n);return n.nextIteration(),[Ar(a)]}case"TensorArrayV3":{let a=k("size",e,t,n),r=k("dtype",e,t,n),s=k("elementShape",e,t,n),i=k("dynamicSize",e,t,n),o=k("clearAfterRead",e,t,n),l=k("identicalElementShapes",e,t,n),u=k("name",e,t,n),p=new ij(u,r,a,s,l,i,o);return n.addTensorArray(p),[p.idTensor,ve(1)]}case"TensorArrayWriteV3":{let a=k("tensorArrayId",e,t,n),r=k("index",e,t,n),s=k("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=k("tensorArrayId",e,t,n),r=k("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=k("tensorArrayId",e,t,n),r=k("indices",e,t,n),s=k("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=k("tensorArrayId",e,t,n),r=k("indices",e,t,n),s=k("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=k("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=k("tensorArrayId",e,t,n),r=k("tensor",e,t,n),s=k("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[ve(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=k("tensorListId",e,t,n),r=k("index",e,t,n),s=k("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=k("tensorListId",e,t,n),r=k("index",e,t,n),s=k("elementShape",e,t,n),i=k("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=k("indices",e,t,n),r=k("tensor",e,t,n),s=k("elementShape",e,t,n),i=k("numElements",e,t,n),o=uj(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=k("elementShape",e,t,n),r=k("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,n),o=e.op==="TensorListReserve"?-1:i,l=lj(a,r,i,o);return n.addTensorList(l),[l.idTensor]}case"TensorListGather":{let a=k("tensorListId",e,t,n),r=k("indices",e,t,n),s=k("elementShape",e,t,n),i=k("elementDType",e,t,n);return[n.getTensorList(a.id).gather(r,i,s)]}case"TensorListStack":{let a=k("tensorListId",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),i=k("numElements",e,t,n);return[n.getTensorList(a.id).stack(r,s,i)]}case"TensorListFromTensor":{let a=k("tensor",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),i=oj(a,r,s);return n.addTensorList(i),[i.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let a=k("tensorListId",e,t,n),r=n.getTensorList(a.id),s=k("dtype",e,t,n),i=k("elementShape",e,t,n);return[r.concat(s,i)]}case"TensorListPushBack":{let a=k("tensorListId",e,t,n),r=k("tensor",e,t,n),s=n.getTensorList(a.id);return s.pushBack(r),[s.idTensor]}case"TensorListPopBack":{let a=k("tensorListId",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n);return[n.getTensorList(a.id).popBack(r,s)]}case"TensorListSplit":{let a=k("tensor",e,t,n),r=k("elementShape",e,t,n),s=k("lengths",e,t,n),i=pj(a,s,r);return n.addTensorList(i),[i.idTensor]}case"TensorListLength":{let a=k("tensorListId",e,t,n),r=n.getTensorList(a.id);return[ve(r.size(),"int32")]}case"TensorListResize":{let a=k("tensorListId",e,t,n),r=k("size",e,t,n),s=n.getTensorList(a.id).resize(r);return n.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function tS(e,t,n){let[a,r]=k("fusedOps",e,t,n),s=a==="biasadd",i=!s,o=r==="prelu",l=a==="fusedbatchnorm",u=k("numArgs",e,t,n);if(s){if(o&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let p=k("strides",e,t,n),d=Yh(e,t,n),c=k("dataFormat",e,t,n).toUpperCase(),h=k("dilations",e,t,n),[m,f]=k("args",e,t,n);i&&(f=m,m=void 0);let g=k("leakyreluAlpha",e,t,n);return{stride:p,pad:d,dataFormat:c,dilations:h,biasArg:m,preluArg:f,activationFunc:r,leakyreluAlpha:g}}var dj=(e,t,n,a=ln)=>{switch(e.op){case"Conv1D":{let r=k("stride",e,t,n),s=k("pad",e,t,n),i=k("dataFormat",e,t,n).toUpperCase(),o=k("dilation",e,t,n);return[a.conv1d(k("x",e,t,n),k("filter",e,t,n),r,s,i,o)]}case"Conv2D":{let r=k("strides",e,t,n),s=Yh(e,t,n),i=k("dataFormat",e,t,n).toUpperCase(),o=k("dilations",e,t,n);return[a.conv2d(k("x",e,t,n),k("filter",e,t,n),[r[1],r[2]],s,i,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:p,leakyreluAlpha:d}=tS(e,t,n);return[a.fused.conv2d({x:k("x",e,t,n),filter:k("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:p,preluActivationWeights:u,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:p,leakyreluAlpha:d}=tS(e,t,n);return[a.fused.depthwiseConv2d({x:k("x",e,t,n),filter:k("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:p,preluActivationWeights:u,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=k("outputShape",e,t,n),s=k("strides",e,t,n),i=Yh(e,t,n);return[a.conv2dTranspose(k("x",e,t,n),k("filter",e,t,n),r,[s[1],s[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let r=k("strides",e,t,n),s=Yh(e,t,n),i=k("dilations",e,t,n),o=k("dataFormat",e,t,n).toUpperCase();return[a.depthwiseConv2d(k("input",e,t,n),k("filter",e,t,n),[r[1],r[2]],s,o,[i[1],i[2]])]}case"Conv3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("dataFormat",e,t,n).toUpperCase(),o=k("dilations",e,t,n);return[a.conv3d(k("x",e,t,n),k("filter",e,t,n),[r[1],r[2],r[3]],s,i,[o[1],o[2],o[3]])]}case"AvgPool":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.avgPool(k("x",e,t,n),[i[1],i[2]],[r[1],r[2]],s)]}case"MaxPool":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.maxPool(k("x",e,t,n),[i[1],i[2]],[r[1],r[2]],s)]}case"MaxPoolWithArgmax":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n),o=k("includeBatchInIndex",e,t,n),{result:l,indexes:u}=a.maxPoolWithArgmax(k("x",e,t,n),[i[1],i[2]],[r[1],r[2]],s,o);return[l,u]}case"AvgPool3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.avgPool3d(k("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],s)]}case"MaxPool3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.maxPool3d(k("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],s)]}case"Dilation2D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("dilations",e,t,n),o=r[1],l=r[2],u=i[1],p=i[2];return[a.dilation2d(k("x",e,t,n),k("filter",e,t,n),[o,l],s,[u,p],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},hj=(e,t,n,a=ln)=>{switch(e.op){case"Fill":{let r=k("shape",e,t,n),s=k("dtype",e,t,n),i=k("value",e,t,n);return[a.fill(r,i,s)]}case"LinSpace":{let r=k("start",e,t,n),s=k("stop",e,t,n),i=k("num",e,t,n);return[a.linspace(r,s,i)]}case"Multinomial":{let r=k("logits",e,t,n),s=k("numSamples",e,t,n),i=k("seed",e,t,n);return[a.multinomial(r,s,i)]}case"OneHot":{let r=k("indices",e,t,n),s=k("depth",e,t,n),i=k("onValue",e,t,n),o=k("offValue",e,t,n),l=k("dtype",e,t,n);return[a.oneHot(r,s,i,o,l)]}case"Ones":return[a.ones(k("shape",e,t,n),k("dtype",e,t,n))];case"OnesLike":return[a.onesLike(k("x",e,t,n))];case"RandomStandardNormal":return[a.randomStandardNormal(k("shape",e,t,n),k("dtype",e,t,n),k("seed",e,t,n))];case"RandomUniform":return[a.randomUniform(k("shape",e,t,n),k("minval",e,t,n),k("maxval",e,t,n),k("dtype",e,t,n))];case"RandomUniformInt":return[a.randomUniformInt(k("shape",e,t,n),k("minval",e,t,n),k("maxval",e,t,n),k("seed",e,t,n))];case"Range":{let r=k("start",e,t,n),s=k("stop",e,t,n),i=k("step",e,t,n);return[a.range(r,s,i,k("dtype",e,t,n))]}case"TruncatedNormal":{let r=k("shape",e,t,n),s=k("mean",e,t,n),i=k("stdDev",e,t,n),o=k("seed",e,t,n);return[a.truncatedNormal(r,s,i,k("dtype",e,t,n),o)]}case"Zeros":return[a.zeros(k("shape",e,t,n),k("dtype",e,t,n))];case"ZerosLike":return[a.zerosLike(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kx(e,t,n){let a=k("boxes",e,t,n),r=k("scores",e,t,n),s=k("maxOutputSize",e,t,n),i=k("iouThreshold",e,t,n),o=k("scoreThreshold",e,t,n),l=k("softNmsSigma",e,t,n);return{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var mj=async(e,t,n,a,r=ln)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u,softNmsSigma:p}=kx(e,t,n),d=await r.image.nonMaxSuppressionWithScoreAsync(s,i,o,l,u,p);return[d.selectedIndices,d.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=kx(e,t,n),p=k("padToMaxOutputSize",e,t,n),d=await r.image.nonMaxSuppressionPaddedAsync(s,i,o,l,u,p);return[d.selectedIndices,d.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=kx(e,t,n);return[await r.image.nonMaxSuppressionAsync(s,i,o,l,u)]}case"Where":{let s=r.cast(k("condition",e,t,n),"bool"),i=[await r.whereAsync(s)];return s.dispose(),i}case"ListDiff":return r.setdiff1dAsync(k("x",e,t,n),k("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},fj=(e,t,n,a=ln)=>{switch(e.op){case"LowerBound":{let r=k("sortedSequence",e,t,n),s=k("values",e,t,n);return[a.lowerBound(r,s)]}case"TopKV2":{let r=k("x",e,t,n),s=k("k",e,t,n),i=k("sorted",e,t,n),o=a.topk(r,s,i);return[o.values,o.indices]}case"UpperBound":{let r=k("sortedSequence",e,t,n),s=k("values",e,t,n);return[a.upperBound(r,s)]}case"Unique":{let r=k("x",e,t,n),s=a.unique(r);return[s.values,s.indices]}case"UniqueV2":{let r=k("x",e,t,n),s=k("axis",e,t,n),i=a.unique(r,s);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},gj=(e,t,n,a=ln)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=k("default",e,t,n);return[dn(e.name,t,n)||r];case"Placeholder":return[dn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let p=k("x",e,t,n);return[Ar(p)]}case"IdentityN":return k("x",e,t,n).map(p=>Ar(p));case"Snapshot":let s=k("x",e,t,n);return[Ar(s)];case"Shape":return[a.tensor1d(k("x",e,t,n).shape,"int32")];case"ShapeN":return k("x",e,t,n).map(p=>a.tensor1d(p.shape));case"Size":return[a.scalar(k("x",e,t,n).size,"int32")];case"Rank":return[a.scalar(k("x",e,t,n).rank,"int32")];case"NoOp":return[a.scalar(1)];case"Print":let i=k("x",e,t,n),o=k("data",e,t,n),l=k("message",e,t,n),u=k("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let p=0;p<o.length;p++)console.log(Array.prototype.slice.call(o[p].dataSync()).slice(0,u));return[i];default:throw TypeError(`Node type ${e.op} is not implemented`)}},bj=class{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=ve(0),this.tensorMap=new Map,qt(this.handle)}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return ve(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(a=>a.dispose()),this.tensorMap.clear(),P(()=>{let a=ct(t),r=n.length,s=a.length;w.assert(r===s,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`);for(let i=0;i<r;i++){let o=n[i],l=a[i];qt(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return P(()=>{let a=[];for(let r=0;r<n.length;r++){let s=n[r],i=this.findWithDefault(s,t);a.push(i)}return Dt(a)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},yj=async(e,t,n,a)=>{switch(e.op){case"HashTable":case"HashTableV2":{let r=a.getHashTableHandleByName(e.name);if(r!=null)return[r];{let s=k("keyDType",e,t,n),i=k("valueDType",e,t,n),o=new bj(s,i);return a.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{let r=k("tableHandle",e,t,n,a),s=k("keys",e,t,n),i=k("values",e,t,n);return[await a.getHashTableById(r.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let r=k("tableHandle",e,t,n,a),s=k("keys",e,t,n),i=k("defaultValue",e,t,n);return[await a.getHashTableById(r.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=k("tableHandle",e,t,n,a);return[a.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},xj=(e,t,n,a=ln)=>{switch(e.op){case"ResizeBilinear":{let r=k("images",e,t,n),s=k("size",e,t,n),i=k("alignCorners",e,t,n),o=k("halfPixelCenters",e,t,n);return[a.image.resizeBilinear(r,[s[0],s[1]],i,o)]}case"ResizeNearestNeighbor":{let r=k("images",e,t,n),s=k("size",e,t,n),i=k("alignCorners",e,t,n),o=k("halfPixelCenters",e,t,n);return[a.image.resizeNearestNeighbor(r,[s[0],s[1]],i,o)]}case"CropAndResize":{let r=k("image",e,t,n),s=k("boxes",e,t,n),i=k("boxInd",e,t,n),o=k("cropSize",e,t,n),l=k("method",e,t,n),u=k("extrapolationValue",e,t,n);return[a.image.cropAndResize(r,s,i,o,l,u)]}case"ImageProjectiveTransformV3":{let r=k("images",e,t,n),s=k("transforms",e,t,n),i=k("outputShape",e,t,n),o=k("fillValue",e,t,n),l=k("interpolation",e,t,n),u=k("fillMode",e,t,n);return[a.image.transform(r,s,l.toLowerCase(),u.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},vj=(e,t,n,a=ln)=>{switch(e.op){case"Equal":return[a.equal(k("a",e,t,n),k("b",e,t,n))];case"NotEqual":return[a.notEqual(k("a",e,t,n),k("b",e,t,n))];case"Greater":return[a.greater(k("a",e,t,n),k("b",e,t,n))];case"GreaterEqual":return[a.greaterEqual(k("a",e,t,n),k("b",e,t,n))];case"Less":return[a.less(k("a",e,t,n),k("b",e,t,n))];case"LessEqual":return[a.lessEqual(k("a",e,t,n),k("b",e,t,n))];case"LogicalAnd":return[a.logicalAnd(k("a",e,t,n),k("b",e,t,n))];case"LogicalNot":return[a.logicalNot(k("a",e,t,n))];case"LogicalOr":return[a.logicalOr(k("a",e,t,n),k("b",e,t,n))];case"Select":case"SelectV2":return[a.where(k("condition",e,t,n),k("a",e,t,n),k("b",e,t,n))];case"BitwiseAnd":return[a.bitwiseAnd(k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},wj=(e,t,n,a=ln)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[a.matMul(k("a",e,t,n),k("b",e,t,n),k("transposeA",e,t,n),k("transposeB",e,t,n))];case"Einsum":return[a.einsum(k("equation",e,t,n),...k("tensors",e,t,n))];case"Transpose":return[a.transpose(k("x",e,t,n),k("perm",e,t,n))];case"_FusedMatMul":let[r,s]=k("fusedOps",e,t,n),i=r==="biasadd",o=s==="prelu",l=k("numArgs",e,t,n),u=k("leakyreluAlpha",e,t,n);if(i){if(o&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[p,d]=k("args",e,t,n);return[a.fused.matMul({a:k("a",e,t,n),b:k("b",e,t,n),transposeA:k("transposeA",e,t,n),transposeB:k("transposeB",e,t,n),bias:p,activation:s,preluActivationWeights:d,leakyreluAlpha:u})];case"MatrixBandPart":return[a.linalg.bandPart(k("a",e,t,n),k("numLower",e,t,n),k("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},kj=(e,t,n,a=ln)=>{switch(e.op){case"EuclideanNorm":return[a.euclideanNorm(k("x",e,t,n),k("axis",e,t,n),k("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":return[a.batchNorm(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"FusedBatchNormV3":return[a.batchNorm(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"LRN":return[a.localResponseNormalization(k("x",e,t,n),k("radius",e,t,n),k("bias",e,t,n),k("alpha",e,t,n),k("beta",e,t,n))];case"Softmax":return[a.softmax(k("x",e,t,n))];case"LogSoftmax":return[a.logSoftmax(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Ij=(e,t,n,a=ln)=>{switch(e.op){case"RaggedGather":{let{outputNestedSplits:r,outputDenseValues:s}=a.raggedGather(k("paramsNestedSplits",e,t,n),k("paramsDenseValues",e,t,n),k("indices",e,t,n),k("outputRaggedRank",e,t,n));return r.concat(s)}case"RaggedRange":{let{rtNestedSplits:r,rtDenseValues:s}=a.raggedRange(k("starts",e,t,n),k("limits",e,t,n),k("splits",e,t,n));return[r,s]}case"RaggedTensorToTensor":return[a.raggedTensorToTensor(k("shape",e,t,n),k("values",e,t,n),k("defaultValue",e,t,n),k("rowPartitionTensors",e,t,n),k("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Sj=(e,t,n,a=ln)=>{switch(e.op){case"Max":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.max(k("x",e,t,n),o,l)]}case"Mean":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.mean(k("x",e,t,n),o,l)]}case"Min":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.min(k("x",e,t,n),o,l)]}case"Sum":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.sum(k("x",e,t,n),o,l)]}case"All":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.all(k("x",e,t,n),o,l)]}case"Any":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.any(k("x",e,t,n),o,l)]}case"ArgMax":{let o=k("axis",e,t,n);return[a.argMax(k("x",e,t,n),o)]}case"ArgMin":{let o=k("axis",e,t,n);return[a.argMin(k("x",e,t,n),o)]}case"Prod":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.prod(k("x",e,t,n),o,l)]}case"Cumprod":{let o=k("axis",e,t,n),l=k("exclusive",e,t,n),u=k("reverse",e,t,n);return[a.cumprod(k("x",e,t,n),o,l,u)]}case"Cumsum":{let o=k("axis",e,t,n),l=k("exclusive",e,t,n),u=k("reverse",e,t,n);return[a.cumsum(k("x",e,t,n),o,l,u)]}case"Bincount":let r=k("x",e,t,n),s=k("weights",e,t,n),i=k("size",e,t,n);return[a.bincount(r,s,i)];case"DenseBincount":{let o=k("x",e,t,n),l=k("weights",e,t,n),u=k("size",e,t,n),p=k("binaryOutput",e,t,n);return[a.denseBincount(o,l,u,p)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Nj=(e,t,n,a=ln)=>{switch(e.op){case"ConcatV2":case"Concat":{let r=k("n",e,t,n),s=k("axis",e,t,n),i=k("tensors",e,t,n);return i=i.slice(0,r),[a.concat(i,s)]}case"Gather":{let r=k("x",e,t,n),s=k("indices",e,t,n);return[a.gather(r,a.cast(s,"int32"),0)]}case"GatherV2":{let r=k("axis",e,t,n),s=k("batchDims",e,t,n),i=k("x",e,t,n),o=k("indices",e,t,n);return[a.gather(i,a.cast(o,"int32"),r,s)]}case"Reverse":{let r=k("dims",e,t,n),s=[];for(let o=0;o<r.length;o++)r[o]&&s.push(o);let i=k("x",e,t,n);return[a.reverse(i,s)]}case"ReverseV2":{let r=k("axis",e,t,n),s=k("x",e,t,n);return[a.reverse(s,r)]}case"Slice":{let r=k("begin",e,t,n),s=k("size",e,t,n);return[a.slice(k("x",e,t,n),r,s)]}case"StridedSlice":{let r=k("begin",e,t,n),s=k("end",e,t,n),i=k("strides",e,t,n),o=k("beginMask",e,t,n),l=k("endMask",e,t,n),u=k("ellipsisMask",e,t,n),p=k("newAxisMask",e,t,n),d=k("shrinkAxisMask",e,t,n),c=k("x",e,t,n);return[a.stridedSlice(c,r,s,i,o,l,u,p,d)]}case"Pack":return P(()=>{let r=k("axis",e,t,n),s=k("tensors",e,t,n),i=s[0].shape,o=a.squeeze(s[0]).shape,l=s.map(u=>{let p=w.arraysEqual(u.shape,i);if(!p&&!w.arraysEqual(a.squeeze(u).shape,o))throw new Error("the input tensors shape does not match");return p?u:a.reshape(u,i)});return[a.stack(l,r)]});case"Unpack":{let r=k("axis",e,t,n),s=k("tensor",e,t,n);return a.unstack(s,r)}case"Tile":{let r=k("reps",e,t,n);return[a.tile(k("x",e,t,n),r)]}case"Split":case"SplitV":{let r=k("axis",e,t,n),s=k("numOrSizeSplits",e,t,n),i=k("x",e,t,n);return a.split(i,s,r)}case"ScatterNd":{let r=k("indices",e,t,n),s=k("values",e,t,n),i=k("shape",e,t,n);return[a.scatterND(r,s,i)]}case"GatherNd":{let r=k("x",e,t,n),s=k("indices",e,t,n);return[a.gatherND(r,s)]}case"SparseToDense":{let r=k("sparseIndices",e,t,n),s=k("outputShape",e,t,n),i=k("sparseValues",e,t,n),o=k("defaultValue",e,t,n);return[a.sparseToDense(r,i,s,i.dtype===o.dtype?o:a.cast(o,i.dtype))]}case"TensorScatterUpdate":{let r=k("indices",e,t,n),s=k("values",e,t,n),i=k("tensor",e,t,n);return[a.tensorScatterUpdate(i,r,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Tj=(e,t,n,a=ln)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:r,outputValues:s,emptyRowIndicator:i,reverseIndexMap:o}=a.sparse.sparseFillEmptyRows(k("indices",e,t,n),k("values",e,t,n),k("denseShape",e,t,n),k("defaultValue",e,t,n));return[r,s,i,o]}case"SparseReshape":{let{outputIndices:r,outputShape:s}=a.sparse.sparseReshape(k("inputIndices",e,t,n),k("inputShape",e,t,n),k("newShape",e,t,n));return[r,s]}case"SparseSegmentMean":return[a.sparse.sparseSegmentMean(k("data",e,t,n),k("indices",e,t,n),k("segmentIds",e,t,n))];case"SparseSegmentSum":return[a.sparse.sparseSegmentSum(k("data",e,t,n),k("indices",e,t,n),k("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Cj=(e,t,n,a=ln)=>{switch(e.op){case"FFT":return[a.fft(k("x",e,t,n))];case"IFFT":return[a.ifft(k("x",e,t,n))];case"RFFT":return[a.rfft(k("x",e,t,n))];case"IRFFT":return[a.irfft(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},_j=(e,t,n,a=ln)=>{switch(e.op){case"StaticRegexReplace":return[a.string.staticRegexReplace(k("input",e,t,n),k("pattern",e,t,n),k("rewrite",e,t,n),k("replaceGlobal",e,t,n))];case"StringNGrams":{let{nGrams:r,nGramsSplits:s}=a.string.stringNGrams(k("data",e,t,n),k("dataSplits",e,t,n),k("separator",e,t,n),k("nGramWidths",e,t,n),k("leftPad",e,t,n),k("rightPad",e,t,n),k("padWidth",e,t,n),k("preserveShortSequences",e,t,n));return[r,s]}case"StringSplit":{let{indices:r,values:s,shape:i}=a.string.stringSplit(k("input",e,t,n),k("delimiter",e,t,n),k("skipEmpty",e,t,n));return[r,s,i]}case"StringToHashBucketFast":return[a.string.stringToHashBucketFast(k("input",e,t,n),k("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Ej=(e,t,n,a=ln)=>{switch(e.op){case"Cast":return[a.cast(k("x",e,t,n),k("dtype",e,t,n))];case"ExpandDims":{let r=k("axis",e,t,n);return[a.expandDims(k("x",e,t,n),r)]}case"Squeeze":{let r=k("axis",e,t,n);return[a.squeeze(k("x",e,t,n),r)]}case"Reshape":return[a.reshape(k("x",e,t,n),k("shape",e,t,n))];case"EnsureShape":return[a.ensureShape(k("x",e,t,n),k("shape",e,t,n))];case"MirrorPad":return[a.mirrorPad(k("x",e,t,n),k("padding",e,t,n),k("mode",e,t,n))];case"PadV2":case"Pad":return[a.pad(k("x",e,t,n),k("padding",e,t,n),k("constantValue",e,t,n))];case"SpaceToBatchND":{let r=k("blockShape",e,t,n),s=k("paddings",e,t,n);return[a.spaceToBatchND(k("x",e,t,n),r,s)]}case"BatchToSpaceND":{let r=k("blockShape",e,t,n),s=k("crops",e,t,n);return[a.batchToSpaceND(k("x",e,t,n),r,s)]}case"DepthToSpace":{let r=k("blockSize",e,t,n),s=k("dataFormat",e,t,n).toUpperCase();return[a.depthToSpace(k("x",e,t,n),r,s)]}case"BroadcastTo":return[a.broadcastTo(k("x",e,t,n),k("shape",e,t,n))];case"BroadcastArgs":return[a.broadcastArgs(k("s0",e,t,n),k("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function nS(e,t,n,a,r=P){let s=((i,o,l)=>{switch(i.category){case"arithmetic":return r(()=>rj(i,o,l));case"basic_math":return r(()=>sj(i,o,l));case"control":return cj(i,o,l);case"convolution":return r(()=>dj(i,o,l));case"creation":return r(()=>hj(i,o,l));case"dynamic":return mj(i,o,l);case"evaluation":return r(()=>fj(i,o,l));case"image":return r(()=>xj(i,o,l));case"graph":return r(()=>gj(i,o,l));case"logical":return r(()=>vj(i,o,l));case"matrices":return r(()=>wj(i,o,l));case"normalization":return r(()=>kj(i,o,l));case"ragged":return r(()=>Ij(i,o,l));case"reduction":return r(()=>Sj(i,o,l));case"slice_join":return r(()=>Nj(i,o,l));case"sparse":return r(()=>Tj(i,o,l));case"spectral":return r(()=>Cj(i,o,l));case"string":return r(()=>_j(i,o,l));case"transformation":return r(()=>Ej(i,o,l));case"hash_table":return yj(i,o,l,a);case"custom":let u=MC(i.op);if(u&&u.customExecutor)return u.customExecutor(new aj(i,o,l));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()`)}})(e,t,n);return w.isPromise(s)?s.then(i=>[].concat(i)):[].concat(s)}var aS=class{constructor(e={},t={},n={},a={},r){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=a,this.parseNodeNameCache=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),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 e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function rS(e,t,n,a){let r=new Set,s=[],i=null,o=null,l=new Set,u=new Set(Object.keys(e).map(c=>Zn(c)[0]));a=a||[];let p=new Set(a.map(c=>Zn(c.name)[0])),d=[...t];for(;d.length>0;){let c=d.pop();if((Qs(c)||Oj(c)||Lj(c))&&i==null&&(i=c,o=i.children.map(h=>h.name).filter(h=>r.has(h))),r.add(c.name),n[c.name]==null&&!u.has(c.name)&&!p.has(c.name)){if(c.inputs.length===0){s.push(c.name);continue}c.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:s,dynamicNode:i,syncInputs:o}}function Aj(e,t){let{usedNodes:n,inputs:a}=t,r=Object.keys(a).map(g=>Zn(g)[0]).map(g=>e.nodes[g]),s=e.initNodes||[],i=g=>n.has(typeof g=="string"?g:g.name);function o(g){return[...new Map(g.map(b=>[b.name,b])).values()]}let l=o([...r,...e.weights,...s]).filter(i),u=o([...l,...Object.values(e.nodes)]).filter(i),p=new Map(u.map(g=>[g.name,g])),d={};for(let g of u){d[g.name]=d[g.name]||0;for(let b of g.children)i(b)||(d[b.name]=Number.POSITIVE_INFINITY),d[b.name]=(d[b.name]||0)+1}let c=Object.entries(d).filter(([,g])=>g===0).map(([g])=>g),h=[...c];for(;c.length>0;){let g=c.pop(),b=p.get(g);for(let y of b.children.filter(i))--d[y.name]===0&&(h.push(y.name),c.push(y.name))}let m=h.map(g=>p.get(g)),f=Fj(m,l);return $j(f,l),f}function Fj(e,t){let n=new Map(e.map(s=>[s.name,s])),a=t.map(s=>s.name),r=new Set(a);for(;a.length>0;){let s=a.pop(),i=n.get(s);for(let o of i.children)!n.has(o.name)||r.has(o.name)||(r.add(o.name),a.push(o.name))}return e.filter(s=>r.has(s.name))}var Bh=class extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}};function $j(e,t){let n=new Map(e.map((o,l)=>[o.name,l])),a=new Set(t.map(o=>o.name)),r=o=>a.has(typeof o=="string"?o:o.name),s=new Set(e.map(o=>o.name)),i=o=>s.has(typeof o=="string"?o:o.name);for(let o of e){for(let l of o.children.filter(i)){if(!n.has(l.name))throw new Bh(`Child ${l.name} of node ${o.name} is unreachable.`);if(n.get(o.name)>n.get(l.name))throw new Bh(`Node ${o.name} is scheduled to run after its child ${l.name}.`)}if(!r(o))for(let l of o.inputs){if(!n.has(l.name))throw new Bh(`Input ${l.name} of node ${o.name} is unreachable.`);if(n.get(l.name)>n.get(o.name))throw new Bh(`Node ${o.name} is scheduled to run before its input ${l.name}.`)}}}function Dj(e){let t=new Map(e.map((o,l)=>[o.name,l])),n=Number.MAX_SAFE_INTEGER,a=e.map((o,l)=>Qs(o)?n:l),r=o=>{let l=a[t.get(o.name)];return l==null?-1:l},s=e.map((o,l)=>o.children.map(r).reduce((u,p)=>Math.max(u,p),a[l])),i=new Map;for(let o=0;o<e.length;++o){let l=s[o];if(l===n)continue;let u=e[o],p=e[l];i.has(p.name)||i.set(p.name,[]),i.get(p.name).push(u)}return i}var Rj=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),Mj=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),Pj=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Qs(e){return Rj.has(e.op)}function Oj(e){return Mj.has(e.op)}function Lj(e){return Pj.has(e.op)}var lv=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(e){let t=Object.keys(e).map(n=>e[n].map(a=>a.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new lv(e.functions[n],this)})}getCompilationKey(e,t){let n=e.map(r=>r.name).sort(),a=t.map(r=>r.name).sort();return n.join(this.SEPARATOR)+"--"+a.join(this.SEPARATOR)}compile(e,t){let n=rS(e,t,this.weightMap,this._initNodes),{missingInputs:a,dynamicNode:r,syncInputs:s}=n;if(r!=null)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(a.length>0){let l=t.map(p=>p.name),u=Object.keys(e);throw new Error(`Cannot compute the outputs [${l}] from the provided inputs [${u}]. Missing the following inputs: [${a}]`)}let i=Aj(this.graph,n),o=Dj(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(e==null)return null;let t=e.clone();return qt(t),t}cloneTensorList(e){return e?e.map(t=>this.cloneAndKeepTensor(t)):null}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,this.cloneTensorList(n)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let a=n.map(d=>this.graph.nodes[Zn(d)[0]]),r=t.map(d=>Zn(d)[0]),s=new Set(r),i=r.map(d=>this.graph.nodes[d]);i.length===0&&(i=this._outputs);let o=this.getCompilationKey(a,i),l=this.compiledMap.get(o);l==null&&(l=this.compile(e,i),this.compiledMap.set(o,l));try{this.keepIntermediateTensors=G().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}let u={},p={};return P(()=>{let d=new aS(this.weightMap,u,p,this.functionExecutorMap,this.parseNodeNameCache),c=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(g=>{let[b,y]=Zn(g,d),x=[];x[y]=e[g],c[b]=x,this.keepIntermediateTensors&&(this.clonedTensorsMap[b]=this.cloneTensorList(x))});let h=this.getFrozenTensorIds(c),{orderedNodes:m,nodeLiveUntilMap:f}=l;for(let g of m){if(c[g.name])continue;let b=nS(g,c,d,this._resourceManager);if(w.isPromise(b))throw new Error(`The execution of the op '${g.op}' returned a promise. Please use model.executeAsync() instead.`);c[g.name]=b,this.keepIntermediateTensors&&(this.clonedTensorsMap[g.name]=this.cloneTensorList(b)),this.checkTensorForDisposalWithNodeLiveUntilInfo(g,c,d,h,s,f.get(g.name))}return this.parent==null&&d.dispose(h),t.map(g=>dn(g,c,d))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(a=>a.id)));return new Set(t)}checkTensorForDisposal(e,t,n,a,r,s,i){if(!(Qs(t)||s.has(e))){for(let o of n[e])o!=null&&(i[o.id]=(i[o.id]||0)+t.children.length);for(let o of t.inputs){if(Qs(o))continue;let l=ZI(o.name,n,a);if(l!=null)for(let u of l){if(!u||u.kept||r.has(u.id))continue;let p=i[u.id];p===1?(u.dispose(),delete i[u.id]):p!=null&&i[u.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,a,r,s){function i(o){return Qs(o)||r.has(o.name)}if(!(Qs(e)||s==null))for(let o of s){if(i(o))continue;let l=ZI(o.name,t,n);for(let u of l)!u||u.kept||a.has(u.id)||u.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(e=>{for(let t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,a={},r={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=G().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}let s=new aS(this.weightMap,a,r,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));let i=await this.executeWithControlFlow(e,s,t,n),o=t.map(d=>dn(d,i,s)),l=o.map(d=>d.id),u=Object.keys(e).map(d=>e[d].id),p=new Set([...l,...u,...this.weightIds]);return Object.values(i).forEach(d=>{d.forEach(c=>{c&&!c.isDisposed&&!p.has(c.id)&&c.dispose()})}),this.parent==null&&s.dispose(p),o}async executeFunctionAsync(e,t,n){let a=e.reduce((r,s,i)=>(r[this.inputs[i].name]=s,r),{});return this._executeAsync(a,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,a){let r=Object.keys(e),s=r.map(x=>this.graph.nodes[Zn(x)[0]]),i=n.map(x=>Zn(x)[0]),o=new Set(i),l=i.map(x=>this.graph.nodes[x]);l.length===0&&(l=this._outputs);let{usedNodes:u,missingInputs:p,dynamicNode:d,syncInputs:c}=rS(e,l,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map(x=>({node:x,contexts:t.currentContext})),m=Object.assign({},this.weightMap);Object.keys(e).forEach(x=>{let[v,I]=Zn(x),T=[];T[I]=e[x],m[v]=T});let f={},g=this.getFrozenTensorIds(m),b={};for(;h.length>0;){let x=this.processStack(s,h,t,m,b,g,o,f,u);await Promise.all(x)}d==null&&!a&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=l.filter(x=>!Qs(x)&&!dn(x.name,m,t)).map(x=>x.name);if(y.length>0){let x="";throw d!=null&&(x=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${c}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${r}]. Consider providing the following inputs: [${p}]. ${x}`)}return m}processStack(e,t,n,a,r,s,i,o,l){let u=[];for(;t.length>0;){let p=t.pop();n.currentContext=p.contexts;let d="";if(p.node.op==="Enter"&&k("isConstant",p.node,a,n)&&([d]=Er(p.node.name,n)),a[p.node.name]==null){let c=nS(p.node,a,n,this._resourceManager);d||([d]=Er(p.node.name,n));let h=n.currentContext;w.isPromise(c)?u.push(c.then(m=>(a[d]=m,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(m)),n.currentContext=h,this.checkTensorForDisposal(d,p.node,a,n,s,i,o),this.processChildNodes(p.node,t,n,a,r,l),m))):(a[d]=c,this.keepIntermediateTensors&&(this.clonedTensorsMap[d]=this.cloneTensorList(c)),this.checkTensorForDisposal(d,p.node,a,n,s,i,o),this.processChildNodes(p.node,t,n,a,r,l))}else this.processChildNodes(p.node,t,n,a,r,l)}return u}processChildNodes(e,t,n,a,r,s){e.children.forEach(i=>{let[o]=Er(i.name,n);r[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!dn(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})):i.inputNames.every(l=>!!dn(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[a]=Zn(t),r=this.graph.nodes[a];if(r.attrParams.shape&&r.attrParams.shape.value){let s=r.attrParams.shape.value,i=s.length===n.shape.length&&n.shape.every((o,l)=>s[l]===-1||s[l]===o);w.assert(i,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${s}], but was [${n.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&w.assert(n.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){var t,n;let a={};for(let r in e){let s=(n=(t=this._signature)===null||t===void 0?void 0:t.inputs)===null||n===void 0?void 0:n[r];s!=null?a[s.name]=e[r]:a[r]=e[r]}return a}checkInputs(e){let t=Object.keys(e).filter(n=>{let[a]=Zn(n);return this.graph.nodes[a]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{var n,a;let r=(a=(n=this._signature)===null||n===void 0?void 0:n.outputs)===null||a===void 0?void 0:a[t];return r!=null?r.name:t},{})}checkOutputs(e){e.forEach(t=>{let[n]=Zn(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},zj=class{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(let e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(let e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}},Wj="?tfjs-format=file",Bj="model.json",$1=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(e,t={},n=jt){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,t==null&&(this.loadOptions={}),this.resourceManager=new zj}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{let t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[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 e=this.handler.load();return w.isPromise(e)?e.then(t=>this.loadSync(t)):this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let r=this.artifacts.userDefinedMetadata;r.signature!=null&&(n=r.signature),r.structuredOutputKeys!=null&&(this.structuredOutputKeys=r.structuredOutputKeys)}this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let a=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new lv(JI.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(a),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=JI.Instance.transformGraph(e.modelInitializer);this.initializer=new lv(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if(typeof e=="string"){let n=this.io.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){let t=e instanceof Te?[e]:e,n={};return t.forEach((a,r)=>n[this.structuredOutputKeys[r]]=a),n}return e}predict(e,t){let n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){let n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Te)&&!Array.isArray(e)){let r=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(r!=null)for(let s in r){let i=r[s];i.resourceId!=null&&(e[s]=this.resourceIdToCapturedInput[i.resourceId])}return e}e=Array.isArray(e)?e:[e];let n=Object.keys(this.resourceIdToCapturedInput).length;if(e.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 ${e.length} input tensors provided.`);let a=0;return this.inputNodes.reduce((r,s)=>{var i,o,l;let u=(l=(o=(i=this.signature)===null||i===void 0?void 0:i.inputs)===null||o===void 0?void 0:o[s])===null||l===void 0?void 0:l.resourceId;return u!=null?r[s]=this.resourceIdToCapturedInput[u]:r[s]=e[a++],r},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}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(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){let t=this.initializerSignature.outputs,n=Object.keys(t);for(let a=0;a<n.length;a++){let r=n[a],s=t[r];this.resourceIdToCapturedInput[s.resourceId]=e[a]}}}execute(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&_e(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}};async function Vj(e,t={},n=jt){if(e==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 e=="string"&&(e=Gj(e));let a=new $1(e,t,n);return await a.load(),a}function Uj(e){if(e==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){let[a,r]=e;if(!a)throw new Error("modelJSON must be the first element of the array");if(!r||!(r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in a))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in a))throw new Error("Model JSON is missing 'weightsManifest'");let s=jt.getWeightSpecs(a.weightsManifest),i=jt.getModelArtifactsForJSONSync(a,s,r);t=jt.fromMemorySync(i)}else if("load"in e)t=e;else if("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e)t=jt.fromMemorySync(e);else throw new Error("Unknown model format");let n=new $1(t);return n.load(),n}function Gj(e){return e.endsWith("/")||(e=e+"/"),`${e}${Bj}${Wj}`}var Hj="4.7.0",a_={};Ee(a_,{CSVDataset:()=>d_,Dataset:()=>yp,FileDataSource:()=>x_,TextLineDataset:()=>c_,URLDataSource:()=>v_,array:()=>m5,csv:()=>N5,func:()=>T5,generator:()=>C5,microphone:()=>E5,version_data:()=>A5,webcam:()=>_5,zip:()=>f5});var qj=ks(Dm()),jj=ks(Dm());function Kj(e,t){return Im(e,t)}function Im(e,t,n=new Map,a=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(a.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(au(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=Im(o,t,n,a);s[i]=l}return a.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function Xj(e,t=s_){return r_(e,t)}function r_(e,t,n=new Set){let a=e[0];if(n.has(a))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(au(a)){let s=Array.isArray(a)?[]:{};n.add(a);for(let i in a){let o=e.map(u=>u[i]),l=r_(o,t,n);s[i]=l}return n.delete(a),s}else throw new Error(`Can't recurse into non-iterable type: ${a}`);else return r.value}function s_(e){return e===null?null:au(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function i_(e,t){let n=new Map;Im(e,t,n);for(let a of Array.from(n.keys())){let r=n.get(a);if(w.isPromise(r)){let s=await r;n.set(a,s)}}return Im(e,t,n)}function au(e){let t=!1;if(G().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=US();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Te)&&!(e instanceof Promise)&&!t)}function Yj(e){return e==null||Zj(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Te||w.isTypedArray(e)}function Zj(e){return e===null||typeof e!="object"&&typeof e!="function"}function Jj(e){return Kj(e,Qj)}function Qj(e){return e instanceof Te?{value:e.clone(),recurse:!1}:au(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var o_=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}},D1=class extends o_{constructor(){super(D1.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let a=0;a<n;a++)t[a]=this.get(this.wrap(this.begin+a));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}};D1.INITIAL_CAPACITY=32;function l_(e){return new n5(e)}function R1(e){return new a5(e)}function e5(e,t){return new u_(e,t)}function t5(e,t=is.FAIL){return new d5(e,t)}var on=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new p5(this,e)}filter(e){return new l5(this,e)}map(e){return new u5(this,e)}mapAsync(e){return new sS(this,e)}serialMapAsync(e){return new sS(this,e).serial()}flatmap(e){return new c5(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new o5(this,e,t)}columnMajorBatch(e,t=!0,n=s_){return this.rowMajorBatch(e,t).map(a=>Xj(a,n))}concatenate(e,t){return new u_(l_([this,e]),t)}take(e){return e<0||e==null?this:new i5(this,e)}skip(e){return e<0||e==null?this:new s5(this,e)}prefetch(e){return new p_(this,e)}shuffle(e,t){return new h5(this,e,t)}serial(){return new r5(this)}},n5=class extends on{constructor(e){super(),this.items=e,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 e=this.items[this.trav];return this.trav++,{value:Jj(e),done:!1}}},a5=class extends on{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},r5=class extends on{constructor(e){super(),this.upstream=e,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()}},s5=class extends on{constructor(e,t){super(),this.upstream=e,this.maxCount=t,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 e=await this.upstream.next();if(e.done)return e;_e(e.value)}return this.upstream.next()}},i5=class extends on{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},o5=class extends on{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,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 e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},l5=class extends on{constructor(e,t){super(),this.upstream=e,this.predicate=t,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 e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;_e(e.value)}}},u5=class extends on{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=Ua.getTensorsInContainer(e.value),n=this.transform(e.value),a=Ua.getTensorsInContainer(n);for(let r of t)Ua.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},p5=class extends on{constructor(e,t){super(),this.upstream=e,this.handler=t,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(e){if(!this.handler(e))return{value:null,done:!0}}}},sS=class extends on{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=Ua.getTensorsInContainer(e.value),n=await this.transform(e.value),a=Ua.getTensorsInContainer(n);for(let r of t)Ua.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},M1=class extends on{constructor(){super(),this.outputQueue=new D1,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}}},c5=class extends M1{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=Ua.getTensorsInContainer(e.value),n=this.transform(e.value),a=Ua.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)Ua.isTensorInList(r,a)||r.dispose();return!0}},u_=class extends on{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,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 t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},is;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(is||(is={}));var d5=class extends on{constructor(e,t=is.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function a(s){return s instanceof on?{value:s.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await i_(this.iterators,a);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case is.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case is.SHORTEST:return{value:null,done:!0};case is.LONGEST:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},p_=class extends on{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new o_(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},h5=class extends p_{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=jj.alea(n||w.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},yp=class{constructor(){this.size=null}batch(e,t=!0){let n=this;w.assert(e>0,()=>`batchSize needs to be positive, but it is
      ${e}`);let a;return this.size===1/0||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),Yn(async()=>(await n.iterator()).columnMajorBatch(e,t,g5),a)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,Yn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,Yn(async()=>(await t.iterator()).filter(a=>P(()=>e(a))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Yn(async()=>(await t.iterator()).map(n=>P(()=>e(n))),this.size)}mapAsync(e){let t=this;return Yn(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return Yn(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,Yn(async()=>{let a=R1(async()=>({value:await t.iterator(),done:!1}));return e5(a.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,Yn(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<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 a=this,r=qj.alea(t||w.now().toString());return Yn(async()=>{let s=r.int32();return n&&(s+=r.int32()),(await a.iterator()).shuffle(e,s.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,Yn(async()=>(await t.iterator()).take(e),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()}};yp.MAX_BUFFER_SIZE=1e4;function Yn(e,t=null){return new class extends yp{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function m5(e){return Yn(async()=>l_(e),e.length)}function f5(e){if(!au(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(let n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return Yn(async()=>{let n=await i_(e,a=>{if(a instanceof yp)return{value:a.iterator(),recurse:!1};if(au(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return t5(n,is.SHORTEST)},t)}function g5(e){if(e===null)return null;let t=e[0];return Yj(t)?{value:b5(e),recurse:!1}:{value:null,recurse:!0}}function b5(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Te?Dt(e):bn(e)}var c_=class extends yp{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
`).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}},Vh='"',nc=Symbol("out"),iS=Symbol("field"),Uh=Symbol("quote"),Ix=Symbol("quoteafterquote"),oS=Symbol("quoteinquote"),d_=class extends yp{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.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 ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((a,r)=>(a[r]=a[r]+1||1,a),{}),n=Object.keys(t).filter(a=>t[a]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let a of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(a)===-1)throw new Error('The key "'+a+'" 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 t=e.value;return this.parseRow(t,!1)}else return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new c_(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},a={};for(let r=0;r<this.fullColumnNames.length;r++){let s=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[r],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);l=void 0}else{let u=Number(o);if(isNaN(u))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=u;else switch(i.dtype){case"float32":l=u;break;case"int32":l=Math.floor(u);break;case"bool":l=this.getBoolean(o);break;default:l=u}}i&&i.isLabel?a[s]=l:n[s]=l}}return Object.keys(a).length===0?n:{xs:n,ys:a}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],a=0,r=e.length,s=nc;for(let i=0;i<r;i++)switch(s){case nc:switch(e.charAt(i)){case Vh:a=i+1,s=Uh;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s=nc;break;default:s=iS,a=i;break}break;case iS:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s=nc,a=i+1;break;default:}break;case Uh:switch(e.charAt(i)){case Vh:s=Ix;break;default:}break;case Ix:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s=nc,a=i+1;break;case Vh:s=Uh;break;default:s=oS;break}break;case oS:switch(e.charAt(i)){case Vh:s=Uh;break;default:}break;default:}if(s===Ix?n.push(e.substring(a,r-1)):n.push(e.substring(a)),t&&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}},h_=class extends on{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))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=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.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(e={}){if(!G().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let t=new h_(e);return await t.start(),t}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 e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!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 t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.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 e,t,n=await this.getAudioData();if(this.includeSpectrogram){let a=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(a,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let a=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(a,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(a=>{let r=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&a({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),a({freqDataQueue:e,timeDataQueue:t}))},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(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((a,r)=>n.set(a,r*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(w.sizeFromShape(t));return n.set(e,n.length-e.length),bn(n,t)}},m_=class extends on{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=je([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,a=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,s=(1-a)/2,i=r+n,o=a+s;this.cropBox=$a([s,r,o,i],[1,4])}else this.cropBox=$a([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!G().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new m_(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&w.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(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Ko.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return P(()=>{let t=nn(se(e,"float32"),0),n;n=ea.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=n.shape;return W(n,a.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.")}},f_=class{},g_=class extends on{split(e){return new y5(this,e)}},y5=class extends g_{constructor(e,t){super(),this.upstream=e,this.impl=new x5(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},x5=class extends M1{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}},v5=class extends on{decodeUTF8(){return new w5(this)}},w5=class extends g_{constructor(e){super(),this.upstream=e,this.impl=new k5(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},k5=class extends M1{constructor(e){if(super(),this.upstream=e,G().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=US();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return G().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},b_=class extends v5{constructor(e,t={}){super(),this.file=e,this.options=t,w.assert(e instanceof Uint8Array||(G().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.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,t)=>{let n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{let a=new FileReader;a.onload=s=>{let i=a.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},a.onabort=s=>t(new Error("Aborted")),a.onerror=s=>t(new Error(s.type));let r=this.file.slice(this.offset,n);a.readAsArrayBuffer(r)}this.offset=n}),done:!1}}};async function I5(e,t={},n){let a,r;typeof e=="string"?a=e:(a=e.url,r=S5(e));let s=await(n||w.fetch)(a,r);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new b_(i,t)}else throw new Error(s.statusText)}var S5=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function y_(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var x_=class extends f_{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(y_(this.input)&&G().get("IS_NODE")){let e=Nv();this.input=e.readFileSync(this.input.slice(7))}return new b_(this.input,this.options)}},v_=class extends f_{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return y_(this.url)?new x_(this.url,this.fileOptions).iterator():I5(this.url,this.fileOptions)}};function N5(e,t={}){return new d_(new v_(e),t)}function T5(e){let t=R1(e);return Yn(async()=>t)}function C5(e){return Yn(async()=>{let t=await e();return R1(()=>t.next())})}async function _5(e,t){return m_.create(e,t)}async function E5(e){return h_.create(e)}var A5="4.7.0";function ge(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&w.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var F5=gr.whereImpl,Yf=class extends Mc{nextDataId(){return Yf.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Rm(this,Aa())}write(e,t,n){this.firstUse&&(this.firstUse=!1,G().get("IS_NODE")&&N.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 a={id:this.nextDataId()};return this.data.set(a,{values:e,dtype:n,refCount:1}),a}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let r=n.map(s=>w.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return{dataId:a,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,a,r){this.data.set(e,{values:t,dtype:a,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let a=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return N.mergeRealAndImagArrays(a,r)}return w.convertBackendValuesAndArrayBuffer(this.data.get(e).values,t)}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(a=>w.decodeString(a));return ze(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,t)}makeOutput(e,t,n){return Aa().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}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(e){ge([e],"where");let t=this.readSync(e.dataId);return F5(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Yf.nextDataId=0;var P1={};Ee(P1,{addImpl:()=>I_,bincountImpl:()=>L1,bincountReduceImpl:()=>S_,bitwiseAndImpl:()=>N_,castImpl:()=>k_,ceilImpl:()=>T_,concatImpl:()=>z1,equalImpl:()=>C_,expImpl:()=>E_,expm1Impl:()=>F_,floorDivImpl:()=>D_,floorImpl:()=>$_,gatherNdImpl:()=>R_,gatherV2Impl:()=>M_,greaterEqualImpl:()=>O_,greaterImpl:()=>P_,lessEqualImpl:()=>z_,lessImpl:()=>L_,linSpaceImpl:()=>W_,logImpl:()=>B_,maxImpl:()=>V_,maximumImpl:()=>U_,minimumImpl:()=>G_,multiplyImpl:()=>W1,negImpl:()=>H_,notEqualImpl:()=>q_,prodImpl:()=>j_,raggedGatherImpl:()=>K_,raggedRangeImpl:()=>X_,raggedTensorToTensorImpl:()=>Y_,rangeImpl:()=>V1,rsqrtImpl:()=>Z_,scatterImpl:()=>ai,sigmoidImpl:()=>EK,simpleAbsImpl:()=>w_,sliceImpl:()=>Nm,sparseFillEmptyRowsImpl:()=>Q_,sparseReshapeImpl:()=>eE,sparseSegmentReductionImpl:()=>U1,sqrtImpl:()=>$K,squaredDifferenceImpl:()=>tE,staticRegexReplaceImpl:()=>nE,stridedSliceImpl:()=>aE,stringNGramsImpl:()=>G1,stringSplitImpl:()=>H1,stringToHashBucketFastImpl:()=>q1,subImpl:()=>rE,tileImpl:()=>sE,topKImpl:()=>oE,transposeImpl:()=>B1,uniqueImpl:()=>K1});function w_(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var $5=e=>{let{x:t}=e.inputs,n=e.backend;ge(t,"abs");let a=new Float32Array(w.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=w_(r),n.makeOutput(a,t.shape,t.dtype)},D5={kernelName:lu,backendName:"cpu",kernelFunc:$5};function Ot(e){return(t,n,a,r,s)=>{let i=N.assertAndGetBroadcastShape(t,n),o=i.length,l=w.computeStrides(i),u=w.sizeFromShape(i),p=w.getTypedArrayFromDType(s,u),d=t.length,c=n.length,h=w.computeStrides(t),m=w.computeStrides(n),f=N.getBroadcastDims(t,i),g=N.getBroadcastDims(n,i);if(f.length+g.length===0)for(let b=0;b<p.length;++b)p[b]=e(a[b%a.length],r[b%r.length]);else for(let b=0;b<p.length;++b){let y=w.indexToLoc(b,o,l),x=y.slice(-d);f.forEach(C=>x[C]=0);let v=w.locToIndex(x,d,h),I=y.slice(-c);g.forEach(C=>I[C]=0);let T=w.locToIndex(I,c,m);p[b]=e(a[v],r[T])}return[p,i]}}function Jn(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(a.shape,"complex64"),l=n.data.get(o.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(a.shape,"float32",s),imag:n.makeTensorInfo(r.shape,"float32",i)},o}var R5={kernelName:Om,backendName:"cpu",kernelFunc:Jn};function Sm(e,t,n="float32"){if(n==="complex64"){let r=Sm(e,t,"float32"),s=Sm(e,t,"float32");return Jn({inputs:{real:r,imag:s},backend:e})}let a=w.makeZerosTypedArray(w.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function dr(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var M5={kernelName:to,backendName:"cpu",kernelFunc:dr};function xi(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.real,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}var P5={kernelName:Km,backendName:"cpu",kernelFunc:xi};function k_(e,t,n,a){if(a==="int32"){let r=Int32Array.from(e);return[t,"int32",r]}if(a==="bool"){let r=w.toTypedArray([0],n),[s,i]=Ot((o,l)=>o!==l?1:0)(t,[],e,r,"bool");return[i,"bool",s]}throw new Error(`Error in Cast: failed to cast ${n} to ${a}`)}function vs(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return dr({inputs:{x:r},backend:n});let p=Sm(n,r.shape,r.dtype),d=vs({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),c=Jn({inputs:{real:d,imag:p},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),c}if(r.dtype==="complex64"){let p=xi({inputs:{input:r},backend:n}),d=vs({inputs:{x:p},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(p),d}if(!w.hasEncodingLoss(r.dtype,s)){let p=dr({inputs:{x:r},backend:n});return{dataId:p.dataId,shape:p.shape,dtype:s}}let i=n.data.get(r.dataId).values,[o,l,u]=k_(i,r.shape,r.dtype,s);return n.makeTensorInfo(o,l,u)}var O5={kernelName:Pi,backendName:"cpu",kernelFunc:vs};function Jt(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;ge([i,o],e);let u=l.data.get(i.dataId).values,p=l.data.get(o.dataId).values,d=i.dtype==="string"?N.fromUint8ToStringArray(u):u,c=i.dtype==="string"?N.fromUint8ToStringArray(p):p,h=a||i.dtype,[m,f]=t(i.shape,o.shape,d,c,h);return l.makeTensorInfo(f,h,m)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=vs({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(u.dataId),d=p.complexTensorInfos.real,c=p.complexTensorInfos.imag,h=l.data.get(d.dataId).values,m=l.data.get(c.dataId).values,f=vs({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),b=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,x=l.data.get(b.dataId).values,v=l.data.get(y.dataId).values,[I,T,C]=n(i.shape,o.shape,h,m,x,v),E=l.makeTensorInfo(C,"float32",I),F=l.makeTensorInfo(C,"float32",T),D=Jn({inputs:{real:E,imag:F},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(F),D}else{let u=l.data.get(i.dataId).values,p=l.data.get(o.dataId).values,d=a||i.dtype,[c,h]=t(i.shape,o.shape,u,p,d);return l.makeTensorInfo(h,d,c)}}}function O1(e){return(t,n,a,r,s,i)=>{let o=N.assertAndGetBroadcastShape(t,n),l=w.sizeFromShape(o),u=o.length,p=w.computeStrides(o),d=w.getTypedArrayFromDType("float32",l),c=w.getTypedArrayFromDType("float32",l),h=N.getBroadcastDims(t,o),m=N.getBroadcastDims(n,o),f=N.mergeRealAndImagArrays(a,r),g=N.mergeRealAndImagArrays(s,i),b=t.length,y=w.computeStrides(t),x=n.length,v=w.computeStrides(n);if(h.length+m.length===0)for(let I=0;I<d.length;I++){let T=I%f.length,C=I%g.length,E=e(f[T*2],f[T*2+1],g[C*2],g[C*2+1]);d[I]=E.real,c[I]=E.imag}else for(let I=0;I<d.length;I++){let T=w.indexToLoc(I,u,p),C=T.slice(-b);h.forEach(S=>C[S]=0);let E=w.locToIndex(C,b,y),F=T.slice(-x);m.forEach(S=>F[S]=0);let D=w.locToIndex(F,x,v),$=e(f[E*2],f[E*2+1],g[D*2],g[D*2+1]);d[I]=$.real,c[I]=$.imag}return[d,c,o]}}var I_=Ot((e,t)=>e+t),L5=O1((e,t,n,a)=>({real:e+n,imag:t+a})),ru=Jt(Is,I_,L5),z5={kernelName:Is,backendName:"cpu",kernelFunc:ru};function L1(e,t,n,a,r){let s=w.sizeFromShape(a),i=w.makeZerosTypedArray(r,n);for(let o=0;o<e.length;o++){let l=e[o];if(l<0)throw new Error("Input x must be non-negative!");l>=r||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function S_(e,t,n,a=!1){let r=e.shape[0],s=e.shape[1],i=ze([r,n],t.dtype);for(let o=0;o<r;o++)for(let l=0;l<s;l++){let u=e.get(o,l);if(u<0)throw new Error("Input x must be non-negative!");u>=n||(a?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}var N_=Ot((e,t)=>e&t),W5=Jt(gu,N_),B5={kernelName:gu,backendName:"cpu",kernelFunc:W5};function yr(e){return(t,n,a)=>{let r=w.getArrayFromDType(n,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],a);return r}}function it(e,t,n){let a=yr(t);return Rs(e,a,n)}function Rs(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;ge(i,e);let o=s,l=o.data.get(i.dataId).values,u;if(i.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=N.fromUint8ToStringArray(l)}else u=l;let p=n||i.dtype,d=t(u,p,r);return o.makeTensorInfo(i.shape,p,d)}}var T_=yr(e=>Math.ceil(e)),V5=Rs(Oi,T_),U5={kernelName:Oi,backendName:"cpu",kernelFunc:V5};function z1(e,t,n,a){let r=w.getArrayFromDType(n,w.sizeFromShape(t));if(a&&n!=="string"){let s=0;e.forEach(i=>{let o=w.sizeFromShape(i.shape);r.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=n==="string"?N.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let p=u*t[1]+s;for(let d=0;d<i.shape[1];++d)r[p+d]=o[l++]}s+=i.shape[1]})}return r}var C_=Ot((e,t)=>e===t?1:0),__=Jt(Su,C_,null,"bool"),G5={kernelName:Su,backendName:"cpu",kernelFunc:__},E_=yr(e=>Math.exp(e)),A_=Rs(Xi,E_,"float32"),H5={kernelName:Xi,backendName:"cpu",kernelFunc:A_},F_=yr(e=>Math.expm1(e)),q5=Rs(Yi,F_),j5={kernelName:Yi,backendName:"cpu",kernelFunc:q5},$_=yr(e=>Math.floor(e)),K5=Rs(Zi,$_),X5={kernelName:Zi,backendName:"cpu",kernelFunc:K5},D_=Ot((e,t)=>Math.floor(e/t)),Y5=Jt(Ji,D_,null,"int32"),Z5={kernelName:Ji,backendName:"cpu",kernelFunc:Y5};function R_(e,t,n,a,r,s,i,o,l){let u=ze([a,s],n);for(let p=0;p<a;p++){let d=[],c=0;for(let h=0;h<r;h++){let m=e[p*r+h];c+=m*i[h],d.push(m)}if(c<0||c>=l/s)throw new Error(`Invalid indices: ${d} does not index into ${o}`);for(let h=0;h<s;h++)u.values[p*s+h]=t.get(...t.indexToLoc(c*s+h))}return u}function M_(e,t,n){let a=ze(n,e.dtype);for(let r=0;r<a.size;++r){let s=a.indexToLoc(r).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let u=e.locToIndex(s);0<=u&&u<e.values.length&&(a.values[r]=e.values[u])}return a}var P_=Ot((e,t)=>e>t?1:0),J5=Jt(Eu,P_,null,"bool"),Q5={kernelName:Eu,backendName:"cpu",kernelFunc:J5},O_=Ot((e,t)=>e>=t?1:0),eK=Jt(eo,O_,null,"bool"),tK={kernelName:eo,backendName:"cpu",kernelFunc:eK},L_=Ot((e,t)=>e<t?1:0),nK=Jt(Au,L_,null,"bool"),aK={kernelName:Au,backendName:"cpu",kernelFunc:nK},z_=Ot((e,t)=>e<=t?1:0),rK=Jt(Fu,z_,null,"bool"),sK={kernelName:Fu,backendName:"cpu",kernelFunc:rK};function W_(e,t,n){let a=(t-e)/(n-1),r=w.makeZerosTypedArray(n,"float32");r[0]=e;for(let s=1;s<r.length;s++)r[s]=r[s-1]+a;return r}var B_=yr(e=>Math.log(e)),iK=Rs(io,B_),oK={kernelName:io,backendName:"cpu",kernelFunc:iK};function V_(e,t,n,a){let r=w.getTypedArrayFromDType(a,w.sizeFromShape(n));for(let s=0;s<r.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let u=e[i+l];(Number.isNaN(u)||u>o)&&(o=u)}r[s]=o}return r}var U_=Ot((e,t)=>Math.max(e,t)),lK=Jt(po,U_),uK={kernelName:po,backendName:"cpu",kernelFunc:lK},G_=Ot((e,t)=>Math.min(e,t)),pK=Jt(fo,G_),cK={kernelName:fo,backendName:"cpu",kernelFunc:pK},W1=Ot((e,t)=>e*t),dK=O1((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),Zf=Jt(yo,W1,dK),hK={kernelName:yo,backendName:"cpu",kernelFunc:Zf};function H_(e,t,n){let a=w.createScalarValue(-1,n);return W1([],t,a,e,n)}function mK(e){let{inputs:t,backend:n}=e,{x:a}=t;ge(a,"neg");let r=n.data.get(a.dataId).values,[s,i]=H_(r,a.shape,a.dtype);return n.makeTensorInfo(i,a.dtype,s)}var fK={kernelName:zu,backendName:"cpu",kernelFunc:mK},q_=Ot((e,t)=>e!==t?1:0),gK=Jt(Wu,q_,null,"bool"),bK={kernelName:Wu,backendName:"cpu",kernelFunc:gK};function B1(e,t,n,a,r){let s=t.length,i=w.sizeFromShape(t),o=w.computeStrides(t),l=w.computeStrides(r),u=w.getTypedArrayFromDType(n,w.sizeFromShape(r));for(let p=0;p<i;++p){let d=w.indexToLoc(p,s,o),c=new Array(d.length);for(let m=0;m<c.length;m++)c[m]=d[a[m]];let h=w.locToIndex(c,s,l);u[h]=e[p]}return u}function Un(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{perm:s}=n;ge(r,"transpose");let i=r.shape.length,o=new Array(i);for(let p=0;p<o.length;p++)o[p]=r.shape[s[p]];let l=a.data.get(r.dataId).values,u=B1(l,r.shape,r.dtype,s,o);return{dataId:a.write(u,o,r.dtype),shape:o,dtype:r.dtype}}var yK={kernelName:$r,backendName:"cpu",kernelFunc:Un};function j_(e,t,n,a){let[r,s]=N.computeOutAndReduceShapes(e,a),i=ba(t,"int32"),o=w.makeZerosTypedArray(w.sizeFromShape(r),i),l=w.sizeFromShape(s);for(let u=0;u<o.length;++u){let p=u*l,d=1;for(let c=0;c<l;++c)d*=n[p+c];o[u]=d}return{outVals:o,outShape:r,outDtype:i}}function xK(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"prod");let o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=N.getAxesPermutation(l,o),p=l,d=r,c=[];u!=null&&(d=Un({inputs:{x:r},backend:n,attrs:{perm:u}}),c.push(d),p=N.getInnerMostAxes(p.length,o));let h=n.data.get(d.dataId).values,{outVals:m,outShape:f,outDtype:g}=j_(d.shape,d.dtype,h,p),b=f;return i&&(b=N.expandShapeToKeepDim(f,l)),c.forEach(y=>n.disposeIntermediateTensorInfo(y)),n.makeTensorInfo(b,g,m)}var vK={kernelName:Io,backendName:"cpu",kernelFunc:xK};function wK(e,t,n){e.forEach((a,r)=>{if(a<0||a>=n){let s=w.indexToLoc(r,t.length,w.computeStrides(t)).join(",");throw new Error(`indices[${s}] = ${a} is not in [0, ${n})`)}})}function kK(e,t){for(let n=0;n<e.length;++n){let a=e[n],r=n===e.length-1?t:e[n+1].length;if(a.length===0)throw new Error("Ragged splits may not be empty");if(a[0]<0)throw new Error("Ragged splits must be non-negative");if(a[a.length-1]>r)throw new Error("Ragged splits must not point past values");for(let s=1;s<a.length;++s)if(a[s-1]>a[s])throw new Error("Ragged splits must be sorted in ascending order")}}function IK(e,t,n,a){let r=[],s=0,i=t.length-1+n.length,o=new Array(i).fill(null).map(()=>[0]);kK(n,a);let l=1;for(let u=0;u<t.length-1;++u){l*=t[u];let p=t[u+1];for(let d=1;d<l+1;++d)o[u].push(d*p)}for(let u=0;u<e.length;++u){let p=e[u],d=e[u]+1;for(let c=0;c<n.length;++c){let h=n[c],m=c+t.length-1;if(m>=0){let f=o[m],g=f[f.length-1]-h[p];for(let b=p;b<d;++b)o[m].push(h[b+1]+g)}p=h[p],d=h[d]}d!==p&&(r.push([p,d]),s+=d-p)}return{outSplits:o,valueSlices:r,numValues:s}}function SK(e){let t=[];for(let n=0;n<e.length;++n){let a=e[n].length,r=w.getArrayFromDType("int32",a);t.push(r),e[n].forEach((s,i)=>r[i]=s)}return t}function lS(e,t){let n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let a=t;a<e.length;a++)n[t-1]*=e[a];return n}function NK(e,t,n,a,r,s){let i=lS(t,2)[1],o=lS(s,2)[1],l=0;for(let u of n)for(let p=u[0];p<u[1];++p){for(let d=0;d<a;++d)r[l*o+d]=e[p*i+d];++l}}function TK(e,t,n,a,r){let s=t.slice();s[0]=r;let i=w.getArrayFromDType(n,w.sizeFromShape(s)),o=e.length,l=o===0?0:o/t[0];return NK(e,t,a,l,i,s),[i,s]}function K_(e,t,n,a,r,s,i,o){if(e.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 l=t[0][0]-1;if(wK(s,i,l),a.length===0)throw new Error("params.rank must be nonzero");let u=a[0],{outSplits:p,valueSlices:d,numValues:c}=IK(s,i,e,u),h=SK(p),m=TK(n,a,r,d,c);return[h,m[0],m[1]]}var uS=2147483647;function X_(e,t,n,a,r,s,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(r.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 o=t.length===0,l=r.length===0,u=i.length===0,p=[];o||p.push(t[0]),l||p.push(r[0]),u||p.push(i[0]);for(let g=1;g<p.length;++g)if(p[g]!==p[g-1])throw new Error("starts, limits, and deltas must have the same shape");let d=p.length===0?1:p[0],c=w.getArrayFromDType("int32",d+1);c[0]=0;for(let g=0;g<d;++g){let b=o?e[0]:e[g],y=l?a[0]:a[g],x=u?s[0]:s[g];if(x===0)throw new Error("Requires delta != 0");let v;if(x>0&&y<b||x<0&&y>b)v=0;else if(v=Math.ceil(Math.abs((y-b)/x)),v>uS)throw new Error(`Requires ((limit - start) / delta) <= ${uS}`);c[g+1]=c[g]+v}let h=c[d],m=w.getArrayFromDType(n,h),f=0;for(let g=0;g<d;++g){let b=c[g+1]-c[g],y=o?e[0]:e[g],x=u?s[0]:s[g];for(let v=0;v<b;++v)m[f++]=y,y+=x}return[c,m]}var Ca=N.RowPartitionType,uv=class{constructor(e,t,n,a,r,s,i,o,l,u){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=a,this.valuesDType=r,this.defaultValue=s,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=N.getRowPartitionTypesHelper(u),this.raggedRank=N.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===Ca.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===Ca.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){let t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case Ca.VALUE_ROWIDS:return uv.getMaxWidthValueRowID(t);case Ca.ROW_SPLITS:return uv.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${Ca[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){let t=e.length;if(t===0||t===1)return 0;let n=0;for(let a=0;a<t-1;++a){let r=e[a+1]-e[a];r>n&&(n=r)}return n}static getMaxWidthValueRowID(e){let t=e.length;if(t===0)return 0;let n=0,a=e[0],r=0;for(let s=1;s<t;++s){let i=e[s];i!==a&&(a=i,r=Math.max(s-n,r),n=s)}return Math.max(t-n,r)}tensorShapeFromTensor(e,t,n=!0){if(t.length===0){if(e[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return cS(e,n)}calculateOutputSize(e){let t=this.valuesShape,n=this.defaultValueShape;N.validateDefaultValueShape(n,t);let a=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=N.combineRaggedTensorToTensorShapes(this.raggedRank,a,t);r[0]<0&&(r[0]=e);for(let s=1;s<=this.raggedRank;++s)r[s]<0&&(r[s]=this.getMaxWidth(s));return r}calculateFirstParentOutputIndex(e,t,n){let a=Math.min(e,n),r=[],s=0;for(let i=0;i<a;++i,s+=t)r.push(s);for(let i=a;i<e;++i)r.push(-1);return w.assert(r.length===e,()=>"Final length of result must be equal to firstDimension."),r}calculateOutputIndexRowSplit(e,t,n,a){let r=e.length,s=[];for(let i=0;i<r-1;++i){let o=e[i+1]-e[i],l=Math.min(a,o),u=t[i];u===-1&&(l=0);for(let p=0;p<l;++p)s.push(u),u+=n;for(let p=0;p<o-l;++p)s.push(-1)}if(r>0&&s.length!==e[r-1])throw new Error("Invalid row split size.");return s}calculateOutputIndexValueRowID(e,t,n,a){let r=e.length,s=[];if(r===0)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let l=t[o];s.push(l);for(let u=1;u<r;++u){let p=e[u];if(p===o)l>=0&&(++i,i<a?l+=n:l=-1);else{if(i=0,o=p,p>=t.length)throw new Error(`Got nextValueRowId=${p} which is not less than ${t.length}`);l=t[p]}s.push(l)}if(s.length!==e.length)throw new Error("Invalid row ids.");return s}calculateOutputIndex(e,t,n,a){let r=this.getRowPartitionTensor(e),s=this.getRowPartitionTypeByDimension(e);switch(s){case Ca.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,n,a);case Ca.ROW_SPLITS:if(r.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(r,t,n,a);default:throw new Error(`Unsupported partition type: ${Ca[s]}`)}}getFirstDimensionSize(){let e=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let t=this.rowPartitionTypes[0];switch(t){case Ca.FIRST_DIM_SIZE:return e[0];case Ca.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Ca.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Ca[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let s=n.length-2;s>=0;--s)n[s]=n[s+1]*t[s+1];let a=cS(t,!1),r=w.getArrayFromDType(this.valuesDType,w.sizeFromShape(a));if(n[0]*t[0]>0){let s=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let i=1;i<=this.raggedRank;++i)s=this.calculateOutputIndex(i-1,s,n[i],t[i]);this.setOutput(this.raggedRank,s,r,a)}return[a,r]}setOutput(e,t,n,a){if(n.length===0)return;let r=this.values,s=n,i=a.slice();i=i.slice(e+1);let o=w.sizeFromShape(i),l=t.length,u=this.defaultValue;if(u.length!==o&&u.length!==1){let h=this.defaultValueShape;P(()=>{let m=W(u,h);u=ri(m,i).dataSync()})}let p=0,d=0,c=0;for(let h=0;h<=l;++h){let m=h<l?t[h]:-1;if(m===c){++c;continue}if(d<c){let f=r.subarray(p*o),g=s.subarray(d*o),b=(c-d)*o;pS(g,f,b)}if(h>=l){let f=n.length;m=Math.floor(f/o)}if(m>c)if(this.defaultValue.length===1)s.subarray(c*o,m*o).fill(this.defaultValue[0]),c=m;else for(;m>c;){let f=s.slice(c*o);pS(f,u,o),++c}m<0?(p=h+1,d=c):(p=h,d=c,c=d+1)}}};function pS(e,t,n){for(let a=0;a<n;a++)e[a]=t[a]}function cS(e,t){let n=[];for(let a of e){if(a<0){if(!t)throw new Error(`Dimension ${a} must be >= 0`);if(a<-1)throw new Error(`Dimension ${a} must be >= -1`);a=-1}n.push(a)}return n}function Y_(e,t,n,a,r,s,i,o,l,u){return new uv(e,t,n,a,r,s,i,o,l,u).compute()}function V1(e,t,n,a){let r=e===t,s=e<t&&n<0,i=t<e&&n>1;if(r||s||i)return w.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/n)),l=w.makeZerosTypedArray(o,a);t<e&&n===1&&(n=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+n;return l}var Z_=yr(e=>1/Math.sqrt(e)),CK=Rs(Fo,Z_),_K={kernelName:Fo,backendName:"cpu",kernelFunc:CK};function ai(e,t,n,a,r,s,i,o,l,u){let p=[a/r,r],d=e.values,c=t.values;if(a===0)return ze(n,t.dtype);let h=l instanceof Vt?l:ze(p,t.dtype);typeof l=="string"||typeof l=="number"?h.values.fill(l):typeof l=="boolean"&&h.values.fill(+l);for(let m=0;m<s;m++){let f=[],g=0;for(let b=0;b<i;b++){let y=d[m*i+b];f.push(y),g+=y*o[b]}if(g<0||g>=a/r)throw new Error(`Invalid indices: ${f} does not index into ${n}`);for(let b=0;b<r;b++)u?h.values[g*r+b]+=c[m*r+b]:h.values[g*r+b]=t.rank===0?c[0]:c[m*r+b]}return h}var EK=yr(e=>1/(1+Math.exp(-e))),J_=it(Po,e=>1/(1+Math.exp(-e))),AK={kernelName:Po,backendName:"cpu",kernelFunc:J_};function Nm(e,t,n,a,r){let s=Xt.isSliceContinous(a,t,n),i=w.sizeFromShape(n),o=w.computeStrides(a);if(s){let d=Xt.computeFlatOffset(t,o);return r==="string"?e.slice(d,d+i):e.subarray(d,d+i)}let l=r==="string"?N.fromUint8ToStringArray(e):e,u=ze(a,r,l),p=ze(n,r);for(let d=0;d<p.size;++d){let c=p.indexToLoc(d),h=c.map((m,f)=>m+t[f]);p.set(u.get(...h),...c)}return r==="string"?N.fromStringArrayToUint8(p.values):p.values}function vi(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a;ge(r,"slice");let[o,l]=Xt.parseSliceParams(r,s,i);Xt.assertParamsValid(r,o,l);let u=n.data.get(r.dataId).values,p=Nm(u,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}var FK={kernelName:Qu,backendName:"cpu",kernelFunc:vi};function Q_(e,t,n,a,r,s,i){let o=t[0],l=s[0],u=new Array(l),p=new Array(o),d=t[1];if(l===0){if(o!==0)throw new Error(N.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=w.getArrayFromDType(n,0),b=w.getArrayFromDType(r,0);return[g,[0,d],b,u,p]}let c=!0,h=0,m=new Array(l).fill(0);for(let g=0;g<o;++g){let b=e[g*d];if(b<0)throw new Error(N.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,b));if(b>=l)throw new Error(N.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,b,l));++m[b],c=c&&b>=h,h=b}let f=!0;for(let g=0;g<l;++g){let b=m[g]===0;u[g]=b,f=f&&!b,m[g]=Math.max(m[g],1),g>0&&(m[g]+=m[g-1])}if(f&&c){let g=e,b=a;for(let y=0;y<o;++y)p[y]=y;return[g,[o,d],b,u,p]}else{let g=m[l-1],b=w.getArrayFromDType(n,g*d),y=w.getArrayFromDType(r,g),x=new Array(l).fill(0);for(let v=0;v<o;++v){let I=e[v*d],T=x[I],C=(I===0?0:m[I-1])+T;x[I]++;for(let E=0;E<d;++E)b[C*d+E]=e[v*d+E];y[C]=a[v],p[v]=C}for(let v=0;v<l;++v)if(x[v]===0){let I=v===0?0:m[v-1];b[I*d+0]=v;for(let T=1;T<d;++T)b[I*d+T]=0;y[I]=i}return[b,[g,d],y,u,p]}}function eE(e,t,n,a,r){let s=w.sizeFromShape(a),i=t[0],o=r.length,l=[],u=1,p=-1;for(let f=0;f<o;++f){let g=r[f];if(g===-1){if(p!==-1)throw new Error(N.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(p,f));p=f,l.push(1)}else{if(g<0)throw new Error(N.getSparseReshapeNegativeOutputDimErrorMessage(f,g));u*=g,l.push(g)}}if(p!==-1){if(u<=0)throw new Error(N.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let f=Math.trunc(s/u);if(u*f!==s)throw new Error(N.getSparseReshapeInputOutputMultipleErrorMessage(a,l));l[p]=f}if(w.sizeFromShape(l)!==s)throw new Error(N.getSparseReshapeInputOutputMismatchErrorMessage(a,l));let d=a.length,c=[];if(d>0){c[d-1]=1;for(let f=d-2;f>=0;--f)c[f]=c[f+1]*a[f+1]}let h=[];if(o>0){h[o-1]=1;for(let f=o-2;f>=0;--f)h[f]=h[f+1]*l[f+1]}let m=w.getArrayFromDType(n,i*o);for(let f=0;f<i;++f){let g=0;for(let b=0;b<d;++b)g+=e[f*d+b]*c[b];for(let b=0;b<o;++b)m[f*o+b]=Math.trunc(g/h[b]),g%=h[b]}return[m,[i,o],l]}function U1(e,t,n,a,r,s=!1,i=0){let o=a.length,l=[t[0],e.length/t[0]],u=l[1],p=o>0?r[o-1]+1:0;if(p<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=t.slice();d[0]=p;let c=d.reduce((y,x)=>y*x,1),h=w.getArrayFromDType(n,c);if(o===0)return p>0&&h.fill(i),[h,d];if(p<=0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,f=1,g=0,b=r[m];for(;;){let y=0;if(f<o){if(y=r[f],b===y){++f;continue}if(b>=y)throw new Error(N.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(b<0||b>=p)throw new Error(N.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(b,p));b>g&&h.fill(i,g*u,b*u);for(let x=m;x<f;++x){let v=a[x];if(v<0||v>=l[0])throw new Error(N.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x,a[x],l[0]));for(let I=0;I<u;I++)h[b*u+I]+=e[v*u+I]}if(s)for(let x=0;x<u;x++)h[b*u+x]/=f-m;if(m=f,++f,g=b+1,b=y,f>o)break}return g<p&&h.fill(i,g*u,p*u),[h,d]}var $K=yr(e=>Math.sqrt(e)),DK=it(Lo,e=>Math.sqrt(e)),RK={kernelName:Lo,backendName:"cpu",kernelFunc:DK},tE=Ot((e,t)=>{let n=e-t;return n*n}),MK=Jt(Bo,tE),PK={kernelName:Bo,backendName:"cpu",kernelFunc:MK},nE=yr((e,t)=>{let{pattern:n,replaceGlobal:a,rewrite:r}=t;return e.replace(new RegExp(n,a?"g":""),r)}),OK=Rs(Jc,nE),LK={kernelName:Jc,backendName:"cpu",kernelFunc:OK};function aE(e,t,n,a){let r=ze(e,t.dtype);for(let s=0;s<r.size;s++){let i=r.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*n[l]+a[l];r.set(t.get(...o),...i)}return r}var zK=class{constructor(e,t,n,a,r,s){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(n),this.rightPad=w.encodeString(a),this.padWidth=r,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,a,r,s){for(let i=0;i<r;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),u=Math.max(0,o-(r-(i+1))),p=s-(l+u),d=t+(l>0?0:i-o),c=0;c+=l*this.leftPad.length;for(let b=0;b<p;++b)c+=e[d+b].length;c+=u*this.rightPad.length;let h=l+u+p-1;c+=h*this.separator.length,n[a+i]=new Uint8Array(c);let m=n[a+i],f=0,g=b=>b.forEach(y=>m[f++]=y);for(let b=0;b<l;++b)g(this.leftPad),g(this.separator);for(let b=0;b<p-1;++b)g(e[d+b]),g(this.separator);if(p>0){g(e[d+p-1]);for(let b=0;b<u;++b)g(this.separator),g(this.rightPad)}else{for(let b=0;b<u-1;++b)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,a=t.length;if(a>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<a;++l){let u=t[l]>=o;if(u=u&&t[l]<=n,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${n}]`);o=t[l]}if(o!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${o}`)}let r=a-1,s=w.getArrayFromDType("int32",a);if(n===0||a===0){let o=new Array(n);for(let l=0;l<=r;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=r;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(p=>{u+=this.getNumNGrams(l,p)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[r]);for(let o=0;o<r;++o){let l=t[o],u=s[o];if(this.nGramWidths.forEach(p=>{let d=t[o+1]-t[o],c=this.getNumNGrams(d,p);this.createNGrams(e,l,i,u,c,p),u+=c}),this.preserveShort&&u===s[o]){let p=t[o+1]-t[o];if(p===0)continue;let d=p+2*this.padWidth,c=1;this.createNGrams(e,l,i,u,c,d)}}return[i,s]}};function G1(e,t,n,a,r,s,i,o){return new zK(n,a,r,s,i,o).compute(e,t)}function WK(e,t,n,a){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)a.push(e.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=e.indexOf(s);for(;i!==-1;){let o=e.subarray(0,i);(!n||o.length!==0)&&a.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!n||e.length!==0)&&a.push(e);return}let r=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(r,s);(!n||i.length!==0)&&a.push(i),r=s+1}}function H1(e,t,n){let a=e.length,r=[],s=0,i=0,o=new Array(a);for(let c=0;c<a;++c){let h=r.length;WK(e[c],t,n,r);let m=r.length-h;o[c]=m,s+=m,i=Math.max(i,m)}let l=w.getArrayFromDType("int32",s*2),u=new Array(s),p=[a,i],d=0;for(let c=0;c<a;++c)for(let h=0;h<o[c];++h)l[d*2]=c,l[d*2+1]=h,u[d]=r[d],++d;return[l,u,p]}function q1(e,t){let n=w.getArrayFromDType("int32",e.length);for(let a=0;a<e.length;++a)n[a]=w.fingerPrint64(e[a]).modulo(t).getLowBitsUnsigned();return n}var rE=Ot((e,t)=>e-t),BK=O1((e,t,n,a)=>({real:e-n,imag:t-a})),j1=Jt(Vo,rE,BK),VK={kernelName:Vo,backendName:"cpu",kernelFunc:j1};function sE(e,t){let n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];let a=ze(n,e.dtype);for(let r=0;r<a.values.length;++r){let s=a.indexToLoc(r),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);a.values[r]=e.values[o]}return a}var ic=(e,t)=>{let n=t.value-e.value;return n===0?e.index-t.index:n};function iE(e,t,n=0,a=e.length-1){for(;a>n;){if(a-n>600){let o=a-n+1,l=t-n+1,u=Math.log(o),p=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*p*(o-p)/o)*Math.sign(l-o/2),c=Math.max(n,Math.floor(t-l*p/o+d)),h=Math.min(a,Math.floor(t+(o-l)*p/o+d));iE(e,t,c,h)}let r=e[t],s=n,i=a;for(w.swap(e,n,t),ic(e[a],r)>0&&w.swap(e,n,a);s<i;){for(w.swap(e,s,i),s++,i--;ic(e[s],r)<0;)s=s+1;for(;ic(e[i],r)>0;)i=i-1}ic(e[n],r)===0?w.swap(e,n,i):(i=i+1,w.swap(e,i,a)),i<=t&&(n=i+1),t<=i&&(a=i-1)}}function oE(e,t,n,a,r){let s=t[t.length-1],[i,o]=[e.length/s,s],l=w.getTypedArrayFromDType(n,i*a),u=w.getTypedArrayFromDType("int32",i*a);for(let d=0;d<i;d++){let c=d*o,h=e.subarray(c,c+o),m=new Array(h.length);h.forEach((y,x)=>m[x]={value:y,index:x}),a<m.length&&(iE(m,a),m=m.slice(0,a)),r&&m.sort(ic);let f=d*a,g=l.subarray(f,f+a),b=u.subarray(f,f+a);for(let y=0;y<a;y++)g[y]=m[y].value,b[y]=m[y].index}let p=t.slice();return p[p.length-1]=a,[ze(p,n,l),ze(p,"int32",u)]}function K1(e,t,n,a){let r=w.parseAxisParam(t,n)[0],s=[1,n[0],1];for(let m=0;m<r;m++)s[0]*=n[m];s[1]=n[r];for(let m=r+1;m<n.length;m++)s[2]*=n[m];let i=new Map,o=new Int32Array(n[r]),l=new Vt(s,a,e),u=[],p=s[0]===1&&s[2]===1;for(let m=0;m<n[r];m++){let f;if(p)f=e[m].toString();else{let b=[];for(let y=0;y<s[0];y++)for(let x=0;x<s[2];x++)b.push(l.get(y,m,x));f=b.join(",")}let g=i.get(f);if(g!=null)o[m]=g;else{let b=i.size;i.set(f,b),o[m]=b,u.push(m)}}let d=s.slice();d[1]=i.size;let c=new Vt(d,a);u.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let b=0;b<s[2];b++)c.set(l.get(g,m,b),g,f,b)});let h=n.slice();return h[r]=d[1],{outputValues:c.values,outputShape:h,indices:o}}var UK="4.7.0";Zm("cpu",()=>new Yf,1);var lE=it(ji,e=>e>=0?e:Math.exp(e)-1),GK={kernelName:ji,backendName:"cpu",kernelFunc:lE};function uE(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a;ge([r],"leakyRelu");let i=w.sizeFromShape(r.shape),o=n.data.get(r.dataId).values,l=w.getTypedArrayFromDType("float32",i);for(let u=0;u<o.length;u++)l[u]=o[u]<0?s*o[u]:o[u];return n.makeTensorInfo(r.shape,"float32",l)}var HK={kernelName:so,backendName:"cpu",kernelFunc:uE},qK=Ot((e,t)=>e<0?t*e:e);function pE(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t;ge([a,r],"prelu");let s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,[o,l]=qK(a.shape,r.shape,s,i,"float32");return n.makeTensorInfo(l,"float32",o)}var jK={kernelName:ko,backendName:"cpu",kernelFunc:pE},cE=it(No,e=>Math.max(0,e)),KK={kernelName:No,backendName:"cpu",kernelFunc:cE},dE=it(_o,e=>Math.min(Math.max(0,e),6)),XK={kernelName:_o,backendName:"cpu",kernelFunc:dE};function Tm(e,t,n,a,r){if(n==="linear")return dr({inputs:{x:t},backend:e});if(n==="relu")return cE({inputs:{x:t},backend:e});if(n==="elu")return lE({inputs:{x:t},backend:e});if(n==="relu6")return dE({inputs:{x:t},backend:e});if(n==="prelu")return pE({inputs:{x:t,alpha:a},backend:e});if(n==="leakyrelu")return uE({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return J_({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function xt(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=w.sizeFromShape(r.shape),o=w.inferFromImplicitShape(s,i),l=w.sizeFromShape(o);w.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let u=n.data.get(r.dataId);if(u.complexTensorInfos!=null){let p=u.complexTensorInfos.real,d=u.complexTensorInfos.imag;p.shape=o,d.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}var YK={kernelName:qu,backendName:"cpu",kernelFunc:xt};function hE(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;ge([r,s],"matMul");let l=r.shape.length,u=s.shape.length,p=i?r.shape[l-2]:r.shape[l-1],d=o?s.shape[u-1]:s.shape[u-2],c=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=w.sizeFromShape(m),b=w.sizeFromShape(f),y=pp.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([c,h]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,p,c]:[g,c,p],v=o?[b,h,d]:[b,d,h],I=xt({inputs:{x:r},backend:n,attrs:{shape:x}}),T=xt({inputs:{x:s},backend:n,attrs:{shape:v}}),C=i?I.shape[1]:I.shape[2],E=i?I.shape[2]:I.shape[1],F=o?T.shape[1]:T.shape[2],D=Math.max(g,b),$=n.data.get(I.dataId).values,S=n.data.get(T.dataId).values,M=w.computeStrides(I.shape),B=w.computeStrides(T.shape),[U,H,j]=i?[M[0],1,M[1]]:[M[0],M[1],1],[K,Z,J]=o?[1,B[1],B[0]]:[B[1],1,B[0]],ee=E*F,ae=ze([D,E,F],I.dtype),te=ae.values,re=n.blockSize;for(let ie=0;ie<D;ie++){let ye=ie%g,ue=ie%b;for(let be=0;be<E;be+=re){let ke=Math.min(be+re,E);for(let Se=0;Se<F;Se+=re){let We=Math.min(Se+re,F);for(let Ge=0;Ge<C;Ge+=re){let ht=Math.min(Ge+re,C);for(let st=be;st<ke;st++)for(let at=Se;at<We;at++){let rt=0;for(let Me=Ge;Me<ht;Me++){let ft=$[ye*U+st*H+Me*j],jn=S[Me*K+at*Z+ue*J];rt+=ft*jn}te[ie*ee+(st*F+at)]+=rt}}}}}return n.disposeIntermediateTensorInfo(I),n.disposeIntermediateTensorInfo(T),n.makeTensorInfo(y,ae.dtype,ae.values)}var ZK={kernelName:Mi,backendName:"cpu",kernelFunc:hE};function JK(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a,c,h,m,f=[];c=hE({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:u},backend:n}),i&&(h=ru({inputs:{a:c,b:i},backend:n}),f.push(c),c=h),p&&(m=Tm(n,c,p,o,d),f.push(c),c=m);for(let g of f)n.disposeIntermediateTensorInfo(g);return c}var QK={kernelName:oi,backendName:"cpu",kernelFunc:JK},e8=it(Ti,e=>Math.acos(e)),t8={kernelName:Ti,backendName:"cpu",kernelFunc:e8},n8=it(Ci,e=>Math.acosh(e)),a8={kernelName:Ci,backendName:"cpu",kernelFunc:n8};function r8(e){let{inputs:t,backend:n}=e,a=t;ge(t,"addN");let r=a.map(o=>n.data.get(o.dataId).values),s=ze(a[0].shape,a[0].dtype),i=s.values;for(let o=0;o<a.length;o++){let l=r[o];for(let u=0;u<i.length;u++)i[u]+=l[u]}return n.makeTensorInfo(s.shape,s.dtype,s.values)}var s8={kernelName:_i,backendName:"cpu",kernelFunc:r8};function i8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"all");let o=w.parseAxisParam(s,r.shape),l=o,u=N.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=Un({inputs:{x:r},backend:n,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,r.shape.length)),N.assertAxesAreInnerMostDims("all",l,p.shape.length);let[d,c]=N.computeOutAndReduceShapes(p.shape,l),h=w.sizeFromShape(c),m=w.makeZerosTypedArray(w.sizeFromShape(d),p.dtype),f=n.data.get(p.dataId).values;for(let b=0;b<m.length;++b){let y=b*h,x=f[y];for(let v=0;v<h;++v){let I=f[y+v];x=x&&I}m[b]=x}u!=null&&n.disposeIntermediateTensorInfo(p);let g=n.makeTensorInfo(d,p.dtype,m);if(i){let b=N.expandShapeToKeepDim(d,o),y=xt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var o8={kernelName:uu,backendName:"cpu",kernelFunc:i8};function l8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"any");let o=w.parseAxisParam(s,r.shape),l=o,u=N.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=Un({inputs:{x:r},backend:n,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,r.shape.length)),N.assertAxesAreInnerMostDims("any",l,p.shape.length);let[d,c]=N.computeOutAndReduceShapes(p.shape,l),h=w.sizeFromShape(c),m=w.makeZerosTypedArray(w.sizeFromShape(d),p.dtype),f=n.data.get(p.dataId).values;for(let b=0;b<m.length;++b){let y=b*h,x=f[y];for(let v=0;v<h;++v){let I=f[y+v];x=x||I}m[b]=x}u!=null&&n.disposeIntermediateTensorInfo(p);let g=n.makeTensorInfo(d,p.dtype,m);if(i){let b=N.expandShapeToKeepDim(d,o),y=xt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var u8={kernelName:pu,backendName:"cpu",kernelFunc:l8};function p8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;ge(r,"argMax");let i=w.parseAxisParam(s,r.shape),o=N.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Un({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],N.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[p,d]=N.computeOutAndReduceShapes(l.shape,i),c=w.sizeFromShape(p),h=w.makeZerosTypedArray(c,"int32"),m=w.sizeFromShape(d),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let b=g*m,y=f[b],x=0;for(let v=0;v<m;++v){let I=f[b+v];I>y&&(y=I,x=v)}h[g]=x}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(p,"int32",h)}var c8={kernelName:cu,backendName:"cpu",kernelFunc:p8};function d8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;ge(r,"argMin");let i=w.parseAxisParam(s,r.shape),o=N.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Un({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],N.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[p,d]=N.computeOutAndReduceShapes(l.shape,i),c=w.sizeFromShape(p),h=w.makeZerosTypedArray(c,"int32"),m=w.sizeFromShape(d),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let b=g*m,y=f[b],x=0;for(let v=0;v<m;++v){let I=f[b+v];I<y&&(y=I,x=v)}h[g]=x}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(p,"int32",h)}var h8={kernelName:du,backendName:"cpu",kernelFunc:d8},m8=it(Ei,e=>Math.asin(e)),f8={kernelName:Ei,backendName:"cpu",kernelFunc:m8},g8=it(Ai,e=>Math.asinh(e)),b8={kernelName:Ai,backendName:"cpu",kernelFunc:g8},y8=it(Fi,e=>Math.atan(e)),x8={kernelName:Fi,backendName:"cpu",kernelFunc:y8},v8=Ot((e,t)=>Math.atan2(e,t)),w8=Jt(Di,v8),k8={kernelName:Di,backendName:"cpu",kernelFunc:w8},I8=it($i,e=>Math.atanh(e)),S8={kernelName:$i,backendName:"cpu",kernelFunc:I8};function X1(e,t,n,a,r,s){let i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,p=r.effectiveFilterHeight,d=r.effectiveFilterWidth,c=r.padInfo.top,h=r.padInfo.left,m=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=ze(r.outShape,n),g=f.values,b=r.outShape[1]*r.outShape[2]*r.outShape[3],y=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let v=0;v<r.batchSize;++v){let I=v*b,T=v*a[0];for(let C=0;C<r.inChannels;++C)for(let E=0;E<r.outHeight;++E){let F=E*i-c,D=Math.max(0,F),$=Math.min(r.inHeight,p+F),S=I+E*y;for(let M=0;M<r.outWidth;++M){let B=M*o-h,U=Math.max(0,B),H=Math.min(r.inWidth,d+B),j=m,K=0,Z=0;for(let ee=D;ee<$;ee+=l){let ae=T+ee*a[1];for(let te=U;te<H;te+=u){let re=ae+te*a[2],ie=e[re+C];s==="max"&&ie>j?j=ie:s==="avg"&&(K+=ie,Z++)}if(isNaN(j))break}let J=S+M*x+C;g[J]=s==="avg"?K/Z:j}}}return f}function mE(e,t,n,a,r=!1,s=!1){let i=ze(a.outShape,"int32"),o=a.strideHeight,l=a.strideWidth,u=a.dilationHeight,p=a.dilationWidth,d=a.effectiveFilterHeight,c=a.effectiveFilterWidth,h=a.padInfo.top,m=a.padInfo.left,f=ze(t,n,e);for(let g=0;g<a.batchSize;++g)for(let b=0;b<a.inChannels;++b)for(let y=0;y<a.outHeight;++y){let x=y*o-h,v=x;for(;v<0;)v+=u;let I=Math.min(a.inHeight,d+x);for(let T=0;T<a.outWidth;++T){let C=T*l-m,E=C;for(;E<0;)E+=p;let F=Math.min(a.inWidth,c+C),D=Number.NEGATIVE_INFINITY,$=-1;for(let S=v;S<I;S+=u){let M=S-x;for(let B=E;B<F;B+=p){let U=B-C,H=f.get(g,S,B,b);H>D&&(D=H,r?$=s?((g*a.inHeight+S)*a.inWidth+B)*a.inChannels+b:(S*a.inWidth+B)*a.inChannels+b:$=M*c+U)}}i.set($,g,y,T,b)}}return i}function fE(e,t,n,a,r,s){let i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,p=r.dilationHeight,d=r.dilationWidth,c=r.effectiveFilterDepth,h=r.effectiveFilterHeight,m=r.effectiveFilterWidth,f=r.padInfo.front,g=r.padInfo.top,b=r.padInfo.left,y=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=ze(r.outShape,n),v=x.values,I=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],T=r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[3]*r.outShape[4],E=r.outShape[4];for(let F=0;F<r.batchSize;++F){let D=F*I,$=F*a[0];for(let S=0;S<r.inChannels;++S)for(let M=0;M<r.outDepth;++M){let B=M*i-f,U=B;for(;U<0;)U+=u;let H=Math.min(r.inDepth,c+B),j=D+M*T;for(let K=0;K<r.outHeight;++K){let Z=K*o-g,J=Z;for(;J<0;)J+=p;let ee=Math.min(r.inHeight,h+Z),ae=j+K*C;for(let te=0;te<r.outWidth;++te){let re=te*l-b,ie=re;for(;ie<0;)ie+=d;let ye=Math.min(r.inWidth,m+re),ue=ae+te*E,be=y,ke=0,Se=0;for(let Ge=U;Ge<H;Ge+=u){let ht=$+Ge*a[1];for(let st=J;st<ee;st+=p){let at=ht+st*a[2];for(let rt=ie;rt<ye;rt+=d){let Me=at+rt*a[3],ft=e[Me+S];if(s==="max"&&ft>be?be=ft:s==="avg"&&(ke+=ft,Se++),isNaN(be))break}if(isNaN(be))break}if(isNaN(be))break}let We=ue+S;v[We]=s==="avg"?ke/Math.max(Se,1):be}}}}return x}function N8(e,t){let n=ze(t.outShape,"int32"),a=t.strideDepth,r=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,p=t.effectiveFilterHeight,d=t.effectiveFilterWidth,c=t.padInfo.front,h=t.padInfo.top,m=t.padInfo.left;for(let f=0;f<t.batchSize;++f)for(let g=0;g<t.inChannels;++g)for(let b=0;b<t.outDepth;++b){let y=b*a-c,x=y;for(;x<0;)x+=i;let v=Math.min(t.inDepth,u+y);for(let I=0;I<t.outHeight;++I){let T=I*r-h,C=T;for(;C<0;)C+=o;let E=Math.min(t.inHeight,p+T);for(let F=0;F<t.outWidth;++F){let D=F*s-m,$=D;for(;$<0;)$+=l;let S=Math.min(t.inWidth,d+D),M=Number.NEGATIVE_INFINITY,B=-1;for(let U=x;U<v;U+=i){let H=U-y;for(let j=C;j<E;j+=o){let K=j-T;for(let Z=$;Z<S;Z+=l){let J=Z-D,ee=e.get(f,U,j,Z,g);ee>=M&&(M=ee,B=H*p*d+K*p+J)}}}n.set(B,f,b,I,F,g)}}}return n}function T8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;ge(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=N.computePool2DInfo(r.shape,s,i,u,o,l),d;if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))d=dr({inputs:{x:r},backend:n});else{let c=n.data.get(r.dataId).values,h=w.computeStrides(r.shape),m=X1(c,r.shape,r.dtype,h,p,"avg");d=n.makeTensorInfo(p.outShape,r.dtype,m.values)}return d}var C8={kernelName:Ri,backendName:"cpu",kernelFunc:T8};function _8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a;ge(r,"avgPool3d");let p=N.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.data.get(r.dataId).values,c=fE(d,r.shape,r.dtype,w.computeStrides(r.shape),p,"avg");return n.makeTensorInfo(c.shape,"float32",c.values)}var E8={kernelName:hu,backendName:"cpu",kernelFunc:_8};function A8(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a;ge([r,s],"avgPool3DGrad");let p=N.computePool3DInfo(s.shape,i,o,1,l,u),d=p.strideDepth,c=p.strideHeight,h=p.strideWidth,m=p.filterDepth,f=p.filterHeight,g=p.filterWidth,b=p.dilationDepth,y=p.dilationHeight,x=p.dilationWidth,v=p.effectiveFilterDepth,I=p.effectiveFilterHeight,T=p.effectiveFilterWidth,C=v-1-p.padInfo.front,E=T-1-p.padInfo.left,F=I-1-p.padInfo.top,D=ze(s.shape,"float32"),$=1/(m*f*g),S=n.bufferSync(r);for(let M=0;M<p.batchSize;++M)for(let B=0;B<p.inChannels;++B)for(let U=0;U<p.inDepth;++U)for(let H=0;H<p.inHeight;++H)for(let j=0;j<p.inWidth;++j){let K=U-C,Z=H-F,J=j-E,ee=0;for(let ae=0;ae<v;ae+=b){let te=(K+ae)/d;if(!(te<0||te>=p.outDepth||Math.floor(te)!==te))for(let re=0;re<I;re+=y){let ie=(Z+re)/c;if(!(ie<0||ie>=p.outHeight||Math.floor(ie)!==ie))for(let ye=0;ye<T;ye+=x){let ue=(J+ye)/h;if(ue<0||ue>=p.outWidth||Math.floor(ue)!==ue)continue;let be=S.get(M,te,ie,ue,B);ee+=be}}}D.set(ee*$,M,U,H,j,B)}return n.makeTensorInfo(D.shape,D.dtype,D.values)}var F8={kernelName:Lc,backendName:"cpu",kernelFunc:A8};function $8(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;ge([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,p=N.computePool2DInfo(i.shape,o,l,1,u),d=p.strideHeight,c=p.strideWidth,h=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,b=p.effectiveFilterHeight,y=p.effectiveFilterWidth,x=y-1-p.padInfo.left,v=b-1-p.padInfo.top,I=ze(i.shape,"float32"),T=1/(h*m),C=n.data.get(r.dataId).values,E=ze(r.shape,"float32",C);for(let F=0;F<p.batchSize;++F)for(let D=0;D<p.inChannels;++D)for(let $=0;$<p.inHeight;++$)for(let S=0;S<p.inWidth;++S){let M=$-v,B=S-x,U=0;for(let H=0;H<b;H+=f){let j=(M+H)/d;if(!(j<0||j>=p.outHeight||Math.floor(j)!==j))for(let K=0;K<y;K+=g){let Z=(B+K)/c;if(Z<0||Z>=p.outWidth||Math.floor(Z)!==Z)continue;let J=E.get(F,j,Z,D);U+=J}}I.set(U*T,F,$,S,D)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}var D8={kernelName:Oc,backendName:"cpu",kernelFunc:$8};function R8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,scale:s,offset:i,mean:o,variance:l}=t;w.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ge([r,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=a;u==null&&(u=.001);let p=n.data.get(r.dataId).values,d=n.data.get(o.dataId).values,c=n.data.get(l.dataId).values,h=s?n.data.get(s.dataId).values:new Float32Array([1]),m=i?n.data.get(i.dataId).values:new Float32Array([0]),f=new Float32Array(p.length),g=m.length,b=h.length,y=c.length,x=d.length,v=0,I=0,T=0,C=0;for(let E=0;E<p.length;++E)f[E]=m[v++]+(p[E]-d[I++])*h[T++]/Math.sqrt(c[C++]+u),v>=g&&(v=0),I>=x&&(I=0),T>=b&&(T=0),C>=y&&(C=0);return n.makeTensorInfo(r.shape,r.dtype,f)}var M8={kernelName:Qi,backendName:"cpu",kernelFunc:R8};function P8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;ge([r],"batchToSpaceND");let o=s.reduce((b,y)=>b*y),l=N.getReshaped(r.shape,s,o),u=N.getPermuted(l.length,s.length),p=N.getReshapedPermuted(r.shape,s,o),d=N.getSliceBeginCoords(i,s.length),c=N.getSliceSize(p,i,s.length),h=xt({inputs:{x:r},backend:n,attrs:{shape:l}}),m=Un({inputs:{x:h},backend:n,attrs:{perm:u}}),f=xt({inputs:{x:m},backend:n,attrs:{shape:p}}),g=vi({inputs:{x:f},backend:n,attrs:{begin:d,size:c}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var O8={kernelName:mu,backendName:"cpu",kernelFunc:P8};function L8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=L1(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var z8={kernelName:fu,backendName:"cpu",kernelFunc:L8};function W8(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var B8={kernelName:zc,backendName:"cpu",kernelFunc:W8},V8=it(Ss,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),U8={kernelName:Ss,backendName:"cpu",kernelFunc:V8},G8=e=>{let{x:t}=e.inputs,n=e.backend,a=new Float32Array(w.sizeFromShape(t.shape)),r=n.data.get(t.dataId),s=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values;for(let u=0;u<o.length;u++){let p=o[u],d=l[u];a[u]=Math.hypot(p,d)}return n.makeOutput(a,t.shape,"float32")},H8={kernelName:Wc,backendName:"cpu",kernelFunc:G8};function su(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.imag,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}var q8={kernelName:Gm,backendName:"cpu",kernelFunc:su};function iu(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=t.map(f=>f.shape);N.assertParamsConsistent(i,s);let o=N.computeOutShape(t.map(f=>f.shape),s);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(f=>w.sizeFromShape(f.shape)>0);if(l.length===1)return dr({inputs:{x:l[0]},backend:n});if(l[0].dtype==="complex64"){let f=l.map(v=>xi({inputs:{input:v},backend:n})),g=l.map(v=>su({inputs:{input:v},backend:n})),b=iu({inputs:f,backend:n,attrs:{axis:s}}),y=iu({inputs:g,backend:n,attrs:{axis:s}}),x=Jn({inputs:{real:b,imag:y},backend:n});return f.forEach(v=>n.disposeIntermediateTensorInfo(v)),g.forEach(v=>n.disposeIntermediateTensorInfo(v)),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(y),x}let u=l.map(f=>{let g=[-1,w.sizeFromShape(f.shape.slice(s))];return xt({inputs:{x:f},backend:n,attrs:{shape:g}})}),p=u.map(f=>({vals:n.data.get(f.dataId).values,shape:f.shape}));o=N.computeOutShape(u.map(f=>f.shape),1);let d=u[0].shape[0]===1,c=z1(p,o,t[0].dtype,d),h=N.computeOutShape(l.map(f=>f.shape),s),m=n.makeTensorInfo(h,t[0].dtype,c);return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var j8={kernelName:bu,backendName:"cpu",kernelFunc:iu};function gE(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=a;ge([r,s],"conv2d");let d=N.convertConv2DDataFormat(l),c=N.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,d),h=c.filterHeight,m=c.filterWidth,f=c.dilationHeight,g=c.dilationWidth,b=c.padInfo.left,y=c.padInfo.top,x=c.dataFormat==="channelsLast",v=new Vt(c.outShape,r.dtype),I=w.computeStrides(r.shape),T=w.computeStrides(s.shape),C=I[0],E=x?I[1]:I[2],F=x?I[2]:1,D=x?1:I[1],$=v.strides[0],S=x?v.strides[1]:v.strides[2],M=x?v.strides[2]:1,B=x?1:v.strides[1],U=n.data.get(r.dataId).values,H=n.data.get(s.dataId).values,j=v.values;for(let K=0;K<c.batchSize;++K){let Z=K*C,J=K*$;for(let ee=0;ee<c.outHeight;++ee){let ae=J+ee*S,te=ee*c.strideHeight-y;for(let re=0;re<h;++re){let ie=te+re*f;if(ie<0||ie>=c.inHeight)continue;let ye=re*T[0],ue=Z+ie*E;for(let be=0;be<c.outWidth;++be){let ke=ae+be*M,Se=be*c.strideWidth-b;for(let We=0;We<m;++We){let Ge=Se+We*g;if(Ge<0||Ge>=c.inWidth)continue;let ht=ye+We*T[1],st=ue+Ge*F,at=ht;for(let rt=0;rt<c.inChannels;++rt){let Me=U[st+rt*D];for(let ft=0;ft<c.outChannels;++ft)j[ke+ft*B]+=Me*H[at+ft];at+=c.outChannels}}}}}}return n.makeTensorInfo(v.shape,v.dtype,j)}var K8={kernelName:Li,backendName:"cpu",kernelFunc:gE};function X8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=a;ge([r,s],"conv2dBackpropFilter");let d=N.convertConv2DDataFormat(l),c=N.computeConv2DInfo(r.shape,p,i,1,o,u,!1,d),{strideHeight:h,strideWidth:m,filterHeight:f,filterWidth:g}=c,b=c.dataFormat==="channelsLast",y=new Vt(c.filterShape,"float32"),x=c.padInfo.left,v=c.padInfo.top,I=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,C=new Vt(r.shape,r.dtype,I),E=new Vt(s.shape,s.dtype,T);for(let F=0;F<f;++F){let D=Math.max(0,Math.ceil((v-F)/h)),$=Math.min(c.outHeight,(c.inHeight+v-F)/h);for(let S=0;S<g;++S){let M=Math.max(0,Math.ceil((x-S)/m)),B=Math.min(c.outWidth,(c.inWidth+x-S)/m);for(let U=0;U<c.inChannels;++U)for(let H=0;H<c.outChannels;++H){let j=0;for(let K=0;K<c.batchSize;++K)for(let Z=D;Z<$;++Z){let J=F+Z*h-v;for(let ee=M;ee<B;++ee){let ae=S+ee*m-x;b?j+=C.get(K,J,ae,U)*E.get(K,Z,ee,H):j+=C.get(K,U,J,ae)*E.get(K,H,Z,ee)}}y.set(j,F,S,U,H)}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var Y8={kernelName:Lm,backendName:"cpu",kernelFunc:X8};function Z8(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=a;ge([r,s],"conv2dBackpropInput");let d=w.computeStrides(s.shape),c=w.computeStrides(r.shape),h=N.convertConv2DDataFormat(u),m=N.computeConv2DInfo(i,s.shape,o,1,l,p,!1,h),f=new Vt(m.inShape,"float32"),g=f.values,b=n.data.get(r.dataId).values,y=n.data.get(s.dataId).values,[x,v,I]=d,{batchSize:T,filterHeight:C,filterWidth:E,inChannels:F,inHeight:D,inWidth:$,outChannels:S,outHeight:M,outWidth:B,strideHeight:U,strideWidth:H}=m;h=m.dataFormat;let j=C-1-m.padInfo.top,K=E-1-m.padInfo.left,Z=h==="channelsLast",J=f.strides[0],ee=Z?f.strides[1]:f.strides[2],ae=Z?f.strides[2]:1,te=Z?1:f.strides[1],re=c[0],ie=Z?c[1]:c[2],ye=Z?c[2]:1,ue=Z?1:c[1];for(let be=0;be<T;++be)for(let ke=0;ke<F;++ke)for(let Se=0;Se<D;++Se){let We=Se-j,Ge=Math.max(0,Math.ceil(We/U)),ht=Math.min(M,(C+We)/U);for(let st=0;st<$;++st){let at=st-K,rt=Math.max(0,Math.ceil(at/H)),Me=Math.min(B,(E+at)/H),ft=0;for(let Lt=Ge;Lt<ht;++Lt){let la=Lt*U-We;for(let cn=rt;cn<Me;++cn){let $n=cn*H-at,ua=re*be+ie*Lt+ye*cn,Dn=x*(C-1-la)+v*(E-1-$n)+I*ke;for(let lt=0;lt<S;++lt){let Rn=b[ua+ue*lt],Kn=y[Dn+lt];ft+=Rn*Kn}}}let jn=J*be+ee*Se+ae*st+te*ke;g[jn]=ft}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var J8={kernelName:zi,backendName:"cpu",kernelFunc:Z8};function Q8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;ge([r,s],"conv3d");let u=N.computeConv3DInfo(r.shape,s.shape,i,l,o),{filterDepth:p,filterHeight:d,filterWidth:c,dilationDepth:h,dilationHeight:m,dilationWidth:f,padInfo:g}=u,b=g.front,y=g.left,x=g.top,v=new Vt(u.outShape,r.dtype),I=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,C=v.values,E=w.computeStrides(r.shape),F=w.computeStrides(s.shape);for(let D=0;D<u.batchSize;++D){let $=D*E[0],S=D*v.strides[0];for(let M=0;M<u.outDepth;++M){let B=S+M*v.strides[1],U=M*u.strideDepth-b;for(let H=0;H<p;++H){let j=U+H*h;if(j<0||j>=u.inDepth)continue;let K=H*F[0],Z=$+j*E[1];for(let J=0;J<u.outHeight;++J){let ee=B+J*v.strides[2],ae=J*u.strideHeight-x;for(let te=0;te<d;++te){let re=ae+te*m;if(re<0||re>=u.inHeight)continue;let ie=K+te*F[1],ye=Z+re*E[2];for(let ue=0;ue<u.outWidth;++ue){let be=ee+ue*u.outChannels,ke=ue*u.strideWidth-y;for(let Se=0;Se<c;++Se){let We=ke+Se*f;if(We<0||We>=u.inWidth)continue;let Ge=ie+Se*F[2],ht=ye+We*u.inChannels,st=Ge;for(let at=0;at<u.inChannels;++at){let rt=I[ht+at];for(let Me=0;Me<u.outChannels;++Me)C[be+Me]+=rt*T[st+Me];st+=u.outChannels}}}}}}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}var eX={kernelName:Wi,backendName:"cpu",kernelFunc:Q8};function tX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;ge([r,s],"conv3dBackpropFilterV2");let u=w.computeStrides(r.shape),p=w.computeStrides(s.shape),d=N.computeConv3DInfo(r.shape,l,i,1,o),c=d.strideDepth,h=d.strideHeight,m=d.strideWidth,f=d.filterDepth,g=d.filterHeight,b=d.filterWidth,y=new Vt(d.filterShape,"float32"),x=y.values,[v,I,T,C]=y.strides,E=n.data.get(s.dataId).values,[F,D,$,S]=p,M=n.data.get(r.dataId).values,[B,U,H,j]=u,K=d.padInfo.front,Z=d.padInfo.left,J=d.padInfo.top;for(let ee=0;ee<f;++ee){let ae=Math.max(0,Math.ceil((K-ee)/c)),te=Math.min(d.outDepth,(d.inDepth+K-ee)/c),re=ee*v;for(let ie=0;ie<g;++ie){let ye=Math.max(0,Math.ceil((J-ie)/h)),ue=Math.min(d.outHeight,(d.inHeight+J-ie)/h),be=ie*I+re;for(let ke=0;ke<b;++ke){let Se=Math.max(0,Math.ceil((Z-ke)/m)),We=Math.min(d.outWidth,(d.inWidth+Z-ke)/m),Ge=ke*T+be;for(let ht=0;ht<d.inChannels;++ht){let st=ht*C+Ge;for(let at=0;at<d.outChannels;++at){let rt=0;for(let Me=0;Me<d.batchSize;++Me){let ft=Me*B,jn=Me*F;for(let Lt=ae;Lt<te;++Lt){let la=(ee+Lt*c-K)*U+ft,cn=Lt*D+jn;for(let $n=ye;$n<ue;++$n){let ua=(ie+$n*h-J)*H+la,Dn=$n*$+cn;for(let lt=Se;lt<We;++lt){let Rn=(ke+lt*m-Z)*j+ua,Kn=lt*S+Dn;rt+=M[Rn+ht]*E[Kn+at]}}}}x[st+at]=rt}}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var nX={kernelName:yu,backendName:"cpu",kernelFunc:tX};function aX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;ge([r],"conv3dBackpropInputV2");let u=w.computeStrides(r.shape),p=w.computeStrides(s.shape),d=N.computeConv3DInfo(l,s.shape,o,1,i),c=new Vt(d.inShape,"float32"),h=c.values,[m,f,g,b]=c.strides,y=n.data.get(r.dataId).values,[x,v,I,T]=u,C=n.data.get(s.dataId).values,[E,F,D,$]=p,{batchSize:S,filterDepth:M,filterHeight:B,filterWidth:U,inChannels:H,inDepth:j,inHeight:K,inWidth:Z,outChannels:J,outDepth:ee,outHeight:ae,outWidth:te,strideDepth:re,strideHeight:ie,strideWidth:ye}=d,ue=M-1-d.padInfo.front,be=B-1-d.padInfo.top,ke=U-1-d.padInfo.left;for(let Se=0;Se<S;++Se)for(let We=0;We<H;++We)for(let Ge=0;Ge<j;++Ge){let ht=Ge-ue,st=Math.max(0,Math.ceil(ht/re)),at=Math.min(ee,(M+ht)/re);for(let rt=0;rt<K;++rt){let Me=rt-be,ft=Math.max(0,Math.ceil(Me/ie)),jn=Math.min(ae,(B+Me)/ie);for(let Lt=0;Lt<Z;++Lt){let la=Lt-ke,cn=Math.max(0,Math.ceil(la/ye)),$n=Math.min(te,(U+la)/ye),ua=0;for(let Dn=st;Dn<at;++Dn){let lt=Dn*re-ht;for(let Rn=ft;Rn<jn;++Rn){let Kn=Rn*ie-Me;for(let Ir=cn;Ir<$n;++Ir){let Nl=Ir*ye-la,tr=x*Se+v*Dn+I*Rn+T*Ir,Gp=E*(M-1-lt)+F*(B-1-Kn)+D*(U-1-Nl)+$*We;for(let Na=0;Na<J;++Na){let Zr=y[tr+Na],Qt=C[Gp+Na];ua+=Zr*Qt}}}}h[m*Se+f*Ge+g*rt+b*Lt+We]=ua}}}return n.makeTensorInfo(c.shape,c.dtype,c.values)}var rX={kernelName:xu,backendName:"cpu",kernelFunc:aX},sX=it(Bi,e=>Math.cos(e)),iX={kernelName:Bi,backendName:"cpu",kernelFunc:sX},oX=it(Vi,e=>Math.cosh(e)),lX={kernelName:Vi,backendName:"cpu",kernelFunc:oX};function uX(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,[p,d,c,h]=r.shape,m=s.shape[0],[f,g]=o,b=ze([m,f,g,h],"float32"),y=n.data.get(s.dataId).values,x=n.data.get(i.dataId).values,v=n.data.get(r.dataId).values,I=w.computeStrides(r.shape),T=w.computeStrides(b.shape);for(let C=0;C<m;C++){let E=C*4,F=y[E],D=y[E+1],$=y[E+2],S=y[E+3],M=x[C];if(M>=p)continue;let B=f>1?($-F)*(d-1)/(f-1):0,U=g>1?(S-D)*(c-1)/(g-1):0;for(let H=0;H<f;H++){let j=f>1?F*(d-1)+H*B:.5*(F+$)*(d-1);if(j<0||j>d-1){for(let K=0;K<g;K++)for(let Z=0;Z<h;Z++){let J=Z+K*T[2]+H*T[1]+C*T[0];b.values[J]=u}continue}if(l==="bilinear"){let K=Math.floor(j),Z=Math.ceil(j),J=j-K;for(let ee=0;ee<g;ee++){let ae=g>1?D*(c-1)+ee*U:.5*(D+S)*(c-1);if(ae<0||ae>c-1){for(let ye=0;ye<h;ye++){let ue=ye+ee*T[2]+H*T[1]+C*T[0];b.values[ue]=u}continue}let te=Math.floor(ae),re=Math.ceil(ae),ie=ae-te;for(let ye=0;ye<h;ye++){let ue=ye+te*I[2]+K*I[1]+M*I[0],be=v[ue];ue=ye+re*I[2]+K*I[1]+M*I[0];let ke=v[ue];ue=ye+te*I[2]+Z*I[1]+M*I[0];let Se=v[ue];ue=ye+re*I[2]+Z*I[1]+M*I[0];let We=v[ue],Ge=be+(ke-be)*ie,ht=Se+(We-Se)*ie;ue=ye+ee*T[2]+H*T[1]+C*T[0],b.values[ue]=Ge+(ht-Ge)*J}}}else for(let K=0;K<g;++K){let Z=g>1?D*(c-1)+K*U:.5*(D+S)*(c-1);if(Z<0||Z>c-1){for(let ae=0;ae<h;ae++){let te=ae+K*T[2]+H*T[1]+C*T[0];b.values[te]=u}continue}let J=Math.round(Z),ee=Math.round(j);for(let ae=0;ae<h;ae++){let te=ae+J*I[2]+ee*I[1]+M*I[0],re=ae+K*T[2]+H*T[1]+C*T[0];b.values[re]=v[te]}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var pX={kernelName:wu,backendName:"cpu",kernelFunc:uX};function cX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;ge(r,"cumprod");let l=N.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=Un({inputs:{x:r},backend:n,attrs:{perm:l}}));let p=N.getInnerMostAxes(1,r.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let d=ba(u.dtype,"int32"),c=w.makeOnesTypedArray(w.sizeFromShape(u.shape),d),h=n.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(b,y)=>b+m-y-1:(b,y)=>b+y;for(let b=0;b<h.length;b+=m)for(let y=0;y<m;y++){let x=f(b,y);if(y===0)c[x]=i?1:h[x];else{let v=f(b,y-1);c[x]=i?h[v]*c[v]:h[x]*c[v]}}let g=n.makeTensorInfo(u.shape,d,c);if(l!=null){let b=N.getUndoAxesPermutation(l),y=Un({inputs:{x:g},backend:n,attrs:{perm:b}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),y}return g}var dX={kernelName:vu,backendName:"cpu",kernelFunc:cX};function hX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;ge(r,"cumsum");let l=N.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=Un({inputs:{x:r},backend:n,attrs:{perm:l}}));let p=N.getInnerMostAxes(1,r.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let d=ba(u.dtype,"int32"),c=w.makeZerosTypedArray(w.sizeFromShape(u.shape),d),h=n.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(b,y)=>b+m-y-1:(b,y)=>b+y;for(let b=0;b<h.length;b+=m)for(let y=0;y<m;y++){let x=f(b,y);if(y===0)c[x]=i?0:h[x];else{let v=f(b,y-1);c[x]=i?h[v]+c[v]:h[x]+c[v]}}let g=n.makeTensorInfo(u.shape,d,c);if(l!=null){let b=N.getUndoAxesPermutation(l),y=Un({inputs:{x:g},backend:n,attrs:{perm:b}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),y}return g}var mX={kernelName:Ui,backendName:"cpu",kernelFunc:hX};function fX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=L1(l,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(s),p=S_(l,u,i,o);return n.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var gX={kernelName:Bc,backendName:"cpu",kernelFunc:fX};function bX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;w.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=r.shape[0],l=r.shape[1],u=r.shape[2],p=r.shape[3],d=l*s,c=u*s,h=p/(s*s),m=n.data.get(r.dataId).values,f=new Float32Array(o*d*c*h),g=0;for(let b=0;b<o;++b)for(let y=0;y<d;++y){let x=Math.floor(y/s),v=y%s;for(let I=0;I<c;++I){let T=Math.floor(I/s),C=I%s,E=(v*s+C)*h;for(let F=0;F<h;++F){let D=F+E+p*(T+u*(x+l*b));f[g++]=m[D]}}}return n.makeTensorInfo([o,d,c,h],r.dtype,f)}var yX={kernelName:ku,backendName:"cpu",kernelFunc:bX};function bE(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=a;ge([r,s],"depthwiseConv2DNative");let p=w.computeStrides(r.shape),d=w.computeStrides(s.shape),c=l;c==null&&(c=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(i,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let h=N.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:b,padInfo:y}=h,x=y.left,v=y.top,I=h.outChannels/h.inChannels,T=new Vt(h.outShape,r.dtype),C=n.data.get(r.dataId).values,E=n.data.get(s.dataId).values,F=T.values;for(let D=0;D<h.batchSize;++D){let $=D*p[0],S=D*T.strides[0];for(let M=0;M<h.outHeight;++M){let B=S+M*T.strides[1],U=M*h.strideHeight-v;for(let H=0;H<m;++H){let j=U+H*g;if(j<0||j>=h.inHeight)continue;let K=H*d[0],Z=$+j*p[1];for(let J=0;J<h.outWidth;++J){let ee=B+J*T.strides[2],ae=J*h.strideWidth-x;for(let te=0;te<f;++te){let re=ae+te*b;if(re<0||re>=h.inWidth)continue;let ie=K+te*d[1],ye=Z+re*h.inChannels,ue=ee,be=ie;for(let ke=0;ke<h.inChannels;++ke){let Se=C[ye+ke];for(let We=0;We<I;++We)F[ue+We]+=Se*E[be+We];ue+=I,be+=I}}}}}}return n.makeTensorInfo(T.shape,T.dtype,T.values)}var xX={kernelName:Gi,backendName:"cpu",kernelFunc:bE};function vX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=a;ge([r,s],"depthwiseConv2dNativeBackpropFilter");let d=N.computeConv2DInfo(r.shape,p,i,o,l,u,!0),{strideHeight:c,strideWidth:h,filterHeight:m,filterWidth:f}=d,g=new Vt(d.filterShape,"float32"),b=d.padInfo.left,y=d.padInfo.top,x=d.outChannels/d.inChannels,v=n.data.get(r.dataId).values,I=new Vt(r.shape,r.dtype,v),T=n.data.get(s.dataId).values,C=new Vt(s.shape,s.dtype,T);for(let E=0;E<m;++E){let F=Math.max(0,Math.ceil((y-E)/c)),D=Math.min(d.outHeight,(d.inHeight+y-E)/c);for(let $=0;$<f;++$){let S=Math.max(0,Math.ceil((b-$)/h)),M=Math.min(d.outWidth,(d.inWidth+b-$)/h);for(let B=0;B<d.outChannels;++B){let U=Math.trunc(B/x),H=B%x,j=0;for(let K=0;K<d.batchSize;++K)for(let Z=F;Z<D;++Z){let J=E+Z*c-y;for(let ee=S;ee<M;++ee){let ae=$+ee*h-b;j+=I.get(K,J,ae,U)*C.get(K,Z,ee,B)}}g.set(j,E,$,U,H)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var wX={kernelName:zm,backendName:"cpu",kernelFunc:vX};function kX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=a;ge([r,s],"depthwiseConv2DNativeBackpropInput");let d=w.computeStrides(r.shape),c=w.computeStrides(s.shape),h=N.computeConv2DInfo(p,s.shape,i,o,l,u,!0),m=new Vt(h.inShape,"float32"),f=m.values,[g,b,y]=m.strides,x=n.data.get(r.dataId).values,[v,I,T]=d,C=n.data.get(s.dataId).values,[E,F,D]=c,{batchSize:$,filterHeight:S,filterWidth:M,inChannels:B,inHeight:U,inWidth:H,outChannels:j,outHeight:K,outWidth:Z,strideHeight:J,strideWidth:ee}=h,ae=S-1-h.padInfo.top,te=M-1-h.padInfo.left,re=j/B;for(let ie=0;ie<$;++ie)for(let ye=0;ye<B;++ye)for(let ue=0;ue<U;++ue){let be=ue-ae,ke=Math.max(0,Math.ceil(be/J)),Se=Math.min(K,(S+be)/J);for(let We=0;We<H;++We){let Ge=We-te,ht=Math.max(0,Math.ceil(Ge/ee)),st=Math.min(Z,(M+Ge)/ee),at=0;for(let rt=ke;rt<Se;++rt){let Me=rt*J-be;for(let ft=ht;ft<st;++ft){let jn=ft*ee-Ge,Lt=v*ie+I*rt+T*ft,la=E*(S-1-Me)+F*(M-1-jn)+D*ye;for(let cn=0;cn<re;++cn){let $n=ye*re+cn,ua=x[Lt+$n],Dn=C[la+cn];at+=ua*Dn}}}f[g*ie+b*ue+y*We+ye]=at}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var IX={kernelName:Wm,backendName:"cpu",kernelFunc:kX};function SX(e){let{inputs:t,backend:n}=e,{x:a}=t,r=w.sizeFromShape(a.shape),s=n.data.get(a.dataId).values,i=ze([r,r],a.dtype),o=i.values;for(let u=0;u<s.length;u++)o[u*r+u]=s[u];let l=[...a.shape,...a.shape];return n.makeTensorInfo(l,i.dtype,i.values)}var NX={kernelName:Vc,backendName:"cpu",kernelFunc:SX},TX={kernelName:Hi,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r}=e,{strides:s,pad:i,dilations:o}=n,l=t,u=l.data.get(a.dataId).values,p=a.shape.length,d=l.data.get(r.dataId).values,c=r.shape.length,{batchSize:h,inHeight:m,inWidth:f,inChannels:g,outHeight:b,outWidth:y,padInfo:x,strideHeight:v,strideWidth:I,filterHeight:T,filterWidth:C,dilationHeight:E,dilationWidth:F,outShape:D}=N.computeDilation2DInfo(a.shape,r.shape,s,i,"NHWC",o),$=w.sizeFromShape(D),S=D.length,M=w.getArrayFromDType(a.dtype,$);for(let B=0;B<h;++B)for(let U=0;U<b;++U){let H=U*v-x.top;for(let j=0;j<y;++j){let K=j*I-x.left;for(let Z=0;Z<g;++Z){let J=Number.MIN_SAFE_INTEGER;for(let ae=0;ae<T;++ae){let te=H+ae*E;if(te>=0&&te<m)for(let re=0;re<C;++re){let ie=K+re*F;if(ie>=0&&ie<f){let ye=w.locToIndex([B,te,ie,Z],p,w.computeStrides(a.shape)),ue=w.locToIndex([ae,re,Z],c,w.computeStrides(r.shape)),be=u[ye]+d[ue];be>J&&(J=be)}}}let ee=w.locToIndex([B,U,j,Z],S,w.computeStrides(D));M[ee]=J}}}return{dataId:l.write(w.toTypedArray(M,a.dtype),D,a.dtype),shape:D,dtype:a.dtype}}},CX={kernelName:Ul,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,u=t,p=w.toNestedArray(a.shape,u.data.get(a.dataId).values),d=w.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:c,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:b,padInfo:y,strideHeight:x,strideWidth:v,filterHeight:I,filterWidth:T,dilationHeight:C,dilationWidth:E,outShape:F}=N.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);w.assert(s.rank===F.length,()=>`Error in ${Ul}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let D=w.toNestedArray(F,u.data.get(s.dataId).values),$=w.makeZerosNestedTypedArray(r.shape,r.dtype);for(let S=0;S<c;++S)for(let M=0;M<g;++M){let B=M*x-y.top;for(let U=0;U<b;++U){let H=U*v-y.left;for(let j=0;j<f;++j){let K=Number.MIN_SAFE_INTEGER,Z=0,J=0;for(let ee=0;ee<I;++ee){let ae=B+ee*C;if(ae>=0&&ae<h)for(let te=0;te<T;++te){let re=H+te*E;if(re>=0&&re<m){let ie=p[S][ae][re][j]+d[ee][te][j];ie>K&&(K=ie,Z=ee,J=te)}}}$[Z][J][j]+=D[S][M][U][j]}}}return{dataId:u.write(w.toTypedArray($,a.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},_X={kernelName:Vl,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,u=t,p=w.toNestedArray(a.shape,u.data.get(a.dataId).values),d=w.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:c,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:b,padInfo:y,strideHeight:x,strideWidth:v,filterHeight:I,filterWidth:T,dilationHeight:C,dilationWidth:E,outShape:F}=N.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);w.assert(s.rank===F.length,()=>`Error in ${Vl}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let D=w.toNestedArray(F,u.data.get(s.dataId).values),$=w.makeZerosNestedTypedArray(a.shape,a.dtype);for(let S=0;S<c;++S)for(let M=0;M<g;++M){let B=M*x-y.top;for(let U=0;U<b;++U){let H=U*v-y.left;for(let j=0;j<f;++j){let K=Number.MIN_SAFE_INTEGER,Z=B<0?0:B,J=H<0?0:H;for(let ee=0;ee<I;++ee){let ae=B+ee*C;if(ae>=0&&ae<h)for(let te=0;te<T;++te){let re=H+te*E;if(re>=0&&re<m){let ie=p[S][ae][re][j]+d[ee][te][j];ie>K&&(K=ie,Z=ae,J=re)}}}$[S][Z][J][j]+=D[S][M][U][j]}}}return{dataId:u.write(w.toTypedArray($,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function EX(e){let{inputs:t,backend:n,attrs:a}=e,{image:r}=t,{canvas:s,options:i}=a,{contextOptions:o,imageOptions:l}=i||{},u=(l==null?void 0:l.alpha)||1,p=(o==null?void 0:o.contextType)||"2d";if(p!=="2d")throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);let d=s.getContext(p,(o==null?void 0:o.contextAttributes)||{});if(d==null)throw new Error(`Could not get the context with ${p} type.`);let[c,h]=r.shape.slice(0,2),m=r.shape.length===2?1:r.shape[2],f=n.data.get(r.dataId).values,g=r.dtype==="float32"?255:1,b=new Uint8ClampedArray(h*c*4);for(let x=0;x<c*h;++x){let v=[0,0,0,255*u];for(let T=0;T<m;T++){let C=f[x*m+T];if(r.dtype==="float32"){if(C<0||C>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${C}.`)}else if(r.dtype==="int32"&&(C<0||C>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${C}.`);m===1?(v[0]=C*g,v[1]=C*g,v[2]=C*g):v[T]=C*g}let I=x*4;b[I+0]=Math.round(v[0]),b[I+1]=Math.round(v[1]),b[I+2]=Math.round(v[2]),b[I+3]=Math.round(v[3])}s.width=h,s.height=c;let y=new ImageData(b,h,c);return d.putImageData(y,0,0),r}var AX={kernelName:Av,backendName:"cpu",kernelFunc:EX};function Rd(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"sum");let o;r.dtype==="bool"?o=vs({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):o=dr({inputs:{x:r},backend:n});let l=o.shape.length,u=w.parseAxisParam(s,o.shape),p=N.getAxesPermutation(u,l),d=u,c=o;p!=null&&(c=Un({inputs:{x:o},backend:n,attrs:{perm:p}}),d=N.getInnerMostAxes(d.length,l)),N.assertAxesAreInnerMostDims("sum",d,c.shape.length);let[h,m]=N.computeOutAndReduceShapes(c.shape,d),f=N.upcastType(c.dtype,"int32"),g=Sm(n,h,f),b=w.sizeFromShape(m),y=n.data.get(g.dataId).values,x=n.data.get(c.dataId).values;for(let v=0;v<y.length;++v){let I=v*b,T=0;for(let C=0;C<b;++C)T+=x[I+C];y[v]=T}if(i){let v=N.expandShapeToKeepDim(g.shape,u),I=g;g=xt({inputs:{x:g},backend:n,attrs:{shape:v}}),n.disposeIntermediateTensorInfo(I)}return n.disposeIntermediateTensorInfo(o),p!=null&&n.disposeIntermediateTensorInfo(c),g}var FX={kernelName:zo,backendName:"cpu",kernelFunc:Rd};function $X(e){let{inputs:t,backend:n,attrs:a}=e,{equation:r}=a,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(r,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=N.getEinsumComputePath(o,l),d=p.length,c=null,h=i.length,m=[];for(let f=0;f<d;++f){for(let g of p[f]){let{permutationIndices:b,expandDims:y}=N.getEinsumPermutation(h,l[g]),x;N.isIdentityPermutation(b)?x=s[g]:(x=Un({inputs:{x:s[g]},backend:n,attrs:{perm:b}}),m.push(x));let v=x.shape.slice();for(let I=0;I<y.length;++I)v.splice(y[I],0,1);w.arraysEqual(x.shape,v)||(x=xt({inputs:{x},backend:n,attrs:{shape:v}}),m.push(x)),c===null?c=x:(c=Zf({inputs:{a:x,b:c},backend:n}),m.push(c))}f<d-1&&(u[f]>=0&&(c=Rd({inputs:{x:c},backend:n,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(c)),h--)}for(let f of m)f!==c&&n.disposeIntermediateTensorInfo(f);return c}var DX={kernelName:Bm,backendName:"cpu",kernelFunc:$X};function RX(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t;ge([a,r],"eluGrad");let s=new Float32Array(w.sizeFromShape(r.shape)),i=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values;for(let l=0;l<i.length;++l){let u=i[l];u>=0?s[l]=o[l]:s[l]=o[l]*(u+1)}return n.makeTensorInfo(r.shape,"float32",s)}var MX={kernelName:Iu,backendName:"cpu",kernelFunc:RX},PX=N.ERF_P,OX=N.ERF_A1,LX=N.ERF_A2,zX=N.ERF_A3,WX=N.ERF_A4,BX=N.ERF_A5,VX=it(Ki,e=>{let t=Math.sign(e),n=Math.abs(e),a=1/(1+PX*n);return t*(1-((((BX*a+WX)*a+zX)*a+LX)*a+OX)*a*Math.exp(-n*n))}),UX={kernelName:Ki,backendName:"cpu",kernelFunc:VX};function Cm(e){let{inputs:t,backend:n,attrs:a}=e,{input:r}=t,{dim:s}=a,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),xt({inputs:{x:r},backend:n,attrs:{shape:o}})}var GX={kernelName:Nu,backendName:"cpu",kernelFunc:Cm},HX=Ot((e,t)=>e/t),Y1=Jt(qi,HX),pv={kernelName:qi,backendName:"cpu",kernelFunc:Y1};function yE(e,t,n){let a=e.shape,r=a[0],s=a[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,s],p=w.sizeFromShape(u),d=w.getTypedArrayFromDType("float32",p),c=w.getTypedArrayFromDType("float32",p);for(let g=0;g<r;g++){let b=vi({inputs:{x:o},backend:n,attrs:{begin:[g,0],size:[1,s]}}),y=vi({inputs:{x:l},backend:n,attrs:{begin:[g,0],size:[1,s]}}),x=Jn({inputs:{real:b,imag:y},backend:n}),{real:v,imag:I}=qX(x,t,n),T=N.mergeRealAndImagArrays(v,I);for(let C=0;C<s;C++){let E=N.getComplexWithIndex(T,C);d[g*s+C]=E.real,c[g*s+C]=E.imag}n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(x)}let h=n.makeTensorInfo(u,"float32",d),m=n.makeTensorInfo(u,"float32",c),f=Jn({inputs:{real:h,imag:m},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}function qX(e,t,n){let a=w.sizeFromShape(e.shape),r=n.data.get(e.dataId),s=n.data.get(r.complexTensorInfos.real.dataId).values,i=n.data.get(r.complexTensorInfos.imag.dataId).values;if(jX(a)){let o=cv(s,i,a,t,n),l=[e.shape[0],e.shape[1]];if(t){let u=n.makeTensorInfo(l,"float32",o.real),p=n.makeTensorInfo(l,"float32",o.imag),d=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),c=dr({inputs:{x:d},backend:n}),h=pv.kernelFunc({inputs:{a:u,b:d},backend:n}),m=pv.kernelFunc({inputs:{a:p,b:c},backend:n}),f=n.data.get(h.dataId).values,g=n.data.get(m.dataId).values;return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return o}else{let o=N.mergeRealAndImagArrays(s,i),l=KX(o,a,t);return N.splitRealAndImagArrays(l)}}function jX(e){return(e&e-1)===0}function cv(e,t,n,a,r){if(n===1)return{real:e,imag:t};let s=N.mergeRealAndImagArrays(e,t),i=n/2,o=N.complexWithEvenIndex(s),l=o.real,u=o.imag,p=[l.length],d=r.makeTensorInfo(p,"float32",l),c=r.makeTensorInfo(p,"float32",u),h=Jn({inputs:{real:d,imag:c},backend:r}),m=N.complexWithOddIndex(s),f=m.real,g=m.imag,b=[f.length],y=r.makeTensorInfo(b,"float32",f),x=r.makeTensorInfo(b,"float32",g),v=Jn({inputs:{real:y,imag:x},backend:r}),I=cv(l,u,i,a,r),T=I.real,C=I.imag,E=[T.length],F=r.makeTensorInfo(E,"float32",T),D=r.makeTensorInfo(E,"float32",C),$=Jn({inputs:{real:F,imag:D},backend:r}),S=cv(f,g,i,a,r),M=S.real,B=S.imag,U=[M.length],H=r.makeTensorInfo(U,"float32",M),j=r.makeTensorInfo(U,"float32",B),K=Jn({inputs:{real:H,imag:j},backend:r}),Z=N.exponents(n,a),J=[Z.real.length],ee=r.makeTensorInfo(J,"float32",Z.real),ae=r.makeTensorInfo(J,"float32",Z.imag),te=Jn({inputs:{real:ee,imag:ae},backend:r}),re=Zf({inputs:{a:te,b:K},backend:r}),ie=ru({inputs:{a:$,b:re},backend:r}),ye=j1({inputs:{a:$,b:re},backend:r}),ue=xi({inputs:{input:ie},backend:r}),be=xi({inputs:{input:ye},backend:r}),ke=su({inputs:{input:ie},backend:r}),Se=su({inputs:{input:ye},backend:r}),We=iu({inputs:[ue,be],backend:r,attrs:{axis:0}}),Ge=iu({inputs:[ke,Se],backend:r,attrs:{axis:0}}),ht=r.data.get(We.dataId).values,st=r.data.get(Ge.dataId).values;return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(v),r.disposeIntermediateTensorInfo(F),r.disposeIntermediateTensorInfo(D),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(H),r.disposeIntermediateTensorInfo(j),r.disposeIntermediateTensorInfo(K),r.disposeIntermediateTensorInfo(ee),r.disposeIntermediateTensorInfo(ae),r.disposeIntermediateTensorInfo(te),r.disposeIntermediateTensorInfo(re),r.disposeIntermediateTensorInfo(ie),r.disposeIntermediateTensorInfo(ye),r.disposeIntermediateTensorInfo(ue),r.disposeIntermediateTensorInfo(ke),r.disposeIntermediateTensorInfo(be),r.disposeIntermediateTensorInfo(Se),r.disposeIntermediateTensorInfo(We),r.disposeIntermediateTensorInfo(Ge),{real:ht,imag:st}}function KX(e,t,n){let a=new Float32Array(t*2);for(let r=0;r<t;r++){let s=0,i=0;for(let o=0;o<t;o++){let l=N.exponent(r*o,t,n),u=N.getComplexWithIndex(e,o);s+=u.real*l.real-u.imag*l.imag,i+=u.real*l.imag+u.imag*l.real}n&&(s/=t,i/=t),N.assignToTypedArray(a,s,i,r)}return a}function XX(e){let{inputs:t,backend:n}=e,{input:a}=t,r=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=xt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=yE(o,!1,n),u=xt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var YX={kernelName:Vm,backendName:"cpu",kernelFunc:XX};function Z1(e){let{backend:t,attrs:n}=e,{shape:a,value:r,dtype:s}=n,i=s||w.inferDtype(r),o=w.getArrayFromDType(i,w.sizeFromShape(a));return JX(o,r,i),t.makeTensorInfo(a,i,o)}var ZX={kernelName:Uc,backendName:"cpu",kernelFunc:Z1};function JX(e,t,n){e.fill(t)}var QX={kernelName:Tu,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,r=n,s=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[i,o,l,u]=a.shape,p=r.data.get(a.dataId).values;for(let d=0;d<i;d++){let c=d*l*o*u;for(let h=0;h<o;h++){let m=h*(l*u);for(let f=0;f<l;f++){let g=f*u;for(let b=0;b<u;b++){let y=Math.round(l-f-1),x=c+m+g+b,v=p[x];if(y>=0&&y<l){let I=y*u,T=c+m+I+b;v=p[T]}s[x]=v}}}}return{dataId:r.write(s,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function eY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=gE({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c}});if(i){let g=f;if(p==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let b=xt({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});f=ru({inputs:{a:f,b},backend:n}),n.disposeIntermediateTensorInfo(b)}else f=ru({inputs:{a:f,b:i},backend:n});n.disposeIntermediateTensorInfo(g)}if(h){let g=f;if(p==="NCHW"&&h==="prelu"&&o.shape.length===1&&o.shape[0]!==1){let b=xt({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});f=Tm(n,f,h,b,m),n.disposeIntermediateTensorInfo(b)}else f=Tm(n,f,h,o,m);n.disposeIntermediateTensorInfo(g)}return f}var tY={kernelName:li,backendName:"cpu",kernelFunc:eY};function nY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=bE({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c}});if(i){let g=f;f=ru({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Tm(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var aY={kernelName:ui,backendName:"cpu",kernelFunc:nY};function rY(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=w.sizeFromShape(a.shape),i=r.shape,o=i[i.length-1],[l,u,p,d]=N.prepareAndValidate(a,r);if(u===0)return n.makeTensorInfo(l,a.dtype,[]);let c=n.data.get(r.dataId).values,h=n.bufferSync(a),m=R_(c,h,a.dtype,u,o,p,d,a.shape,s);return n.makeTensorInfo(l,a.dtype,m.values)}var sY={kernelName:_u,backendName:"cpu",kernelFunc:rY};function iY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a;ge([r,s],"gatherV2");let l=w.parseAxisParam(i,r.shape)[0],u=n.data.get(s.dataId).values,p=r.shape[l];for(let v=0;v<u.length;++v){let I=u[v];w.assert(I<=p-1&&I>=0,()=>`GatherV2: the index value ${I} is not in [0, ${p-1}]`)}let d=o;o==null&&(d=0);let c=w.sizeFromShape(s.shape),h=N.segment_util.collectGatherOpShapeInfo(r,s,l,d),m=xt({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),f=xt({inputs:{x:s},backend:n,attrs:{shape:[h.batchSize,c/h.batchSize]}}),g=[h.batchSize,h.outerSize,c/h.batchSize,h.sliceSize],b=n.bufferSync(f),y=n.bufferSync(m),x=M_(y,b,g);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.makeTensorInfo(h.outputShape,x.dtype,x.values)}var oY={kernelName:Cu,backendName:"cpu",kernelFunc:iY};function lY(e){let{inputs:t,backend:n}=e,{input:a}=t,r=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=xt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=yE(o,!0,n),u=xt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var uY={kernelName:Um,backendName:"cpu",kernelFunc:lY},pY=it(no,e=>Number.isFinite(e)?1:0,"bool"),cY={kernelName:no,backendName:"cpu",kernelFunc:pY},dY=it(ao,e=>Math.abs(e)===1/0?1:0,"bool"),hY={kernelName:ao,backendName:"cpu",kernelFunc:dY},mY=it(ro,e=>Number.isNaN(e)?1:0,"bool"),fY={kernelName:ro,backendName:"cpu",kernelFunc:mY};function gY(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=W_(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var bY={kernelName:$u,backendName:"cpu",kernelFunc:gY},yY=it(oo,e=>Math.log1p(e)),xY={kernelName:oo,backendName:"cpu",kernelFunc:yY},vY=Ot((e,t)=>e&&t),wY=Jt(Du,vY,null,"bool"),kY={kernelName:Du,backendName:"cpu",kernelFunc:wY},IY=it(Ru,e=>e?0:1,"bool"),SY={kernelName:Ru,backendName:"cpu",kernelFunc:IY},NY=Ot((e,t)=>e||t),TY=Jt(Mu,NY,null,"bool"),CY={kernelName:Mu,backendName:"cpu",kernelFunc:TY};function _Y(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;ge(r,"LRN");let u=r.shape[3],p=u-1,d=n.data.get(r.dataId).values,c=w.sizeFromShape(r.shape),h=new Float32Array(c);function m(f){let g=f%u,b=f-g+Math.max(0,g-s),y=f-g+Math.min(g+s,p),x=0;for(;b<=y;b++){let v=d[b];x+=v*v}return x}for(let f=0;f<c;f++){let g=m(f),b=d[f]*Math.pow(i+o*g,-l);h[f]=b}return n.makeTensorInfo(r.shape,r.dtype,h)}var EY={kernelName:lo,backendName:"cpu",kernelFunc:_Y};function AY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a;ge(i,"LRNGrad");let d=w.sizeFromShape(i.shape),c=i.shape[3],h=n.data.get(i.dataId).values,m=n.data.get(r.dataId).values,f=n.data.get(s.dataId).values,g=new Float32Array(d),b=d;for(let y=0;y<b;y++){let x=y%c,v=y-x+Math.max(0,x-o),I=y-x+Math.min(c,x+o+1),T=0;for(let C=v;C<I;C++)T+=Math.pow(m[C],2);T=u*T+l;for(let C=v;C<I;C++){let E=-2*u*p*m[C]*f[y]/T;y===C&&(E+=Math.pow(T,-p)),E*=h[y],g[C]+=E}}return n.makeTensorInfo(i.shape,r.dtype,g)}var FY={kernelName:Pu,backendName:"cpu",kernelFunc:AY};function xE(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=n,l=r.shape,u=l.length,p=w.parseAxisParam(s,l),d=p,c=N.getAxesPermutation(d,u),h=o.data.get(r.dataId).values;if(c!=null){let v=new Array(u);for(let I=0;I<v.length;I++)v[I]=l[c[I]];h=B1(h,l,r.dtype,c,v),d=N.getInnerMostAxes(d.length,u),l=v}ge(r,"max"),N.assertAxesAreInnerMostDims("max",d,u);let[m,f]=N.computeOutAndReduceShapes(l,d),g=w.sizeFromShape(f),b=V_(h,g,m,r.dtype),y=o.write(b,m,r.dtype),x=m;return i&&(x=N.expandShapeToKeepDim(m,p)),{dataId:y,shape:x,dtype:r.dtype}}var $Y={kernelName:uo,backendName:"cpu",kernelFunc:xE};function DY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;ge(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=N.computePool2DInfo(r.shape,s,i,u,o,l),d;if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))d=dr({inputs:{x:r},backend:n});else{let c=n.data.get(r.dataId).values,h=w.computeStrides(r.shape),m=X1(c,r.shape,r.dtype,h,p,"max");d=n.makeTensorInfo(p.outShape,r.dtype,m.values)}return d}var RY={kernelName:co,backendName:"cpu",kernelFunc:DY};function MY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a;ge(r,"maxPool3d");let p=N.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.data.get(r.dataId).values,c=fE(d,r.shape,r.dtype,w.computeStrides(r.shape),p,"max");return n.makeTensorInfo(c.shape,"float32",c.values)}var PY={kernelName:Ou,backendName:"cpu",kernelFunc:MY};function OY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a;ge([r,s],"maxPool3DGrad");let p=N.computePool3DInfo(s.shape,i,o,1,l,u),d=n.bufferSync(s),c=N8(d,p),h=p.strideDepth,m=p.strideHeight,f=p.strideWidth,g=p.dilationDepth,b=p.dilationHeight,y=p.dilationWidth,x=p.effectiveFilterDepth,v=p.effectiveFilterHeight,I=p.effectiveFilterWidth,T=x-1-p.padInfo.front,C=I-1-p.padInfo.left,E=v-1-p.padInfo.top,F=ze(s.shape,"float32"),D=n.bufferSync(r);for(let $=0;$<p.batchSize;++$)for(let S=0;S<p.inChannels;++S)for(let M=0;M<p.inDepth;++M)for(let B=0;B<p.inHeight;++B)for(let U=0;U<p.inWidth;++U){let H=M-T,j=B-E,K=U-C,Z=0;for(let J=0;J<x;J+=g){let ee=(H+J)/h;if(!(ee<0||ee>=p.outDepth||Math.floor(ee)!==ee))for(let ae=0;ae<v;ae+=b){let te=(j+ae)/m;if(!(te<0||te>=p.outHeight||Math.floor(te)!==te))for(let re=0;re<I;re+=y){let ie=(K+re)/f;if(ie<0||ie>=p.outWidth||Math.floor(ie)!==ie)continue;let ye=x*v*I-1-c.get($,ee,te,ie,S),ue=J*v*I+ae*I+re,be=ye===ue?1:0;if(be===0)continue;let ke=D.get($,ee,te,ie,S);Z+=ke*be}}}F.set(Z,$,M,B,U,S)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}var LY={kernelName:Hc,backendName:"cpu",kernelFunc:OY};function zY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;ge([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:d}=a,c=N.computePool2DInfo(o.shape,l,u,1,p,d),h=n.data.get(o.dataId).values,m=ze(c.outShape,o.dtype,mE(h,o.shape,o.dtype,c).values),f=c.strideHeight,g=c.strideWidth,b=c.dilationHeight,y=c.dilationWidth,x=c.effectiveFilterHeight,v=c.effectiveFilterWidth,I=v-1-c.padInfo.left,T=x-1-c.padInfo.top,C=ze(o.shape,"float32"),E=n.data.get(r.dataId).values,F=ze(r.shape,"float32",E);for(let D=0;D<c.batchSize;++D)for(let $=0;$<c.inChannels;++$)for(let S=0;S<c.inHeight;++S)for(let M=0;M<c.inWidth;++M){let B=S-T,U=M-I,H=0;for(let j=0;j<x;j+=b){let K=(B+j)/f;if(!(K<0||K>=c.outHeight||Math.floor(K)!==K))for(let Z=0;Z<v;Z+=y){let J=(U+Z)/g;if(J<0||J>=c.outWidth||Math.floor(J)!==J)continue;let ee=x*v-1-m.get(D,K,J,$),ae=j*v+Z,te=ee===ae?1:0;if(te===0)continue;let re=F.get(D,K,J,$);H+=re*te}}C.set(H,D,S,M,$)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var WY={kernelName:Gc,backendName:"cpu",kernelFunc:zY};function BY(e,t,n,a,r){let s=w.computeStrides(t),i=X1(e,t,n,s,r,"max"),o=mE(e,t,n,r,!0,a);return[i.values,o.values]}var VY={kernelName:qc,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;ge(a,"MaxPoolWithArgmax");let u=l.data.get(a.dataId).values,p=N.computePool2DInfo(a.shape,r,s,[1,1],i),[d,c]=BY(u,a.shape,a.dtype,o,p),h=l.write(d,p.outShape,a.dtype),m=l.write(c,p.outShape,a.dtype);return[{dataId:h,shape:p.outShape,dtype:a.dtype},{dataId:m,shape:p.outShape,dtype:"int32"}]}};function UY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=w.parseAxisParam(s,r.shape),l=N.computeOutAndReduceShapes(r.shape,o)[1],u=w.sizeFromShape(l),p=[],d=n.makeTensorInfo([],"float32",new Float32Array([u]));p.push(d);let c=vs({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});p.push(c);let h=Y1({inputs:{a:c,b:d},backend:n});p.push(h);let m=Rd({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:i}});return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var GY={kernelName:ho,backendName:"cpu",kernelFunc:UY};function HY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"min");let o=w.parseAxisParam(s,r.shape),l=o,u=N.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=Un({inputs:{x:r},backend:n,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,r.shape.length)),N.assertAxesAreInnerMostDims("min",l,p.shape.length);let[d,c]=N.computeOutAndReduceShapes(p.shape,l),h=w.sizeFromShape(c),m=w.makeZerosTypedArray(w.sizeFromShape(d),p.dtype),f=n.data.get(p.dataId).values;for(let b=0;b<m.length;++b){let y=b*h,x=f[y];for(let v=0;v<h;++v){let I=f[y+v];(Number.isNaN(I)||I<x)&&(x=I)}m[b]=x}u!=null&&n.disposeIntermediateTensorInfo(p);let g=n.makeTensorInfo(d,p.dtype,m);if(i){let b=N.expandShapeToKeepDim(d,o),y=xt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var qY={kernelName:mo,backendName:"cpu",kernelFunc:HY};function jY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,mode:i}=a;ge(r,"mirrorPad");let o=s.map((y,x)=>y[0]+r.shape[x]+y[1]),l=s.map(y=>y[0]),u=s.map((y,x)=>y[0]+r.shape[x]),p=i==="reflect"?0:1,d=n.data.get(r.dataId).values,c=r.shape.length,h=w.computeStrides(r.shape),m=w.sizeFromShape(o),f=o.length,g=w.computeStrides(o),b=w.getTypedArrayFromDType(r.dtype,m);for(let y=0;y<m;y++){let x=w.indexToLoc(y,f,g);for(let I=0;I<f;I++)x[I]<l[I]?x[I]=l[I]*2-x[I]-p:x[I]>=u[I]&&(x[I]=(u[I]-1)*2-x[I]+p);x=x.map((I,T)=>I-l[T]);let v=w.locToIndex(x,c,h);b[y]=d[v]}return{dataId:n.write(b,o,r.dtype),shape:o,dtype:r.dtype}}var KY={kernelName:go,backendName:"cpu",kernelFunc:jY},XY=Ot((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),YY=Jt(bo,XY),ZY={kernelName:bo,backendName:"cpu",kernelFunc:YY},JY=ks(Dm());function vE(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=r.shape.length,o=s;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);let l=w.parseAxisParam([o],r.shape),u=xE({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),p=N.expandShapeToKeepDim(u.shape,l),d=xt({inputs:{x:u},backend:n,attrs:{shape:p}}),c=j1({inputs:{a:r,b:d},backend:n}),h=A_({inputs:{x:c},backend:n}),m=Rd({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),f=xt({inputs:{x:m},backend:n,attrs:{shape:p}}),g=Y1({inputs:{a:h,b:f},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var QY={kernelName:Wo,backendName:"cpu",kernelFunc:vE};function e7(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;ge(r,"multinomial");let l=o?r:vE({inputs:{logits:r},backend:n,attrs:{dim:-1}}),u=l.shape[0],p=l.shape[1],d=n.data.get(l.dataId).values,c=[u,s],h=w.makeZerosTypedArray(w.sizeFromShape(c),"int32");for(let m=0;m<u;++m){let f=m*p,g=new Float32Array(p-1);g[0]=d[f];for(let x=1;x<g.length;++x)g[x]=g[x-1]+d[f+x];let b=JY.alea(i.toString()),y=m*s;for(let x=0;x<s;++x){let v=b();h[y+x]=g.length;for(let I=0;I<g.length;I++)if(v<g[I]){h[y+x]=I;break}}}return o||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(c,"int32",h)}var t7={kernelName:Lu,backendName:"cpu",kernelFunc:e7},n7=gr.nonMaxSuppressionV3Impl;function a7(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a;ge(r,"NonMaxSuppression");let u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,{selectedIndices:d}=n7(u,p,i,o,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var r7={kernelName:Bu,backendName:"cpu",kernelFunc:a7},s7=gr.nonMaxSuppressionV4Impl;function i7(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=a;ge(r,"NonMaxSuppressionPadded");let p=n.data.get(r.dataId).values,d=n.data.get(s.dataId).values,{selectedIndices:c,validOutputs:h}=s7(p,d,i,o,l,u);return[n.makeTensorInfo([c.length],"int32",new Int32Array(c)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var o7={kernelName:Vu,backendName:"cpu",kernelFunc:i7},l7=gr.nonMaxSuppressionV5Impl;function u7(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=a;ge(r,"NonMaxSuppressionWithScore");let p=n.data.get(r.dataId).values,d=n.data.get(s.dataId).values,c=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:b}=l7(p,d,c,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var p7={kernelName:Uu,backendName:"cpu",kernelFunc:u7};function c7(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=a;ge(r,"oneHot");let u=w.sizeFromShape(r.shape),p=new Float32Array(u*i);p.fill(l);let d=n.data.get(r.dataId).values;for(let c=0;c<u;++c)d[c]>=0&&d[c]<i&&(p[c*i+d[c]]=o);return n.makeTensorInfo([...r.shape,i],s,p)}var d7={kernelName:xo,backendName:"cpu",kernelFunc:c7};function _m(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(a.dtype==="complex64"){let r=xi({inputs:{input:a},backend:n}),s=_m({inputs:{x:r},backend:n}),i=su({inputs:{input:a},backend:n}),o=_m({inputs:{x:i},backend:n}),l=Jn({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Z1({backend:n,attrs:{shape:a.shape,value:0,dtype:a.dtype}})}var h7={kernelName:lp,backendName:"cpu",kernelFunc:_m};function wE(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(a.dtype==="complex64"){let r=xi({inputs:{input:a},backend:n}),s=wE({inputs:{x:r},backend:n}),i=su({inputs:{input:a},backend:n}),o=_m({inputs:{x:i},backend:n}),l=Jn({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Z1({backend:n,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}var m7={kernelName:Gu,backendName:"cpu",kernelFunc:wE};function kE(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return Cm({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=Cm({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=iu({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var f7={kernelName:Hu,backendName:"cpu",kernelFunc:kE};function g7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;ge(r,"pad");let o=s.map((b,y)=>b[0]+r.shape[y]+b[1]),l=s.map(b=>b[0]),u=n.data.get(r.dataId).values,p=w.sizeFromShape(r.shape),d=r.shape.length,c=w.computeStrides(r.shape),h=w.sizeFromShape(o),m=o.length,f=w.computeStrides(o),g=w.getTypedArrayFromDType(r.dtype,h);i!==0&&g.fill(i);for(let b=0;b<p;b++){let y=w.indexToLoc(b,d,c).map((v,I)=>v+l[I]),x=w.locToIndex(y,m,f);g[x]=u[b]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var IE={kernelName:vo,backendName:"cpu",kernelFunc:g7},b7=Ot((e,t)=>Math.pow(e,t)),y7=Jt(wo,b7),x7={kernelName:wo,backendName:"cpu",kernelFunc:y7};function v7(e){let{inputs:t,backend:n,attrs:a}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=a,l=r.map(b=>n.data.get(b.dataId).values),u=r.map(b=>b.shape),p=n.data.get(s.dataId).values,d=n.data.get(i.dataId).values,[c,h,m]=K_(l,u,p,s.shape,s.dtype,d,i.shape,o),f=c.map(b=>n.makeTensorInfo([b.length],"int32",b)),g=n.makeTensorInfo(m,s.dtype,h);return f.concat([g])}var w7={kernelName:Hm,backendName:"cpu",kernelFunc:v7};function k7(e){let{inputs:t,backend:n}=e,{starts:a,limits:r,deltas:s}=t,i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=X_(i,a.shape,a.dtype,o,r.shape,l,s.shape),d=n.makeTensorInfo([u.length],"int32",u),c=n.makeTensorInfo([p.length],a.dtype,p);return[d,c]}var I7={kernelName:qm,backendName:"cpu",kernelFunc:k7};function S7(e){let{inputs:t,backend:n,attrs:a}=e,{shape:r,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=a,u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,d=n.data.get(i.dataId).values,c=o.map(g=>n.data.get(g.dataId).values),h=o.map(g=>g.shape),[m,f]=Y_(u,r.shape,p,s.shape,s.dtype,d,i.shape,c,h,l);return n.makeTensorInfo(m,s.dtype,f)}var N7={kernelName:jm,backendName:"cpu",kernelFunc:S7};function T7(e){let{backend:t,attrs:n}=e,{start:a,stop:r,dtype:s,step:i}=n,o=V1(a,r,i,s);return t.makeTensorInfo([o.length],s,o)}var C7={kernelName:jc,backendName:"cpu",kernelFunc:T7},_7=it(So,e=>1/e),E7={kernelName:So,backendName:"cpu",kernelFunc:_7};function A7(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;ge(r,"resizeBilinear");let l=w.computeStrides(r.shape),[u,p]=o,[d,c,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(w.sizeFromShape([d,u,p,m])),b=[s&&u>1?c-1:c,s&&p>1?h-1:h],y=[s&&u>1?u-1:u,s&&p>1?p-1:p],x=0,v=b[0]/y[0],I=b[1]/y[1];for(let T=0;T<d;T++)for(let C=0;C<u;C++){let E;i?E=v*(C+.5)-.5:E=v*C;let F=Math.max(0,Math.floor(E)),D=E-F,$=Math.min(c-1,Math.ceil(E)),S=T*l[0]+F*l[1],M=T*l[0]+$*l[1];for(let B=0;B<p;B++){let U;i?U=I*(B+.5)-.5:U=I*B;let H=Math.max(0,Math.floor(U)),j=U-H,K=Math.min(h-1,Math.ceil(U)),Z=S+H*l[2],J=M+H*l[2],ee=S+K*l[2],ae=M+K*l[2];for(let te=0;te<m;te++){let re=f[Z+te],ie=f[J+te],ye=f[ee+te],ue=f[ae+te],be=re+(ye-re)*j,ke=ie+(ue-ie)*j,Se=be+(ke-be)*D;g[x++]=Se}}}return n.makeTensorInfo([d,u,p,m],"float32",g)}var F7={kernelName:Co,backendName:"cpu",kernelFunc:A7};function $7(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;ge([s,r],"resizeBilinearGrad");let o=w.computeStrides(r.shape),[l,u,p,d]=r.shape,[,c,h]=s.shape,m=new Float32Array(l*u*p*d),f=[i&&c>1?u-1:u,i&&h>1?p-1:p],g=[i&&c>1?c-1:c,i&&h>1?h-1:h],b=f[0]/g[0],y=f[1]/g[1],x=n.data.get(s.dataId).values,v=0;for(let I=0;I<l;I++){let T=I*o[0];for(let C=0;C<c;C++){let E=C*b,F=Math.floor(E),D=Math.min(Math.ceil(E),u-1),$=T+F*o[1],S=T+D*o[1],M=E-F,B=1-M;for(let U=0;U<h;U++){let H=U*y,j=Math.floor(H),K=Math.min(Math.ceil(H),p-1),Z=H-j,J=1-Z,ee=$+j*o[2],ae=$+K*o[2],te=S+j*o[2],re=S+K*o[2],ie=B*J,ye=B*Z,ue=M*J,be=M*Z;for(let ke=0;ke<d;ke++){let Se=x[v++];m[ee+ke]+=Se*ie,m[ae+ke]+=Se*ye,m[te+ke]+=Se*ue,m[re+ke]+=Se*be}}}}return n.makeTensorInfo([l,p,u,d],"float32",m)}var D7={kernelName:Ku,backendName:"cpu",kernelFunc:$7};function R7(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;ge(r,"resizeNearestNeighbor");let l=w.computeStrides(r.shape),[u,p]=o,[d,c,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(d*u*p*m),b=[s&&u>1?c-1:c,s&&p>1?h-1:h],y=[s&&u>1?u-1:u,s&&p>1?p-1:p],x=b[0]/y[0],v=b[1]/y[1],I=0;for(let T=0;T<d;T++){let C=T*l[0];for(let E=0;E<u;E++){let F=i?x*(E+.5):x*E,D=Math.min(c-1,s?Math.round(F):Math.floor(F));i&&(D=Math.max(0,D));let $=C+D*l[1];for(let S=0;S<p;S++){let M=i?v*(S+.5):v*S,B=Math.min(h-1,s?Math.round(M):Math.floor(M));i&&(B=Math.max(0,B));let U=$+B*l[2];for(let H=0;H<m;H++){let j=f[U+H];g[I++]=j}}}}return n.makeTensorInfo([d,u,p,m],r.dtype,g)}var M7={kernelName:To,backendName:"cpu",kernelFunc:R7};function P7(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;ge([s,r],"resizeNearestNeighborGrad");let o=w.computeStrides(r.shape),l=w.computeStrides(s.shape),[u,p,d,c]=r.shape,[,h,m]=s.shape,f=new Float32Array(u*p*d*c),g=n.data.get(s.dataId).values,b=[i&&h>1?p-1:p,i&&m>1?d-1:d],y=[i&&h>1?h-1:h,i&&m>1?m-1:m],x=b[0]/y[0],v=b[1]/y[1],I=1/x,T=1/v,C=Math.ceil(I)*2+2,E=Math.ceil(T)*2+2;for(let F=0;F<u;F++){let D=F*o[0];for(let $=0;$<p;$++){let S=D+$*o[1],M=Math.floor($*I),B=Math.floor(M-C/2);for(let U=0;U<d;U++){let H=S+U*o[2],j=Math.floor(U*T),K=Math.floor(j-E/2);for(let Z=0;Z<c;Z++){let J=0;for(let ee=0;ee<C;ee++){let ae=ee+B;if(ae<0||ae>=h)continue;let te=D+ae*l[1],re=ae*x,ie=Math.min(p-1,i?Math.round(re):Math.floor(re));if($===ie)for(let ye=0;ye<E;ye++){let ue=ye+K;if(ue<0||ue>=m)continue;let be=te+ue*l[2],ke=ue*v,Se=Math.min(d-1,i?Math.round(ke):Math.floor(ke));U===Se&&(J+=g[be+Z])}}f[H+Z]=J}}}}return n.makeTensorInfo(r.shape,r.dtype,f)}var O7={kernelName:ju,backendName:"cpu",kernelFunc:P7};function L7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a;ge(r,"reverse");let i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return dr({inputs:{x:r},backend:n});let l=new Vt(r.shape,r.dtype),u=n.bufferSync(r);for(let p=0;p<l.size;p++){let d=l.indexToLoc(p),c=d.slice();o.forEach(h=>c[h]=r.shape[h]-1-c[h]),l.set(u.get(...c),...d)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var z7={kernelName:Eo,backendName:"cpu",kernelFunc:L7},W7={kernelName:up,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[u,p,d,c]=a.shape,[h,m]=N.getImageCenter(i,p,d),f=255,g=Math.sin(r),b=Math.cos(r),y=o.data.get(a.dataId).values;for(let x=0;x<u;x++){let v=x*d*p*c;for(let I=0;I<p;I++){let T=I*(d*c);for(let C=0;C<d;C++){let E=C*c;for(let F=0;F<c;F++){let D=[u,I,C,F],$=D[2],S=D[1],M=($-h)*b-(S-m)*g,B=($-h)*g+(S-m)*b;M=Math.round(M+h),B=Math.round(B+m);let U=s;if(typeof s!="number"&&(F===3?U=f:U=s[F]),M>=0&&M<d&&B>=0&&B<p){let j=B*(d*c),K=M*c,Z=v+j+K+F;U=y[Z]}let H=v+T+E+F;l[H]=U}}}}return{dataId:o.write(l,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},B7=it(Ao,e=>{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),V7={kernelName:Ao,backendName:"cpu",kernelFunc:B7};function U7(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=N.calculateShapes(s,r,i),c=!0,h=n.bufferSync(r),m=n.bufferSync(s),f=ai(h,m,i,d,u,l,o,p,0,c);return n.makeTensorInfo(i,f.dtype,f.values)}var G7={kernelName:Xu,backendName:"cpu",kernelFunc:U7};function H7(e,t){let n=0,a=e.length,r=0;for(;n<a;)r=Math.floor((n+a)/2),e[r]<t?n=r+1:a=r;return a}function q7(e,t){let n=0,a=e.length,r=0;for(;n<a;)r=Math.floor((n+a)/2),e[r]<=t?n=r+1:a=r;return a}function j7(e,t,n,a,r,s){let i=w.getArrayFromDType("int32",n*r);for(let o=0;o<n;++o){let l=e.slice(o*a,(o+1)*a),u=o*r;for(let p=0;p<r;++p)i[u+p]=s==="left"?H7(l,t[p+u]):q7(l,t[p+u])}return i}function K7(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=j7(o,l,r.shape[0],r.shape[1],s.shape[1],i);return n.makeTensorInfo(s.shape,"int32",u)}var X7={kernelName:Zu,backendName:"cpu",kernelFunc:K7};function Y7(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t;ge([a,r,s],"select");let i=a.shape.length,o=n.data.get(a.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=ba(r.dtype,s.dtype),d=w.makeZerosTypedArray(w.sizeFromShape(r.shape),p),c=0,h=i===0||i>1||r.shape.length===1?1:w.sizeFromShape(r.shape.slice(1));for(let m=0;m<o.length;m++)for(let f=0;f<h;f++)o[m]===1?d[c++]=l[m]:d[c++]=u[m];return n.makeTensorInfo(r.shape,p,d)}var Z7={kernelName:Ju,backendName:"cpu",kernelFunc:Y7},J7=N.SELU_SCALEALPHA,Q7=N.SELU_SCALE,eZ=it($o,e=>e>=0?Q7*e:J7*(Math.exp(e)-1)),tZ={kernelName:$o,backendName:"cpu",kernelFunc:eZ},nZ=it(Mo,e=>e<0?-1:e>0?1:0),aZ={kernelName:Mo,backendName:"cpu",kernelFunc:nZ},rZ=it(Do,e=>Math.sin(e)),sZ={kernelName:Do,backendName:"cpu",kernelFunc:rZ},iZ=it(Ro,e=>Math.sinh(e)),oZ={kernelName:Ro,backendName:"cpu",kernelFunc:iZ},lZ=11920928955078125e-23,dS=Math.log(lZ)+2,uZ=it(Oo,e=>{let t=e>-dS,n=e<dS,a=Math.exp(e),r;return n?r=a:t?r=e:r=Math.log(1+a),r}),pZ={kernelName:Oo,backendName:"cpu",kernelFunc:uZ};function cZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;ge([r],"spaceToBatchND");let o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let u=IE.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=N.getReshaped(u.shape,s,o,!1),d=N.getPermuted(p.length,s.length,!1),c=N.getReshapedPermuted(u.shape,s,o,!1),h=xt({inputs:{x:u},backend:n,attrs:{shape:p}}),m=Un({inputs:{x:h},backend:n,attrs:{perm:d}}),f=xt({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}var dZ={kernelName:ep,backendName:"cpu",kernelFunc:cZ};function hZ(e){let{inputs:t,backend:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
        ${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
        ${a.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
        ${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
        ${i.shape}`);let o=n.data.get(a.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=n.data.get(i.dataId).values[0],[d,c,h,m,f]=Q_(o,a.shape,a.dtype,l,r.dtype,u,p);return[n.makeTensorInfo(c,a.dtype,d),n.makeTensorInfo([c[0]],r.dtype,h),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var mZ={kernelName:Kc,backendName:"cpu",kernelFunc:hZ};function fZ(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
        ${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
        ${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(n.data.get(r.dataId).values),o=n.data.get(a.dataId).values,l=Array.from(n.data.get(s.dataId).values),[u,p,d]=eE(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(p,a.dtype,u),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var gZ={kernelName:np,backendName:"cpu",kernelFunc:fZ};function bZ(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
          ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
          ${s.shape}`);if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=U1(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(p,a.dtype,u)}var yZ={kernelName:Xc,backendName:"cpu",kernelFunc:bZ};function xZ(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
         ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
         ${s.shape}`);if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=U1(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(p,a.dtype,u)}var vZ={kernelName:Yc,backendName:"cpu",kernelFunc:xZ};function wZ(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=N.calculateShapes(s,r,o),h=!1,m=n.bufferSync(r),f;switch(s.dtype){case"bool":{let g=n.bufferSync(s),b=!!n.data.get(i.dataId).values[0];f=ai(m,g,o,c,p,u,l,d,b,h);break}case"float32":{let g=n.bufferSync(s),b=n.data.get(i.dataId).values[0];f=ai(m,g,o,c,p,u,l,d,b,h);break}case"int32":{let g=n.bufferSync(s),b=n.data.get(i.dataId).values[0];f=ai(m,g,o,c,p,u,l,d,b,h);break}case"string":{let g=n.bufferSync(s),b=w.decodeString(n.data.get(i.dataId).values[0]);f=ai(m,g,o,c,p,u,l,d,b,h);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return n.makeTensorInfo(o,f.dtype,f.values)}var kZ={kernelName:ap,backendName:"cpu",kernelFunc:wZ};function IZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=N.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(d=>{let c=[...p];c[o]=d;let h=vi({inputs:{x:r},backend:n,attrs:{begin:u,size:c}});return u[o]+=d,h})}var SZ={kernelName:tp,backendName:"cpu",kernelFunc:IZ},NZ={kernelName:Zc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;ge(n,"square");let r=a.data.get(n.dataId).values,s=new Float32Array(r.length);for(let i=0;i<r.length;++i){let o=r[i];s[i]=o*o}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},TZ=it(Ts,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),CZ={kernelName:Ts,backendName:"cpu",kernelFunc:TZ};function _Z(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a;ge(r,"stridedSlice");let{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:b,begin:y,end:x,strides:v}=Xt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),I;if(f)I=xt({inputs:{x:r},backend:n,attrs:{shape:m}});else if(g||b){w.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let T=Xt.computeOutShape(y,x,v),C=vi({inputs:{x:r},backend:n,attrs:{begin:y,size:T}});I=xt({inputs:{x:C},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(C)}else{let T=n.bufferSync(r),C=aE(h,T,v,y);I=n.makeTensorInfo(m,C.dtype,C.values)}return I}var EZ={kernelName:rp,backendName:"cpu",kernelFunc:_Z};function AZ(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:p,dataSplits:d}=t,c=n.data.get(p.dataId).values,h=n.data.get(d.dataId).values,[m,f]=G1(c,h,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(d.shape,"int32",f)]}var FZ={kernelName:Qc,backendName:"cpu",kernelFunc:AZ};function $Z(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{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 o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values[0],[u,p,d]=H1(o,l,r),c=p.length;return[n.makeTensorInfo([c,2],"int32",u),n.makeTensorInfo([c],"string",p),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var DZ={kernelName:ed,backendName:"cpu",kernelFunc:$Z};function RZ(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.data.get(s.dataId).values,o=q1(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var MZ={kernelName:td,backendName:"cpu",kernelFunc:RZ},PZ=it(Uo,e=>Math.tan(e)),OZ={kernelName:Uo,backendName:"cpu",kernelFunc:PZ},LZ=it(Go,e=>Math.tanh(e)),zZ={kernelName:Go,backendName:"cpu",kernelFunc:LZ};function WZ(e){let{inputs:t,backend:n}=e,{tensor:a,indices:r,updates:s}=t,{sliceRank:i,numUpdates:o,sliceSize:l,strides:u,outputSize:p}=N.calculateShapes(s,r,a.shape),d=!1,c=n.bufferSync(r),h=n.bufferSync(s),m=n.bufferSync(a),f=ai(c,h,a.shape,p,l,o,i,u,m,d);return n.makeTensorInfo(a.shape,f.dtype,f.values)}var BZ={kernelName:Yu,backendName:"cpu",kernelFunc:WZ};function VZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;ge(r,"tile");let i=sE(n.bufferSync(r),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}var UZ={kernelName:Ns,backendName:"cpu",kernelFunc:VZ};function GZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a;ge(r,"topk");let o=n.data.get(r.dataId).values,[l,u]=oE(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}var HZ={kernelName:sp,backendName:"cpu",kernelFunc:GZ};function qZ(e){let{inputs:t,attrs:n,backend:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],b=w.computeStrides(r.shape),y=b[0],x=b[1],v=b[2],I=w.computeStrides(g),T=I[0],C=I[1],E=I[2],F=w.getTypedArrayFromDType(r.dtype,w.sizeFromShape(g));F.fill(l);let D=a.data.get(r.dataId).values,$=a.data.get(s.dataId).values;for(let S=0;S<p;++S){let M=s.shape[0]===1?$:$.subarray(S*8,S*8+8);for(let B=0;B<m;++B)for(let U=0;U<f;++U)for(let H=0;H<h;++H){let j,K=M[6]*U+M[7]*B+1;if(K===0)continue;let Z=(M[0]*U+M[1]*B+M[2])/K,J=(M[3]*U+M[4]*B+M[5])/K,ee=hS(Z,c,o),ae=hS(J,d,o);switch(i){case"nearest":j=JZ(D,d,c,y,x,v,S,ae,ee,H,l);break;case"bilinear":j=QZ(D,d,c,y,x,v,S,ae,ee,H,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let te=S*T+B*C+U*E+H;F[te]=j}return a.makeTensorInfo(g,r.dtype,F)}return{dataId:a.write(F,g,r.dtype),shape:r.shape,dtype:r.dtype}}var jZ={kernelName:ip,backendName:"cpu",kernelFunc:qZ};function hS(e,t,n){switch(n){case"reflect":return KZ(e,t);case"wrap":return XZ(e,t);case"nearest":return ZZ(e,t);case"constant":default:return YZ(e,t)}}function KZ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let a=2*t;n<a&&(n=a*Math.trunc(-n/a)+n),n=n<-t?n+a:-n-1}else if(n>t-1)if(t<=1)n=0;else{let a=2*t;n-=a*Math.trunc(n/a),n>=t&&(n=a-n-1)}return w.clamp(0,n,t-1)}function XZ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let a=t-1;n+=t*(Math.trunc(-n/a)+1)}else if(n>t-1)if(t<=1)n=0;else{let a=t-1;n-=t*Math.trunc(n/a)}return w.clamp(0,n,t-1)}function YZ(e,t){return e}function ZZ(e,t){return w.clamp(0,e,t-1)}function oc(e,t,n,a,r,s,i,o,l,u,p){let d=i*a+o*r+l*s+u;return 0<=o&&o<t&&0<=l&&l<n?e[d]:p}function JZ(e,t,n,a,r,s,i,o,l,u,p){let d=Math.round(o),c=Math.round(l);return oc(e,t,n,a,r,s,i,d,c,u,p)}function QZ(e,t,n,a,r,s,i,o,l,u,p){let d=Math.floor(o),c=Math.floor(l),h=d+1,m=c+1,f=(m-l)*oc(e,t,n,a,r,s,i,d,c,u,p)+(l-c)*oc(e,t,n,a,r,s,i,d,m,u,p),g=(m-l)*oc(e,t,n,a,r,s,i,h,c,u,p)+(l-c)*oc(e,t,n,a,r,s,i,h,m,u,p);return(h-o)*f+(o-d)*g}function eJ(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;ge(s,"unique");let i=a.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:u}=K1(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([u.length],"int32",u)]}var tJ={kernelName:nd,backendName:"cpu",kernelFunc:eJ};function nJ(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r.shape.length,o=r.shape[s],l=new Array(i-1),u=0;for(let h=0;h<i;h++)h!==s&&(l[u++]=r.shape[h]);let p=new Array(i).fill(0),d=r.shape.slice();d[s]=1;let c=new Array(o);for(let h=0;h<c.length;h++){p[s]=h;let m=vi({inputs:{x:r},backend:n,attrs:{begin:p,size:d}});c[h]=xt({inputs:{x:m},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(m)}return c}var aJ={kernelName:op,backendName:"cpu",kernelFunc:nJ};function rJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a;ge(r,"unsortedSegmentSum");let o=r.shape.length,l=s.shape.length,u=[],p=[],d=o-l,c=s;for(let m=0;m<d;++m){let f=Cm({inputs:{input:c},backend:n,attrs:{dim:m+1}});c=f,p.push(f)}for(let m=0;m<i;++m){let f=w.createScalarValue(m,"int32"),g=n.makeTensorInfo([],"int32",f),b=__({inputs:{a:g,b:c},backend:n}),y=vs({inputs:{x:b},backend:n,attrs:{dtype:"float32"}}),x=Zf({inputs:{a:y,b:r},backend:n}),v=Rd({inputs:{x},backend:n,attrs:{axis:0,keepDims:!1}});u.push(v),p.push(g),p.push(b),p.push(y),p.push(x),p.push(v)}let h=kE({inputs:u,backend:n,attrs:{axis:0}});return p.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var sJ={kernelName:ad,backendName:"cpu",kernelFunc:rJ},iJ=[QK,D5,t8,a8,z5,s8,o8,u8,c8,h8,f8,b8,x8,k8,S8,C8,E8,F8,D8,ZK,M8,O8,z8,B5,B8,O5,U5,U8,R5,H8,j8,K8,Y8,J8,eX,nX,rX,iX,lX,pX,dX,mX,gX,yX,xX,wX,IX,NX,TX,CX,_X,AX,DX,GK,MX,G5,UX,H5,GX,j5,YX,ZX,QX,X5,Z5,tY,aY,sY,oY,Q5,tK,M5,uY,q8,cY,hY,fY,HK,aK,sK,bY,oK,xY,kY,SY,CY,EY,FY,$Y,uK,RY,PY,LY,WY,VY,GY,qY,cK,KY,ZY,t7,hK,fK,r7,o7,p7,bK,d7,m7,f7,IE,x7,jK,vK,w7,I7,N7,C7,P5,pv,E7,KK,XK,YK,F7,D7,M7,O7,z7,W7,V7,_K,G7,X7,Z7,tZ,AK,aZ,sZ,oZ,FK,QY,pZ,dZ,mZ,gZ,yZ,vZ,kZ,SZ,RK,NZ,PK,LK,CZ,EZ,FZ,DZ,MZ,VK,FX,OZ,zZ,BZ,UZ,HZ,jZ,yK,tJ,aJ,sJ,h7];for(let e of iJ)rd(e);var SE={};Ee(SE,{assertNotComplex:()=>vp,bindCanvasToFramebuffer:()=>bJ,bindColorTextureToFramebuffer:()=>Jh,bindTextureToProgramUniformSampler:()=>WE,bindTextureUnit:()=>OE,bindVertexBufferToProgramAttribute:()=>dv,callAndCheck:()=>de,canBeRepresented:()=>TE,createFragmentShader:()=>EE,createFramebuffer:()=>PE,createProgram:()=>AE,createStaticIndexBuffer:()=>DE,createStaticVertexBuffer:()=>$E,createTexture:()=>RE,createVertexShader:()=>_E,getBatchDim:()=>wi,getExtensionOrThrow:()=>lc,getFramebufferErrorMessage:()=>BE,getMaxTexturesInShader:()=>HE,getNumChannels:()=>fJ,getProgramUniformLocation:()=>zE,getProgramUniformLocationOrThrow:()=>LE,getRowsCols:()=>ki,getShapeAs3D:()=>pc,getTextureShapeFromLogicalShape:()=>UE,getWebGLDisjointQueryTimerVersion:()=>qE,getWebGLErrorMessage:()=>CE,getWebGLMaxTextureSize:()=>GE,hasExtension:()=>ma,isCapableOfRenderingToFloatTexture:()=>jE,isDownloadFloatTextureEnabled:()=>KE,isReshapeFree:()=>Ac,isWebGLFenceEnabled:()=>XE,isWebGLVersionEnabled:()=>mv,linkProgram:()=>FE,logShaderSourceAndInfoLog:()=>Q1,resetMaxTextureSize:()=>yJ,resetMaxTexturesInShader:()=>xJ,unbindColorTextureFromFramebuffer:()=>hv,unbindTextureUnit:()=>gJ,validateFramebuffer:()=>uc,validateProgram:()=>Zh,validateTextureSize:()=>ME});var ei={},Gh={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function NE(e,t){ei[e]=t}function Ka(e,t){if(!(e in ei)||t!=null){let a=lJ(e,t);if(a!==null)ei[e]=a;else return console.log("Could not get context for WebGL version",e),null}let n=ei[e];return n==null||n.isContextLost()?(delete ei[e],Ka(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),ei[e])}function oJ(e){if(!G().getBool("IS_SAFARI")&&typeof OffscreenCanvas!="undefined"&&e===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 lJ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let n=t==null?oJ(e):t;return n.addEventListener("webglcontextlost",a=>{a.preventDefault(),delete ei[e]},!1),G().getBool("SOFTWARE_WEBGL_ENABLED")&&(Gh.failIfMajorPerformanceCaveat=!1),e===1?n.getContext("webgl",Gh)||n.getContext("experimental-webgl",Gh):n.getContext("webgl2",Gh)}var Ec;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(Ec||(Ec={}));var ha;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(ha||(ha={}));var hn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(hn||(hn={}));function Md(e,t){return[t,e]}function uJ(e,t){return e*t}function Hh(e){let t=w.sizeFromShape(e),n=Math.ceil(t/4);return w.sizeToSquarishShape(n)}function xp(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function pJ(e,t){let[n,a]=xp(e,t);return n*a*4}function J1(e,t){let n=e,a,r,s,i,o,l,u,p,d,c;return G().getNumber("WEBGL_VERSION")===2?(a=n.R32F,r=n.R16F,s=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,p=1,d=n.HALF_FLOAT,c=n.FLOAT,l=n.RGBA8):(a=e.RGBA,r=e.RGBA,s=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,p=4,d=t!=null?t.HALF_FLOAT_OES:null,c=e.FLOAT,l=e.RGBA),{internalFormatFloat:a,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:p,textureTypeHalfFloat:d,textureTypeFloat:c}}function de(e,t){let n=t();return G().getBool("DEBUG")&&cJ(e),n}function cJ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+CE(e,t))}var dJ=596e-10,hJ=65504;function TE(e){return!!(G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||dJ<Math.abs(e)&&Math.abs(e)<hJ)}function CE(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function lc(e,t){return Wr(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function _E(e,t){let n=Wr(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(de(e,()=>e.shaderSource(n,t)),de(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function EE(e,t){let n=Wr(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(de(e,()=>e.shaderSource(n,t)),de(e,()=>e.compileShader(n)),G().get("ENGINE_COMPILE_ONLY"))return n;if(e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw Q1(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var mJ=/ERROR: [0-9]+:([0-9]+):/g;function Q1(e,t){let n=mJ.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let a=+n[1],r=e.split(`
`),s=r.length.toString().length+2,i=r.map((d,c)=>w.rightPad((c+1).toString(),s)+d),o=0;for(let d=0;d<i.length;d++)o=Math.max(i[d].length,o);let l=i.slice(0,a-1),u=i.slice(a-1,a),p=i.slice(a);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${w.rightPad(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
`))}function AE(e){return Wr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function FE(e,t){if(de(e,()=>e.linkProgram(t)),!G().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Zh(e,t){if(de(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function $E(e,t){let n=Wr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),de(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function DE(e,t){let n=Wr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return de(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),de(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function fJ(){return G().getNumber("WEBGL_VERSION")===2?1:4}function RE(e){return Wr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function ME(e,t){let n=G().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a=`[${e}x${t}]`;throw new Error("Requested texture size "+a+" is invalid.")}if(e>n||t>n){let a=`[${e}x${t}]`,r=`[${n}x${n}]`;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+r+".")}}function PE(e){return Wr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function dv(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),de(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),de(e,()=>e.enableVertexAttribArray(o)),!0)}function OE(e,t,n){VE(e,n),de(e,()=>e.activeTexture(e.TEXTURE0+n)),de(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function gJ(e,t){VE(e,t),de(e,()=>e.activeTexture(e.TEXTURE0+t)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function LE(e,t,n){return Wr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function zE(e,t,n){return e.getUniformLocation(t,n)}function WE(e,t,n,a){de(e,()=>OE(e,t,a)),de(e,()=>e.uniform1i(n,a))}function bJ(e){de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),de(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),de(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function Jh(e,t,n){de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),de(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function hv(e,t){de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),de(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function uc(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+BE(e,t))}function BE(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function Wr(e,t,n){let a=de(e,()=>t());if(a==null)throw new Error(n);return a}function VE(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(a<e.TEXTURE0||a>n){let r=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${r}.`)}}function wi(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function ki(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function pc(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[wi(e),...ki(e)]),t}function UE(e,t=!1){let n=G().getNumber("WEBGL_MAX_TEXTURE_SIZE"),a=G().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");a===1/0&&G().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(a=n/2),t&&(n=n*2,a=a*2,e=e.map((o,l)=>l>=e.length-2?w.nearestLargerEven(e[l]):e[l]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let r=w.sizeFromShape(e),s=null;e.length<=1&&r<=n?s=[1,r]:e.length===2&&e[0]<=n&&e[1]<=n?s=e:e.length===3&&e[0]*e[1]<=n&&e[2]<=n?s=[e[0]*e[1],e[2]]:e.length===3&&e[0]<=n&&e[1]*e[2]<=n?s=[e[0],e[1]*e[2]]:e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n?s=[e[0]*e[1]*e[2],e[3]]:e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(s=[e[0],e[1]*e[2]*e[3]]);let i=s!=null&&Math.max(...s)>a&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(s==null||i)if(t){let o=wi(e),l=2,u=2;e.length&&([l,u]=ki(e)),r=o*(l/2)*(u/2),s=w.sizeToSquarishShape(r).map(p=>p*2)}else s=w.sizeToSquarishShape(r);return s}function qh(e){return e%2===0}function Ac(e,t){if(e=e.slice(-2),t=t.slice(-2),w.arraysEqual(e,t)||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){let n=e[e.length-1],a=t[t.length-1];if(n===a||qh(n)&&qh(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&qh(e[0])&&qh(t[0])}var Qh,em;function GE(e){if(Qh==null){let t=Ka(e);Qh=t.getParameter(t.MAX_TEXTURE_SIZE)}return Qh}function yJ(){Qh=null}function xJ(){em=null}function HE(e){if(em==null){let t=Ka(e);em=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,em)}function qE(e){if(e===0)return 0;let t,n=Ka(e);return ma(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:ma(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function ma(e,t){return e.getExtension(t)!=null}function mv(e){try{if(Ka(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function jE(e){if(e===0)return!1;let t=Ka(e);if(e===1){if(!ma(t,"OES_texture_float"))return!1}else if(!ma(t,"EXT_color_buffer_float"))return!1;return fv(t)}function KE(e){if(e===0)return!1;let t=Ka(e);if(e===1){if(!ma(t,"OES_texture_float")||!ma(t,"WEBGL_color_buffer_float"))return!1}else{if(ma(t,"EXT_color_buffer_float"))return fv(t);let n="EXT_color_buffer_half_float";if(ma(t,n)){let a=t.getExtension(n);return vJ(t,a)}return!1}return fv(t)}function fv(e){let t=J1(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let a=1,r=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,a,r,0,t.textureFormatFloat,t.textureTypeFloat,null);let s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(s),i}function vJ(e,t){let n=J1(e,t),a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a);let r=1,s=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,s,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(a),e.deleteFramebuffer(i),o}function XE(e){return e!==2?!1:Ka(e).fenceSync!=null}function vp(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&w.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var xe=G();xe.registerFlag("HAS_WEBGL",()=>xe.getNumber("WEBGL_VERSION")>0);xe.registerFlag("WEBGL_VERSION",()=>mv(2)?2:mv(1)?1:0);xe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);xe.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>xe.get("WEBGL_VERSION")===2);xe.registerFlag("WEBGL_CPU_FORWARD",()=>!0);xe.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);xe.registerFlag("WEBGL_PACK",()=>xe.getBool("HAS_WEBGL"));xe.registerFlag("WEBGL_PACK_NORMALIZATION",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_CLIP",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_REDUCE",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_LAZILY_UNPACK",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_CONV_IM2COL",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>GE(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>HE(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=xe.getNumber("WEBGL_VERSION");return e===0?0:qE(e)});xe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>xe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!od.isMobile());xe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>jE(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>xe.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:xe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));xe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>KE(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>XE(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>xe.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);xe.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});xe.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>od.isMobile()?1:-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});xe.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);xe.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);xe.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);xe.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);xe.registerFlag("WEBGL_EXP_CONV",()=>!1);xe.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>xe.getBool("IS_TEST"));xe.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);xe.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);xe.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);xe.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function En(){let e,t,n,a,r,s,i,o,l,u;return G().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",a="in",r="texture",s="outputColor",i="out vec4 outputColor;",o=G().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)
    `:"",l="",u=`
      #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)));
      }
    `):(e="",t="attribute",n="varying",a="varying",r="texture2D",s="gl_FragColor",i="",o=`
      #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));
      }
    `,l=`
      uniform float INFINITY;
 
      bool isinf(float val) {
        return abs(val) == INFINITY;
      }
      bvec4 isinf(vec4 val) {
        return equal(abs(val), vec4(INFINITY));
      }
    `,u=`
      int round(float value) {
        return int(floor(value + 0.5));
      }
 
      ivec4 round(vec4 value) {
        return ivec4(floor(value + vec4(0.5)));
      }
    `),{version:e,attribute:t,varyingVs:n,varyingFs:a,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Jo(e,t,n="index"){let a=w.computeStrides(t);return a.map((r,s)=>{let i=`int ${e[s]} = ${n} / ${r}`,o=s===a.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${r}`:`index -= ${e[s]} * ${r}`;return`${i}; ${o};`}).join("")}function Jf(e,t,n="index"){let a=w.computeStrides(t);return a.map((r,s)=>{let i=`int ${e[s]} = ${n} / outShapeStrides[${s}]`,o=s===a.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function wJ(e,t){let n=e.length,a=e.map(s=>`${t}[${s}]`),r=new Array(n-1);r[n-2]=a[n-1];for(let s=n-3;s>=0;--s)r[s]=`(${r[s+1]} * ${a[s+1]})`;return r}function kJ(e,t,n="index"){let a=e.map((s,i)=>i),r=wJ(a,t);return r.map((s,i)=>{let o=`int ${e[i]} = ${n} / ${r[i]}`,l=i===r.length-1?`int ${e[i+1]} = ${n} - ${e[i]} * ${r[i]}`:`index -= ${e[i]} * ${r[i]}`;return`${o}; ${l};`}).join("")}function ek(e){let t=w.computeStrides(e).map(n=>n.toString());return`
  int getFlatIndex(ivec3 coords) {
    return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
  }
`}function tk(){return`
  int getFlatIndex(ivec3 coords) {
    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
  }
`}var YE=`
  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;
  }
`,{getBroadcastDims:ZE}=N;function IJ(e,t,n){let a=[];if(e.forEach(c=>{let h=w.sizeFromShape(c.shapeInfo.logicalShape);if(c.shapeInfo.isUniform?a.push(`uniform float ${c.name}${h>1?`[${h}]`:""};`):(a.push(`uniform sampler2D ${c.name};`),a.push(`uniform int offset${c.name};`)),n.enableShapeUniforms){let{uniformShape:m}=nk(n.packedInputs,c.shapeInfo.logicalShape,c.shapeInfo.texShape);switch(m.length){case 1:a.push(`uniform int ${c.name}Shape;`);break;case 2:a.push(`uniform ivec2 ${c.name}Shape;`);break;case 3:a.push(`uniform ivec3 ${c.name}Shape;`);break;case 4:a.push(`uniform ivec4 ${c.name}Shape;`);break;default:break}a.push(`uniform ivec2 ${c.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:a.push("uniform int outShape;");break;case 2:a.push("uniform ivec2 outShape;"),a.push("uniform int outShapeStrides;");break;case 3:a.push("uniform ivec3 outShape;"),a.push("uniform ivec2 outShapeStrides;");break;case 4:a.push("uniform ivec4 outShape;"),a.push("uniform ivec3 outShapeStrides;");break;default:break}a.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(c=>{a.push(`uniform ${c.type} ${c.name}${c.arrayIndex?`[${c.arrayIndex}]`:""};`)});let r=a.join(`
`),s=e.map(c=>SJ(c,t,n.packedInputs,n.enableShapeUniforms)).join(`
`),i=t.texShape,o=En(),l=CJ(o),u,p,d=AJ(o);return t.isPacked?(u=NJ(t.logicalShape,i,n.enableShapeUniforms),p=EJ(o)):(u=TJ(t.logicalShape,i,n.enableShapeUniforms),p=_J(o)),n.packedInputs&&(d+=RJ),[d,l,p,r,u,s,n.userCode].join(`
`)}function wp(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return qJ(e,t);case 1:return KJ(e,t);case 2:return YJ(e,t);case 3:return JJ(e,t);case 4:return e9(e,t);case 5:return t9(e);case 6:return n9(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function JE(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return HJ(e);case 1:return jJ(e,t);case 2:return XJ(e,t);case 3:return ZJ(e,t);default:return QJ(e,t)}}function SJ(e,t,n=!1,a){let r="";n?r+=JE(e,a):r+=wp(e,a);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(n?r+=a9(e,t):r+=r9(e,t)),r}function NJ(e,t,n){switch(e.length){case 0:return QE();case 1:return MJ(e,t,n);case 2:return UJ(e,t,n);case 3:return OJ(e,t,n);default:return zJ(e,t,n)}}function TJ(e,t,n){switch(e.length){case 0:return QE();case 1:return PJ(e,t,n);case 2:return GJ(e,t,n);case 3:return LJ(e,t,n);case 4:return WJ(e,t,n);case 5:return BJ(e,t);case 6:return VJ(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function CJ(e){return`
    float sampleTexture(sampler2D textureSampler, vec2 uv) {
      return ${e.texture2D}(textureSampler, uv).r;
    }
  `}function _J(e){return`
    void setOutput(float val) {
      ${e.output} = vec4(val, 0, 0, 0);
    }
  `}function EJ(e){return`
    void setOutput(vec4 val) {
      ${e.output} = val;
    }
  `}function AJ(e){return`${e.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${e.varyingFs} vec2 resultUV;
    ${e.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;
    ${e.defineSpecialNaN}
    ${e.defineSpecialInf}
    ${e.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);
    }
 
    ${FJ}
    ${$J}
    ${DJ}
  `}var FJ=`
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);
}
`,$J=`
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);
}
`,DJ=`
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);
}
`,RJ=`
  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 QE(){return`
    int getOutputCoords() {
      return 0;
    }
  `}function MJ(e,t,n){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return a[0]===1?n?`
      int getOutputCoords() {
        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
      }
    `:`
      int getOutputCoords() {
        return 2 * int(resultUV.x * ${a[1]}.0);
      }
    `:a[1]===1?n?`
      int getOutputCoords() {
        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
      }
    `:`
      int getOutputCoords() {
        return 2 * int(resultUV.y * ${a[0]}.0);
      }
    `:n?`
    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(${a[0]}, ${a[1]}));
      return 2 * (resTexRC.x * ${a[1]} + resTexRC.y);
    }
  `}function PJ(e,t,n){return t[0]===1?n?`
      int getOutputCoords() {
        return int(resultUV.x * float(outTexShape[1]));
      }
    `:`
      int getOutputCoords() {
        return int(resultUV.x * ${t[1]}.0);
      }
    `:t[1]===1?n?`
      int getOutputCoords() {
        return int(resultUV.y * float(outTexShape[0]));
      }
    `:`
      int getOutputCoords() {
        return int(resultUV.y * ${t[0]}.0);
      }
    `:n?`
    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 OJ(e,t,n){if(n)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 a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),s=r*Math.ceil(e[1]/2);return`
    ivec3 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${a[0]}, ${a[1]}));
      int index = resTexRC.x * ${a[1]} + resTexRC.y;
 
      int b = index / ${s};
      index -= b * ${s};
 
      int r = 2 * (index / ${r});
      int c = imod(index, ${r}) * 2;
 
      return ivec3(b, r, c);
    }
  `}function LJ(e,t,n){if(n)return`
  ivec3 getOutputCoords() {
    ivec2 resTexRC = ivec2(resultUV.yx *
                           vec2(outTexShape[0], outTexShape[1]));
    int index = resTexRC.x * outTexShape[1] + resTexRC.y;
    ${Jf(["r","c","d"],e)}
    return ivec3(r, c, d);
  }
`;let a=Jo(["r","c","d"],e);return`
    ivec3 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
      ${a}
      return ivec3(r, c, d);
    }
  `}function zJ(e,t,n){if(n)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 a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),s=r*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let u=2;u<e.length-1;u++)i*=e[e.length-u-1],o=`
      int b${u} = index / ${i};
      index -= b${u} * ${i};
    `+o,l=`b${u}, `+l;return`
    ivec${e.length} getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${a[0]}, ${a[1]}));
      int index = resTexRC.x * ${a[1]} + resTexRC.y;
 
      ${o}
 
      int b = index / ${s};
      index -= b * ${s};
 
      int r = 2 * (index / ${r});
      int c = imod(index, ${r}) * 2;
 
      return ivec${e.length}(${l});
    }
  `}function WJ(e,t,n){if(n)return`
    ivec4 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(outTexShape[0], outTexShape[1]));
      int index = resTexRC.x * outTexShape[1] + resTexRC.y;
      ${Jf(["r","c","d","d2"],e)}
      return ivec4(r, c, d, d2);
    }
  `;let a=Jo(["r","c","d","d2"],e);return`
    ivec4 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
      ${a}
      return ivec4(r, c, d, d2);
    }
  `}function BJ(e,t){let n=Jo(["r","c","d","d2","d3"],e);return`
    ivec5 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
                             ${t[1]}));
 
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
 
      ${n}
 
      ivec5 outShape = ivec5(r, c, d, d2, d3);
      return outShape;
    }
  `}function VJ(e,t){let n=Jo(["r","c","d","d2","d3","d4"],e);return`
    ivec6 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
 
      ${n}
 
      ivec6 result = ivec6(r, c, d, d2, d3, d4);
      return result;
    }
  `}function UJ(e,t,n){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n?`
      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(${a[0]}, ${a[1]}));
      }
    `;let r=Math.ceil(e[1]/2);return n?`
    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(${a[0]}, ${a[1]}));
 
      int index = resTexRC.x * ${a[1]} + resTexRC.y;
      int r = 2 * (index / ${r});
      int c = imod(index, ${r}) * 2;
 
      return ivec2(r, c);
    }
  `}function GJ(e,t,n){return w.arraysEqual(e,t)?n?`
      ivec2 getOutputCoords() {
        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
      }
    `:`
      ivec2 getOutputCoords() {
        return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
      }
    `:e[1]===1?n?`
      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);
      }
    `:e[0]===1?n?`
      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);
      }
    `:n?`
    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 / ${e[1]};
      int c = index - r * ${e[1]};
      return ivec2(r, c);
    }
  `}function Qo(e){return`offset${e}`}function HJ(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=En();return`
    vec4 ${n}() {
      return ${a.texture2D}(${t}, halfCR);
    }
  `}function qJ(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${a}() {return ${n};}`;let[r,s]=e.shapeInfo.texShape;if(r===1&&s===1)return`
      float ${a}() {
        return sampleTexture(${n}, halfCR);
      }
    `;let i=Qo(n);if(t)return`
    float ${a}() {
      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});
      return sampleTexture(${n}, uv);
    }
  `;let[o,l]=e.shapeInfo.texShape;return`
    float ${a}() {
      vec2 uv = uvFromFlat(${o}, ${l}, ${i});
      return sampleTexture(${n}, uv);
    }
  `}function jJ(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=En();if(t)return`
    vec4 ${a}(int index) {
      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
      vec2 uv = packedUVfrom1D(
        packedTexShape[0], packedTexShape[1], index);
      return ${s.texture2D}(${n}, uv);
    }
  `;let i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return`
    vec4 ${a}(int index) {
      vec2 uv = packedUVfrom1D(
        ${i[0]}, ${i[1]}, index);
      return ${s.texture2D}(${n}, uv);
    }
  `}function KJ(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
      float ${a}(int index) {
        ${kp(e)}
      }
    `;let r=e.shapeInfo.texShape,s=r[0],i=r[1];if(i===1&&s===1)return`
      float ${a}(int index) {
        return sampleTexture(${n}, halfCR);
      }
    `;let o=Qo(n);return i===1?t?`
      float ${a}(int index) {
        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${n}TexShape[0]));
        return sampleTexture(${n}, uv);
      }
    `:`
      float ${a}(int index) {
        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
        return sampleTexture(${n}, uv);
      }
    `:s===1?t?`
      float ${a}(int index) {
        vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${n}TexShape[1]), 0.5);
        return sampleTexture(${n}, uv);
      }
    `:`
      float ${a}(int index) {
        vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
        return sampleTexture(${n}, uv);
      }
    `:t?`
    float ${a}(int index) {
      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${o});
      return sampleTexture(${n}, uv);
    }
  `:`
    float ${a}(int index) {
      vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
      return sampleTexture(${n}, uv);
    }
  `}function XJ(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=En();if(s!=null&&w.arraysEqual(n,s))return t?`
      vec4 ${r}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
 
        return ${l.texture2D}(${a}, uv);
      }
    `:`
      vec4 ${r}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
 
        return ${l.texture2D}(${a}, uv);
      }
    `;if(t)return`
    vec4 ${r}(int row, int col) {
      ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
      int valuesPerRow = int(ceil(float(${a}Shape[1]) / 2.0));
      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
      return ${l.texture2D}(${a}, uv);
    }
  `;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],p=Math.ceil(n[1]/2);return`
    vec4 ${r}(int row, int col) {
      vec2 uv = packedUVfrom2D(${p}, ${u[0]}, ${u[1]}, row, col);
      return ${l.texture2D}(${a}, uv);
    }
  `}function YJ(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape;if(s!=null&&w.arraysEqual(n,s)){if(t)return`
      float ${r}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
        return sampleTexture(${a}, uv);
      }
    `;let c=s[0],h=s[1];return`
    float ${r}(int row, int col) {
      vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${c}.0);
      return sampleTexture(${a}, uv);
    }
  `}let{newShape:i,keptDims:o}=w.squeezeShape(n),l=i;if(l.length<n.length){let c=Ip(e,l),h=["row","col"];return`
      ${wp(c,t)}
      float ${r}(int row, int col) {
        return ${r}(${Sp(h,o)});
      }
    `}if(e.shapeInfo.isUniform)return`
      float ${r}(int row, int col) {
        int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
        ${kp(e)}
      }
    `;let u=s[0],p=s[1],d=Qo(a);return p===1?t?`
      float ${r}(int row, int col) {
        float index = dot(vec3(row, col, ${d}), vec3(${a}Shape[1], 1, 1));
        vec2 uv = vec2(0.5, (index + 0.5) / float(${a}TexShape[0]));
        return sampleTexture(${a}, uv);
      }
    `:`
    float ${r}(int row, int col) {
      float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
      vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
      return sampleTexture(${a}, uv);
    }
  `:u===1?t?`
      float ${r}(int row, int col) {
        float index = dot(vec3(row, col, ${d}), vec3(${a}Shape[1], 1, 1));
        vec2 uv = vec2((index + 0.5) / float(${a}TexShape[1]), 0.5);
        return sampleTexture(${a}, uv);
      }
    `:`
    float ${r}(int row, int col) {
      float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
      vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);
      return sampleTexture(${a}, uv);
    }
  `:t?`
      float ${r}(int row, int col) {
        // Explicitly use integer operations as dot() only works on floats.
        int index = row * ${a}Shape[1] + col + ${d};
        vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index);
        return sampleTexture(${a}, uv);
      }
    `:`
  float ${r}(int row, int col) {
    // Explicitly use integer operations as dot() only works on floats.
    int index = row * ${n[1]} + col + ${d};
    vec2 uv = uvFromFlat(${u}, ${p}, index);
    return sampleTexture(${a}, uv);
  }
`}function ZJ(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(n[0]===1){let c=n.slice(1),h=[1,2],m=Ip(e,c),f=["b","row","col"];return`
        ${JE(m,t)}
        vec4 ${r}(int b, int row, int col) {
          return ${r}(${Sp(f,h)});
        }
      `}let o=En();if(t)return`
    vec4 ${r}(int b, int row, int col) {
      ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
      int valuesPerRow = int(ceil(float(${a}Shape[2]) / 2.0));
      int texelsInBatch = valuesPerRow * int(ceil(float(${a}Shape[1]) / 2.0));
      vec2 uv = packedUVfrom3D(
        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
      return ${o.texture2D}(${a}, uv);
    }
  `;let l=i[0],u=i[1],p=Math.ceil(n[2]/2),d=p*Math.ceil(n[1]/2);return`
    vec4 ${r}(int b, int row, int col) {
      vec2 uv = packedUVfrom3D(
        ${l}, ${u}, ${d}, ${p}, b, row, col);
      return ${o.texture2D}(${a}, uv);
    }
  `}function JJ(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=n[1]*n[2],i=n[2],{newShape:o,keptDims:l}=w.squeezeShape(n),u=o;if(u.length<n.length){let f=Ip(e,u),g=["row","col","depth"];return`
        ${wp(f,t)}
        float ${r}(int row, int col, int depth) {
          return ${r}(${Sp(g,l)});
        }
      `}if(e.shapeInfo.isUniform)return`
      float ${r}(int row, int col, int depth) {
        int index = round(dot(vec3(row, col, depth),
                          vec3(${s}, ${i}, 1)));
        ${kp(e)}
      }
    `;let p=e.shapeInfo.texShape,d=p[0],c=p[1],h=e.shapeInfo.flatOffset;if(c===s&&h==null)return t?`
      float ${r}(int row, int col, int depth) {
        int stride1 = ${a}Shape[2];
        float texR = float(row);
        float texC = dot(vec2(col, depth), vec2(stride1, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${a}TexShape[1], ${a}TexShape[0]);
        return sampleTexture(${a}, uv);
      }
    `:`
        float ${r}(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(${c}.0, ${d}.0);
          return sampleTexture(${a}, uv);
        }
      `;if(c===i&&h==null)return t?`
      float ${r}(int row, int col, int depth) {
        float texR = dot(vec2(row, col), vec2(${a}Shape[1], 1));
        float texC = float(depth);
        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
        return sampleTexture(${a}, uv);
      }
    `:`
    float ${r}(int row, int col, int depth) {
      float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
      float texC = float(depth);
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}.0, ${d}.0);
      return sampleTexture(${a}, uv);
    }
  `;let m=Qo(a);return t?`
    float ${r}(int row, int col, int depth) {
      // Explicitly use integer operations as dot() only works on floats.
      int stride0 = ${a}Shape[1] * ${a}Shape[2];
      int stride1 = ${a}Shape[2];
      int index = row * stride0 + col * stride1 + depth + ${m};
      vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index);
      return sampleTexture(${a}, uv);
    }
    `:`
      float ${r}(int row, int col, int depth) {
        // Explicitly use integer operations as dot() only works on floats.
        int index = row * ${s} + col * ${i} + depth + ${m};
        vec2 uv = uvFromFlat(${d}, ${c}, index);
        return sampleTexture(${a}, uv);
      }
  `}function QJ(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=En();if(t)return`
    vec4 ${a}(int b2, int b, int row, int col) {
      int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
      int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
      texelsInBatch *= ${n}Shape[1];
      index = b2 * texelsInBatch + index;
      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}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 ${r.texture2D}(${n}, uv);
    }
  `;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],p=l[1],d=Math.ceil(s[i-1]/2),c=d*Math.ceil(s[i-2]/2),h="int b, int row, int col",m=`b * ${c} + (row / 2) * ${d} + (col / 2)`;for(let f=2;f<i-1;f++)h=`int b${f}, `+h,c*=s[i-f-1],m=`b${f} * ${c} + `+m;return`
    vec4 ${a}(${h}) {
      int index = ${m};
      int texR = index / ${p};
      int texC = index - texR * ${p};
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${u});
      return ${r.texture2D}(${n}, uv);
    }
  `}function e9(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=n[3],i=n[2]*s,o=n[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(n);if(l.length<n.length){let y=Ip(e,l),x=["row","col","depth","depth2"];return`
      ${wp(y,t)}
      float ${r}(int row, int col, int depth, int depth2) {
        return ${r}(${Sp(x,u)});
      }
    `}if(e.shapeInfo.isUniform)return`
      float ${r}(int row, int col, int depth, int depth2) {
        int index = round(dot(vec4(row, col, depth, depth2),
                          vec4(${o}, ${i}, ${s}, 1)));
        ${kp(e)}
      }
    `;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,c=d[0],h=d[1],m=`int stride2 = ${a}Shape[3];`,f=`int stride1 = ${a}Shape[2] * stride2;`,g=`int stride0 = ${a}Shape[1] * stride1;`;if(h===o&&p==null)return t?`
      float ${r}(int row, int col, int depth, int depth2) {
        ${m}
        ${f}
        float texR = float(row);
        float texC =
            dot(vec3(col, depth, depth2),
                vec3(stride1, stride2, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${a}TexShape[1], ${a}TexShape[0]);
        return sampleTexture(${a}, uv);
      }
    `:`
      float ${r}(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(${h}.0, ${c}.0);
        return sampleTexture(${a}, uv);
      }
    `;if(h===s&&p==null)return t?`
      float ${r}(int row, int col, int depth, int depth2) {
        float texR = dot(vec3(row, col, depth),
                         vec3(${a}Shape[1] * ${a}Shape[2], ${a}Shape[2], 1));
        float texC = float(depth2);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${a}TexShape[1], ${a}TexShape[0]);
        return sampleTexture(${a}, uv);
      }
    `:`
      float ${r}(int row, int col, int depth, int depth2) {
        float texR = dot(vec3(row, col, depth),
                         vec3(${n[1]*n[2]}, ${n[2]}, 1));
        float texC = float(depth2);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${h}.0, ${c}.0);
        return sampleTexture(${a}, uv);
      }
    `;let b=Qo(a);return t?`
    float ${r}(int row, int col, int depth, int depth2) {
      // Explicitly use integer operations as dot() only works on floats.
      ${m}
      ${f}
      ${g}
      int index = row * stride0 + col * stride1 +
          depth * stride2 + depth2;
      vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index + ${b});
      return sampleTexture(${a}, uv);
    }
  `:`
    float ${r}(int row, int col, int depth, int depth2) {
      // Explicitly use integer operations as dot() only works on floats.
      int index = row * ${o} + col * ${i} +
          depth * ${s} + depth2;
      vec2 uv = uvFromFlat(${c}, ${h}, index + ${b});
      return sampleTexture(${a}, uv);
    }
  `}function t9(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],s=t[3]*r,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(t);if(l.length<t.length){let f=Ip(e,l),g=["row","col","depth","depth2","depth3"];return`
      ${wp(f)}
      float ${a}(int row, int col, int depth, int depth2, int depth3) {
        return ${a}(${Sp(g,u)});
      }
    `}if(e.shapeInfo.isUniform)return`
      float ${a}(int row, int col, int depth, int depth2, int depth3) {
        float index = dot(
          vec4(row, col, depth, depth2),
          vec4(${o}, ${i}, ${s}, ${r})) +
          depth3;
        ${kp(e)}
      }
    `;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,c=d[0],h=d[1];if(h===o&&p==null)return`
      float ${a}(int row, int col, int depth, int depth2, int depth3) {
        int texR = row;
        float texC = dot(vec4(col, depth, depth2, depth3),
                         vec4(${i}, ${s}, ${r}, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${h}.0, ${c}.0);
        return sampleTexture(${n}, uv);
      }
    `;if(h===r&&p==null)return`
      float ${a}(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(${h}.0, ${c}.0);
        return sampleTexture(${n}, uv);
      }
    `;let m=Qo(n);return`
    float ${a}(int row, int col, int depth, int depth2, int depth3) {
      // Explicitly use integer operations as dot() only works on floats.
      int index = row * ${o} + col * ${i} + depth * ${s} +
          depth2 * ${r} + depth3 + ${m};
      vec2 uv = uvFromFlat(${c}, ${h}, index);
      return sampleTexture(${n}, uv);
    }
  `}function n9(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:s}=w.squeezeShape(t);if(r.length<t.length){let g=Ip(e,r),b=["row","col","depth","depth2","depth3","depth4"];return`
      ${wp(g)}
      float ${a}(int row, int col, int depth,
                    int depth2, int depth3, int depth4) {
        return ${a}(${Sp(b,s)});
      }
    `}let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,p=t[1]*u;if(e.shapeInfo.isUniform)return`
      float ${a}(int row, int col, int depth,
                  int depth2, int depth3, int depth4) {
        int index = round(dot(
          vec4(row, col, depth, depth2),
          vec4(${p}, ${u}, ${l}, ${o})) +
          dot(
            vec2(depth3, depth4),
            vec2(${i}, 1)));
        ${kp(e)}
      }
    `;let d=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,h=c[0],m=c[1];if(m===p&&d==null)return`
      float ${a}(int row, int col, int depth,
                    int depth2, int depth3, int depth4) {
        int texR = row;
        float texC = dot(vec4(col, depth, depth2, depth3),
          vec4(${u}, ${l}, ${o}, ${i})) +
               float(depth4);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${m}.0, ${h}.0);
        return sampleTexture(${n}, uv);
      }
    `;if(m===i&&d==null)return`
      float ${a}(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(${m}.0, ${h}.0);
        return sampleTexture(${n}, uv);
      }
    `;let f=Qo(n);return`
    float ${a}(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 * ${p} + col * ${u} + depth * ${l} +
          depth2 * ${o} + depth3 * ${i} + depth4 + ${f};
      vec2 uv = uvFromFlat(${h}, ${m}, index);
      return sampleTexture(${n}, uv);
    }
  `}function kp(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
    for (int i = 0; i < ${n}; i++) {
      if (i == index) {
        return ${t}[i];
      }
    }
  `}function a9(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=ZE(e.shapeInfo.logicalShape,t.logicalShape),l=dt(i),u=i-s,p,d=["x","y","z","w","u","v"];s===0?p="":i<2&&o.length>=1?p="coords = 0;":p=o.map(g=>`coords.${d[g+u]} = 0;`).join(`
`);let c="";i<2&&s>0?c="coords":c=e.shapeInfo.logicalShape.map((g,b)=>`coords.${d[b+u]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,f=w.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)h=`
      return vec4(outputValue.xy, outputValue.xy);
    `;else if(m&&!f)i===1?h=`
        return vec4(outputValue.x, outputValue.x, 0., 0.);
      `:h=`
        return vec4(outputValue.x);
      `;else if(o.length){let g=s-2,b=s-1;o.indexOf(g)>-1&&o.indexOf(b)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(b)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
    vec4 ${r}() {
      ${l} coords = getOutputCoords();
      ${p}
      vec4 outputValue = get${a}(${c});
      ${h}
    }
  `}function r9(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&w.arraysEqual(i,s))return`
      float ${r}() {
        return sampleTexture(${n}, resultUV);
      }
    `;let u=dt(l),p=ZE(e.shapeInfo.logicalShape,t.logicalShape),d=l-o,c,h=["x","y","z","w","u","v"];o===0?c="":l<2&&p.length>=1?c="coords = 0;":c=p.map(f=>`coords.${h[f+d]} = 0;`).join(`
`);let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${h[g+d]}`).join(", "),`
    float ${r}() {
      ${u} coords = getOutputCoords();
      ${c}
      return get${a}(${m});
    }
  `}function dt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function nk(e,t,n){let{newShape:a,keptDims:r}=w.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):a,l=!e&&s>1&&!w.arraysEqual(t,n)&&a.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function Ip(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Sp(e,t){return t.map(n=>e[n]).join(", ")}function s9(e,t,n,a){let r=n.map((p,d)=>{let c={logicalShape:p.shape,texShape:p.isUniform?null:p.texData.texShape,isUniform:p.isUniform,isPacked:p.isUniform?!1:p.texData.isPacked,flatOffset:null};return p.texData!=null&&p.texData.slice!=null&&p.texData.slice.flatOffset>0&&(c.flatOffset=p.texData.slice.flatOffset),{name:t.variableNames[d],shapeInfo:c}}),s=r.map(p=>p.shapeInfo),i={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},o=IJ(r,i,t),l=EE(e.gl,o),u=e.createProgram(l);return G().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(u),Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i},eA(e,t,u)))}function eA(e,t,n){let a=[],r=[],s,i,o,l=null,u=null;u=e.getUniformLocation(n,"NAN",!1),G().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(n,"INFINITY",!1));let p=!1;for(let d of t.variableNames){let c={name:d,uniform:e.getUniformLocation(n,d,p),offset:e.getUniformLocation(n,`offset${d}`,p)};t.enableShapeUniforms&&(c.shape=e.getUniformLocation(n,`${d}Shape`,p),c.texShape=e.getUniformLocation(n,`${d}TexShape`,p)),a.push(c)}if(t.enableShapeUniforms&&(s=e.getUniformLocation(n,"outShape",p),o=e.getUniformLocation(n,"outShapeStrides",p),i=e.getUniformLocation(n,"outTexShape",p)),t.customUniforms)for(let d of t.customUniforms)r.push(e.getUniformLocation(n,d.name,p));return{variablesLocations:a,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:s,outShapeStridesLocation:o,outTexShapeLocation:i}}function mS(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,a)=>{let r=n.logicalShape,s=t[a],i=s.shape;if(!w.arraysEqual(r,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${i} must match`);if(n.isUniform&&s.isUniform)return;let o=n.texShape,l=s.isUniform?null:s.texData.texShape;if(!w.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function i9(e,t,n,a,r){t.program.enableShapeUniforms||(mS(t.inShapeInfos,n),mS([t.outShapeInfo],[a]));let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),G().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN);for(let l=0;l<n.length;++l){let u=n[l],{uniform:p,offset:d,shape:c,texShape:h}=t.variablesLocations[l];if(c){let{uniformShape:m}=nk(t.program.packedInputs,u.shape,u.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(c,new Int32Array(m));break;case 2:e.gl.uniform2iv(c,new Int32Array(m));break;case 3:e.gl.uniform3iv(c,new Int32Array(m));break;case 4:e.gl.uniform4iv(c,new Int32Array(m));break;default:break}}if(h&&e.gl.uniform2i(h,u.texData.texShape[0],u.texData.texShape[1]),p!=null){if(u.isUniform){if(w.sizeFromShape(u.shape)<2)e.gl.uniform1f(p,u.uniformValues[0]);else{let m=u.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(p,m)}continue}u.texData.slice!=null&&d!=null&&e.gl.uniform1i(d,u.texData.slice.flatOffset),e.setInputMatrixTexture(u.texData.texture.texture,p,l)}}let o=t.outShapeLocation;if(o)switch(a.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(a.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(a.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(a.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(a.shape));break;default:break}if(t.outShapeStridesLocation){let l=w.computeStrides(a.shape);switch(a.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,a.texData.texShape[0],a.texData.texShape[1]),t.program.customUniforms&&r)for(let l=0;l<t.program.customUniforms.length;++l){let u=t.program.customUniforms[l],p=t.customUniformLocations[l],d=r[l];if(u.type==="float")e.gl.uniform1fv(p,d);else if(u.type==="vec2")e.gl.uniform2fv(p,d);else if(u.type==="vec3")e.gl.uniform3fv(p,d);else if(u.type==="vec4")e.gl.uniform4fv(p,d);else if(u.type==="int")e.gl.uniform1iv(p,d);else if(u.type==="ivec2")e.gl.uniform2iv(p,d);else if(u.type==="ivec3")e.gl.uniform3iv(p,d);else if(u.type==="ivec4")e.gl.uniform4iv(p,d);else throw Error(`uniform type ${u.type} is not supported yet.`)}e.executeProgram()}function o9(e,t,n){let a="";t.concat(n).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!i.isUniform){let l=i.texData.texShape,{useSqueezeShape:u,uniformShape:p,keptDims:d}=nk(e.packedInputs,i.shape,l),c="",h="",m="";if(p.length===1&&e.packedInputs){let I=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];c=`${I[0]>1}_${I[1]>1}`}else if(p.length===2&&!e.packedInputs)h=`${p[0]>1}_${p[1]>1}`;else if(p.length>2&&!e.packedInputs){let I=w.computeStrides(p);m=`${I[0]===l[1]}_${I[I.length-1]===l[1]}`}let f=i.shape.length,g=p.length===2&&w.arraysEqual(i.shape,l),b=w.sizeFromShape(i.shape)===1,y=N.getBroadcastDims(i.shape,n.shape),x=!e.packedInputs&&f===n.shape.length&&w.arraysEqual(l,n.texData.texShape),v=e.packedInputs||p.length>2?"":`${l[0]>1}_${l[1]>1}`;a+=`${f}_${x}_${u?d:""}_${p.length}_${b}_${y}_${g}_${c}_${h}_${m}_${v}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;a+=`${i.shape}_${l}_${o}`}});let r=e.userCode,s=e.constructor.name;return s+="_"+a+"_"+r+`${G().getNumber("WEBGL_VERSION")}`,s}function vn(e){return G().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var l9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ec.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=En();this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length),this.userCode=`
      ivec3 outCoordsFromFlatIndex(int index) {
        ${this.enableShapeUniforms?Jf(["r","c","d"],e):Jo(["r","c","d"],e)}
        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);
        }
 
        ${t.output} = result;
      }
    `}},u9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ec.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=En();this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length),this.userCode=`
      ivec3 outCoordsFromFlatIndex(int index) {
        ${this.enableShapeUniforms?Jf(["r","c","d"],e):Jo(["r","c","d"],e)}
        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));
        }
 
        ${t.output} = result;
      }
    `}},p9=class{constructor(e){this.variableNames=["A"],this.outTexUsage=ha.DOWNLOAD;let t=En();this.outputShape=e,this.userCode=`
      ${YE}
 
      void main() {
        float x = getAAtOutCoords();
        ${t.output} = encode_float(x);
      }
    `}},c9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ha.DOWNLOAD;let t=En();this.outputShape=e,this.userCode=`
      ${YE}
 
      void main() {
        ivec3 coords = getOutputCoords();
        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
        ${t.output} = encode_float(x);
      }
    `}},d9={R:0,G:1,B:2,A:3},fS=class{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let a=En();this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)");let s="";for(let i=0;i<n.length;i++){let o=n[i];s+=`
          if(offset == ${i}) {
            result = values[${d9[o]}];
          }`}this.userCode=`
      ${this.enableShapeUniforms?tk():ek(e)}
 
      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 = ${a.texture2D}(A, uv);
          ${s}
        }
        ${a.output} = vec4(${r}, 0., 0., 0.);
      }
    `}},h9=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=En();this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length);let a="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;a+=`
          localCoords = coords;
          if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
          localCoords[2] += ${i};
          if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
            localCoords[1] += ${s};
 
            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[${o}] = values[0];
            } else if (offset == 1) {
              result[${o}] = values[1];
            } else if (offset == 2) {
              result[${o}] = values[2];
            } else {
              result[${o}] = values[3];
            }
          }
        }
        `}this.userCode=`
        ${this.enableShapeUniforms?tk():ek(e)}
 
        void main() {
          ivec3 coords = getOutputCoords();
 
          vec4 result = vec4(0.);
          int flatIndex, r, c, offset;
          ivec3 localCoords;
          vec2 uv;
          vec4 values;
 
          ${a}
 
          ${n.output} = ${r};
        }
    `}},tA={};Ee(tA,{bindVertexProgramAttributeStreams:()=>pA,createBufferFromOutputTexture:()=>hA,createFloat16MatrixTexture:()=>iA,createFloat16PackedMatrixTexture:()=>uA,createFloat32MatrixTexture:()=>sA,createIndexBuffer:()=>rA,createPackedMatrixTexture:()=>lA,createUnsignedBytesMatrixTexture:()=>oA,createVertexBuffer:()=>aA,createVertexShader:()=>nA,downloadByteEncodedFloatMatrixFromOutputTexture:()=>fA,downloadFloat32MatrixFromBuffer:()=>mA,downloadMatrixFromPackedOutputTexture:()=>bA,downloadPackedMatrixFromBuffer:()=>gA,getInternalFormatForFloat16MatrixTexture:()=>rk,getInternalFormatForFloat16PackedMatrixTexture:()=>ok,getInternalFormatForFloat32MatrixTexture:()=>ak,getInternalFormatForPackedMatrixTexture:()=>ik,getInternalFormatForUnsignedBytesMatrixTexture:()=>sk,uploadDenseMatrixToTexture:()=>cA,uploadPixelDataToTexture:()=>dA});function nA(e){let t=En(),n=`${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 _E(e,n)}function aA(e){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 $E(e,t)}function rA(e){let t=new Uint16Array([0,1,2,2,1,3]);return DE(e,t)}function Pd(e,t,n,a,r,s){ME(t,n);let i=RE(e),o=e.TEXTURE_2D;return de(e,()=>e.bindTexture(o,i)),de(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),de(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),de(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),de(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),G().getNumber("WEBGL_VERSION")===1?de(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)):de(e,()=>e.texStorage2D(o,1,a,t,n)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[n,t]}}function ak(e){return e.internalFormatFloat}function sA(e,t,n,a){let[r,s]=Md(t,n);return Pd(e,r,s,ak(a),a.textureFormatFloat,e.FLOAT)}function rk(e){return e.internalFormatHalfFloat}function iA(e,t,n,a){let[r,s]=Md(t,n);return Pd(e,r,s,rk(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function sk(e){return e.downloadTextureFormat}function oA(e,t,n,a){let[r,s]=Md(t,n);return Pd(e,r,s,sk(a),e.RGBA,e.UNSIGNED_BYTE)}function ik(e){return e.internalFormatPackedFloat}function lA(e,t,n,a){let[r,s]=xp(t,n);return Pd(e,r,s,ik(a),e.RGBA,e.FLOAT)}function ok(e){return e.internalFormatPackedHalfFloat}function uA(e,t,n,a){let[r,s]=xp(t,n);return Pd(e,r,s,ok(a),e.RGBA,a.textureTypeHalfFloat)}function pA(e,t,n){return de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),dv(e,t,"clipSpacePos",n,3,20,0)&&dv(e,t,"uv",n,2,20,12)}function cA(e,t,n,a,r,s){de(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;r instanceof Uint8Array?(i=new Uint8Array(n*a*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*a*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(r),G().getNumber("WEBGL_VERSION")===2?de(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA,o,i)):de(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function dA(e,t,n){de(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?G().getNumber("WEBGL_VERSION")===2?de(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):de(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):G().getNumber("WEBGL_VERSION")===2?de(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):de(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function hA(e,t,n,a){let r=e.createBuffer();de(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return de(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),de(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),de(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function mA(e,t,n){let a=e,r=new Float32Array(n);return a.bindBuffer(a.PIXEL_PACK_BUFFER,t),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,r),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),r}function fA(e,t,n,a){let[r,s]=Md(t,n),i=4,o=new Uint8Array(uJ(t*n,i));return de(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function gA(e,t,n,a,r,s,i,o){let l=e,u=new Float32Array(pJ(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function bA(e,t,n){let a=new Float32Array(t*n*4);return de(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var tm=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let t=G().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,NE(t,e)):this.gl=Ka(t),e=this.gl,G().getNumber("WEBGL_VERSION")===2){let r=e;this.createVertexArray=()=>de(r,()=>r.createVertexArray()),this.bindVertexArray=s=>de(r,()=>r.bindVertexArray(s)),this.deleteVertexArray=s=>de(r,()=>r.deleteVertexArray(s)),this.getVertexArray=()=>de(r,()=>r.getParameter(r.VERTEX_ARRAY_BINDING))}else if(e!=null){let r=e.getExtension("OES_vertex_array_object");if(r==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>de(e,()=>r.createVertexArrayOES()),this.bindVertexArray=s=>de(e,()=>r.bindVertexArrayOES(s)),this.deleteVertexArray=s=>de(e,()=>r.deleteVertexArrayOES(s)),this.getVertexArray=()=>de(e,()=>e.getParameter(r.VERTEX_ARRAY_BINDING_OES))}let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),G().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=lc(this.gl,r),ma(this.gl,s))this.textureHalfFloatExtension=lc(this.gl,s);else if(G().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),ma(this.gl,a))this.colorBufferHalfFloatExtension=lc(this.gl,a);else if(G().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",ma(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(ma(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=aA(this.gl),this.indexBuffer=rA(this.gl),this.framebuffer=PE(this.gl),this.textureConfig=J1(this.gl,this.textureHalfFloatExtension)}get debug(){return G().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 e=this.gl;de(e,()=>e.finish()),de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),de(e,()=>e.deleteFramebuffer(this.framebuffer)),de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),de(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),de(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),sA(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),iA(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),oA(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),dA(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),cA(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),uA(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),lA(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(hv(this.gl,this.framebuffer),this.outputTexture=null),de(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>fA(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,a,r,s){return gA(this.gl,e,t,n,a,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return mA(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let a=hA(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),a}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(G().getBool("WEBGL_FENCE_API_ENABLED")){let a=e,r=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let s=a.clientWaitSync(r,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},t=r}else G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>bA(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=nA(t));let n=AE(t);de(t,()=>t.attachShader(n,this.vertexShader)),de(t,()=>t.attachShader(n,e)),FE(t,n);let a=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&Zh(t,a),a}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);let t=this.gl;de(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),pA(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(de(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Zh(this.gl,this.program),de(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?LE(this.gl,e,t):zE(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),de(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),WE(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[a,r]=xp(t,n);this.setOutputMatrixTextureDriver(e,a,r)}setOutputMatrixWriteRegion(e,t,n,a){this.setOutputMatrixWriteRegionDriver(n,e,a,t)}setOutputPackedMatrixWriteRegion(e,t,n,a){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Zh(this.gl,this.program),uc(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;if(this.debug){let t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}de(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),de(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=lc(this.gl,G().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(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.createQuery();return n.beginQuery(a.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await w.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),a=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=m9(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in G().platform&&(n=G().platform.setTimeoutCustom.bind(G().platform)),w.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Jh(this.gl,e,this.framebuffer),this.debug&&uc(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Jh(this.gl,this.outputTexture,this.framebuffer),this.debug&&uc(this.gl)):hv(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let a=this.gl;Jh(a,e,this.framebuffer),this.debug&&uc(a),this.outputTexture=e,de(a,()=>a.viewport(0,0,t,n)),de(a,()=>a.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,a){this.throwIfDisposed(),de(this.gl,()=>this.gl.scissor(e,t,n,a))}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 m9(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:f9,bincountImpl:yA,bincountReduceImpl:g9,bitwiseAndImpl:b9,castImpl:y9,ceilImpl:x9,concatImpl:v9,equalImpl:w9,expImpl:k9,expm1Impl:I9,floorImpl:S9,gatherNdImpl:N9,gatherV2Impl:T9,greaterImpl:C9,greaterEqualImpl:_9,lessImpl:E9,lessEqualImpl:A9,linSpaceImpl:F9,logImpl:$9,maxImpl:D9,maximumImpl:R9,minimumImpl:M9,multiplyImpl:P9,negImpl:O9,notEqualImpl:L9,prodImpl:z9,raggedGatherImpl:W9,raggedRangeImpl:B9,raggedTensorToTensorImpl:V9,rangeImpl:U9,rsqrtImpl:G9,scatterImpl:H9,sigmoidImpl:q9,simpleAbsImpl:xA,sliceImpl:j9,sparseFillEmptyRowsImpl:K9,sparseReshapeImpl:X9,sparseSegmentReductionImpl:vA,sqrtImpl:Y9,staticRegexReplaceImpl:Z9,stridedSliceImpl:J9,stringNGramsImpl:Q9,stringSplitImpl:eQ,stringToHashBucketFastImpl:tQ,subImpl:nQ,tileImpl:aQ,topKImpl:rQ,transposeImpl:lk,uniqueImpl:sQ}=P1;function wA(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Sn(e,t){return t===1?[e]:wA(e,t)}function iQ(e,t){if(e===1)return"rc";let n="";for(let a=0;a<e;a++)n+=t[a],a<e-1&&(n+=",");return n}var oQ=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=vn(this.outputShape.length),this.rank===0)this.userCode=`
        void main() {
          setOutput(vec4(getA(), 0., 0., 0.));
        }
      `;else{let t=Sn("rc",this.rank),n=dt(this.rank),a=this.getOutOfBoundsCondition(t),r=this.getSetup(t),s=this.getOutput(t);this.userCode=`
        void main() {
          ${n} rc = getOutputCoords();
 
          if(${a}) {
            setOutput(vec4(0));
          } else {
            ${r}
 
            setOutput(vec4(${s}));
          }
        }
      `}}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let a=0;a<=1;a++){let r=`${n===0?"r":"rp1"}, ${a===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)r=`${e[e.length-1-s]},`+r;t.push(r)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],a=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
      int r = ${t[0]};
      int c = ${t[1]};
      int rp1 = r + 1;
      int cp1 = c + 1;
 
      bool cEdge = cp1 >= ${n};
      bool rEdge = rp1 >= ${a};
    `}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
            cEdge ? 0. : getA(${t[1]}),
            rEdge ? 0. : getA(${t[2]}),
            rEdge || cEdge ? 0. : getA(${t[3]})`}},kA=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length);let n="";for(let a=0;a<4;a++){let r="thisRC = rc;";a%2===1&&(r+="thisRC.z += 1;"),a>1&&(r+="thisRC.y += 1;"),n+=`
        ${r}
        ${a>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[${a}] =
            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
        ${a>0?"}":""}
      `}this.userCode=`
      ${lQ(t,this.enableShapeUniforms)}
      ${this.enableShapeUniforms?tk():ek(e)}
 
      void main() {
        ivec3 rc = getOutputCoords();
 
        vec4 result = vec4(0.);
 
        ivec3 thisRC;
        int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
        int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
 
        ${n}
 
        setOutput(result);
      }
    `}};function lQ(e,t){return`
    ivec3 inputCoordsFromReshapedOutCoords(int index) {
      ${t?kJ(["r","c","d"],"inputShape"):Jo(["r","c","d"],e)}
      return ivec3(r, c, d);
    }
  `}var uQ=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){let a=bS(t,n),r=yS(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=gS(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[r].pop();return this.usedTextures[r].push(o),o}let i;return a===hn.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===hn.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===hn.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===hn.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===hn.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,n,a){if(this.freeTextures==null)return;let r=bS(n,a),s=yS(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=gS(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=G().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],u=l&&l.indexOf(e);if(u==null||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[u]=l[l.length-1],l.pop(),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}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 e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function pQ(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F||t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function gS(e,t,n,a,r){let s=cQ(t,a),i;if(r){let[l,u]=xp(e[0],e[1]);i=l*u}else{let[l,u]=Md(e[0],e[1]);i=l*u}let o=pQ(n,s);return i*o}function cQ(e,t){switch(e){case hn.PACKED_2X2_FLOAT32:return ik(t);case hn.PACKED_2X2_FLOAT16:return ok(t);case hn.UNPACKED_FLOAT32:return ak(t);case hn.UNPACKED_FLOAT16:return rk(t);case hn.PACKED_4X1_UNSIGNED_BYTE:return sk(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function dQ(e){return G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?hn.PACKED_2X2_FLOAT32:hn.UNPACKED_FLOAT32:e?hn.PACKED_2X2_FLOAT16:hn.UNPACKED_FLOAT16}function bS(e,t){if(e===ha.UPLOAD)return hn.PACKED_2X2_FLOAT32;if(e===ha.RENDER||e==null)return dQ(t);if(e===ha.DOWNLOAD||e===ha.PIXELS)return hn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function yS(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var ir=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length),this.userCode=`
      float unaryOperation(float x) {
        ${t}
      }
 
      void main() {
        float x = getAAtOutCoords();
        float y = unaryOperation(x);
 
        setOutput(y);
      }
    `}},Oa="if (isnan(x)) return x;",hQ="return x;",xS="return abs(x);",mQ="return (x >= 0.0) ? x : (exp(x) - 1.0);",fQ=Oa+`
  return (x < 0.0) ? 0.0 : x;
`,gQ=Oa+`
  return (x < 0.0) ? 0.0 : min(6.0, x);
`,ns="return x;",bQ="return 1.0 / (1.0 + exp(-1.0 * x));",yQ="return x;",xQ=`
  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;
`,vQ=`
  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;
`,wQ=`
  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;
`,kQ="return 1.0 / (1.0 + exp(-1.0 * x));",os=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length),this.userCode=`
      vec4 unaryOperation(vec4 x) {
        ${t}
      }
 
      void main() {
        vec4 x = getAAtOutCoords();
        vec4 y = unaryOperation(x);
 
        setOutput(y);
      }
    `}},IQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=vn(this.outputShape.length);let t=e.length,n=Sn("rc",t),a=dt(t),r=iQ(t,n),s=n.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
      void main() {
        ${a} rc = getOutputCoords();
        vec4 packedInput = getA(${r});
 
        setOutput(getChannel(packedInput, ${i}));
      }
    `}},SQ=gr.whereImpl,NQ=1e-7,TQ=1e-4,Sx={};function CQ(e){return e in Sx||(Sx[e]={}),Sx[e]}var _Q=G().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),EQ=600;function AQ(){return G().global.screen==null?1024:G().global.screen.height*G().global.screen.width*window.devicePixelRatio*EQ/1024/1024}var Qf=class extends Mc{nextDataId(){return Qf.nextDataId++}constructor(e){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,!G().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof tm)t=e;else{let n=Ka(G().getNumber("WEBGL_VERSION"),e);t=new tm(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Ka(G().getNumber("WEBGL_VERSION"));t=new tm(n),this.binaryCache=CQ(G().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new uQ(this.gpgpu),this.numMBBeforeWarning=AQ(),this.texData=new Rm(this,Aa())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,a,r,s){let i=this.makeTensorInfo(t,n),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[a,r]},o.texShape=[a,r];let l=pc(t),u=new fS(l,!1,s),p=this.runWebGLProgram(u,[i],n,[[a,r]]);return p.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),p.dataId}write(e,t,n){if((G().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||G().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a={id:this.nextDataId()};return this.texData.set(a,{shape:t,dtype:n,values:e,usage:ha.UPLOAD,refCount:1}),a}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,a,r){if(G().getBool("DEBUG")&&this.checkNumericalProblems(t),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:a,values:t,usage:ha.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:a,complexTensorInfos:r,slice:s,shape:i,isPacked:o}=t;if(s!=null){let d;o?d=new os(i,ns):d=new ir(i,ns);let c=this.runWebGLProgram(d,[{dataId:e,shape:i,dtype:a}],a),h=this.readSync(c.dataId);return this.disposeIntermediateTensorInfo(c),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return n;let l=this.activeTimers!=null,u;l&&(u=w.now());let p;if(a==="complex64"){let d=this.readSync(r.real.dataId),c=this.readSync(r.imag.dataId);p=N.mergeRealAndImagArrays(d,c)}else p=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(m=>h.push(m))}let t=this.texData.get(e),{values:n,shape:a,slice:r,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(r!=null){let h;o?h=new os(a,ns):h=new ir(a,ns);let m=this.runWebGLProgram(h,[{dataId:e,shape:a,dtype:s}],s),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(n!=null)return this.convertAndCacheOnCPU(e);if(G().getBool("DEBUG")&&!G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&G().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,u;if(s!=="complex64"&&G().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(h.texture.texture,...Hh(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(s==="complex64"){let h=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=h[0],f=h[1];p=N.mergeRealAndImagArrays(m,f)}else if(l==null)p=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(a);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let h=this.gpgpu.gl;de(h,()=>h.deleteBuffer(l))}let d=this.convertAndCacheOnCPU(e,p),c=this.pendingRead.get(e);return this.pendingRead.delete(e),c.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Aa().removeDataId(e,this),this.pendingDeletes--),d}readToGPU(e,t={}){let n=this.texData.get(e),{values:a,shape:r,slice:s,dtype:i,isPacked:o,texture:l}=n;if(i==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(s!=null){let c;o?c=new os(r,ns):c=new ir(r,ns);let h=this.runWebGLProgram(c,[{dataId:e,shape:r,dtype:i}],i),m=this.readToGPU(h,t);return this.disposeIntermediateTensorInfo(h),m}if(l==null)throw a!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(e,t.customTexShape),p=Aa().makeTensorFromTensorInfo(u),d=this.texData.get(u.dataId);return Object.assign({tensorRef:p},d.texture)}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(a=>w.decodeString(a));return ze(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!TE(n))throw G().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(e){let{shape:t,dtype:n,isPacked:a}=this.texData.get(e),r=w.sizeFromShape(t);if(G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let d=this.decode(e),c=this.texData.get(d.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(c.texture.texture,...Hh(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(d),h}let s=G().getBool("WEBGL_PACK")&&a===!0,i=s?pc(t):t,o=s?new c9(i):new p9(i),l=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),u=this.texData.get(l.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),p}timerAvailable(){return G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){let t=this.activeTimers,n=[],a=!1;this.programTimersStack==null?(this.programTimersStack=n,a=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=w.flatten(this.activeTimers.map(o=>o.query)).filter(o=>o!=null),s=w.flatten(this.activeTimers.map(o=>o.name)).filter(o=>o!=null);this.activeTimers=t,a&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(r);i.kernelMs=w.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:w.now(),endMs:null}}endTimer(e){return G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=w.now(),e)}async getQueryTime(e){if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:a,usage:r,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(a,n),this.textureManager.releaseTexture(t,a,r,s)));let u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=_Q){return G().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&w.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){N.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return SQ(e.shape,t)}packedUnaryOp(e,t,n){let a=new os(e.shape,t),r=this.compileAndRun(a,[e],n);return Aa().makeTensorFromTensorInfo(r)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let a=xA(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,a)}if(G().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,xS,e.dtype);let t=new ir(e.shape,xS),n=this.compileAndRun(t,[e]);return Aa().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let r=n.map(s=>w.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:t}}makeOutput(e,t,n){return Aa().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){let t=new IQ(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new oQ(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[wi(e.shape),...ki(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},r=[wi(t),...ki(t)],s=new kA(r,n),i=!0,o=[n],l=this.runWebGLProgram(s,[a],e.dtype,o,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){let n=this.texData.get(e),{isPacked:a,shape:r,dtype:s}=n;if(t!=null){let d=w.sizeFromShape(r),c=t[0]*t[1]*4;w.assert(d<=c,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let i=pc(r),o;a?o=new u9(i):o=new l9(i);let l=!0,u=[t!=null?t:Hh(i)],p=this.runWebGLProgram(o,[{shape:i,dtype:s,dataId:e}],s,u,l,t);return{dtype:s,shape:r,dataId:p.dataId}}runWebGLProgram(e,t,n,a,r=!1,s){let i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===Ec.DENSE){let g=s!=null?s:Hh(e.outputShape);o.texShape=g.map(b=>b*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),w.sizeFromShape(i.shape)===0)return o.values=w.getTypedArrayFromDType(i.dtype,0),i;let l=[],u=t.map(g=>{if(g.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(g.dataId);if(b.texture==null){if(!e.packedInputs&&w.sizeFromShape(g.shape)<=G().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:b.values};e.packedInputs&&(b.isPacked=!0,b.shape=g.shape)}if(this.uploadToGPU(g.dataId),!!b.isPacked!=!!e.packedInputs)g=b.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),b=this.texData.get(g.dataId);else if(b.isPacked&&!Ac(b.shape,g.shape)){let y=g,x=g.shape;g.shape=b.shape,g=this.packedReshape(g,x),l.push(g),b=this.texData.get(g.dataId),y.shape=x}return{shape:g.shape,texData:b,isUniform:!1}});this.uploadToGPU(i.dataId);let p={shape:i.shape,texData:o,isUniform:!1},d=o9(e,u,p),c=this.getAndSaveBinary(d,()=>s9(this.gpgpu,e,u,p)),h=this.activeTimers!=null,m;h&&(m=this.startTimer()),G().get("ENGINE_COMPILE_ONLY")||i9(this.gpgpu,c,u,p,a),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),h&&(m=this.endTimer(m),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(m)}));let f=G().get("WEBGL_FLUSH_THRESHOLD");if(f>0){let g=w.now();g-this.lastGlFlushTime>f&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!G().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&r===!1){let g=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),g}return i}compileAndRun(e,t,n,a,r=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,a,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(G().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=P(()=>{if(!G().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=G().getBool("DEBUG");G().set("DEBUG",!1);let t=this.abs(ve(1e-8)).dataSync()[0];if(G().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?NQ:TQ}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:a,values:r,texture:s,usage:i,isPacked:o}=t;if(s!=null)return;let l=this.activeTimers!=null,u;l&&(u=w.now());let p=t.texShape;if(p==null&&(p=UE(n,o),t.texShape=p),r!=null){let d=pc(n),c,h=p[1],m=p[0],f=r instanceof Uint8Array||r instanceof Uint8ClampedArray;(o||!f)&&([h,m]=xp(p[0],p[1])),o?c=new h9(d,f):c=new fS(d,f);let g=f?[m,h]:p,b=this.makeTensorInfo(g,a),y=this.texData.get(b.dataId);f?y.usage=ha.PIXELS:y.usage=ha.UPLOAD,y.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),h,m,r);let x=[[m,h]],v=!0,I=this.runWebGLProgram(c,[b],a,x,v),T=this.texData.get(I.dataId);t.texShape=T.texShape,t.isPacked=T.isPacked,t.usage=T.usage,G().get("ENGINE_COMPILE_ONLY")?this.disposeData(I.dataId):(t.texture=T.texture,t.values=null,this.texData.delete(I.dataId)),this.disposeIntermediateTensorInfo(b),l&&(this.uploadWaitMs+=w.now()-u)}else{let d=this.acquireTexture(p,i,a,o);t.texture=d}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:a}=n;return t!=null&&(n.values=FQ(t,a)),n.values}acquireTexture(e,t,n,a){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,a)}computeBytes(e,t){return e[0]*e[1]*w.bytesPerElement(t)}checkCompileCompletion(){for(let[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){let e=[];if(this.gpgpu.parallelCompilationExtension){for(let[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(let[,t]of Object.entries(this.binaryCache)){let n=new Promise(a=>{try{this.checkCompletion_(t),a(!0)}catch(r){throw r}});e.push(n)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await Qw(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(Q1(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);let{variablesLocations:t,customUniformLocations:n,infLoc:a,nanLoc:r,outShapeLocation:s,outShapeStridesLocation:i,outTexShapeLocation:o}=eA(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=a,e.nanLoc=r,e.outShapeLocation=s,e.outShapeStridesLocation=i,e.outTexShapeLocation=o}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";let{texture:a,height:r,width:s,channels:i}=e,o=Aa().backend;if(!o.gpgpu.gl.isTexture(a))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=o.writeTexture(a,t,n,r,s,i);return Aa().makeTensorFromDataId(l,t,n,o)}};Qf.nextDataId=0;function FQ(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let a=0;a<n.length;++a)n[a]=Math.round(e[a]);return n}else throw new Error(`Unknown dtype ${t}`)}var $Q="4.7.0";function IA(){G().set("WEBGL_FORCE_F16_TEXTURES",!0)}od.isBrowser()&&Zm("webgl",()=>new Qf,2);var DQ={forceHalfFloat:IA},uk=`
  if (isnan(a)) return a;
  if (isnan(b)) return b;
`,Ii=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=N.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=vn(this.outputShape.length),this.userCode=`
      float binaryOperation(float a, float b) {
        ${e}
      }
 
      void main() {
        float a = getAAtOutCoords();
        float b = getBAtOutCoords();
        setOutput(binaryOperation(a, b));
      }
    `}},el=`
  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;
`,Np=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length;this.enableShapeUniforms=vn(r);let s="";if(a)if(r===0||w.sizeFromShape(this.outputShape)===1)s=`
          result.y = 0.;
          result.z = 0.;
          result.w = 0.;
        `;else if(s=`
          ${dt(r)} coords = getOutputCoords();
        `,r===1)this.enableShapeUniforms?s+=`
            result.y = (coords + 1) >= outShape ? 0. : result.y;
            result.z = 0.;
            result.w = 0.;
          `:s+=`
            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
            result.z = 0.;
            result.w = 0.;
          `;else{let i=Sn("coords",r);this.enableShapeUniforms?s+=`
            bool nextRowOutOfBounds =
              (${i[r-2]} + 1) >= outShape[${r} - 2];
            bool nextColOutOfBounds =
              (${i[r-1]} + 1) >= outShape[${r} - 1];
            result.y = nextColOutOfBounds ? 0. : result.y;
            result.z = nextRowOutOfBounds ? 0. : result.z;
            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
          `:s+=`
            bool nextRowOutOfBounds =
              (${i[r-2]} + 1) >= ${this.outputShape[r-2]};
            bool nextColOutOfBounds =
              (${i[r-1]} + 1) >= ${this.outputShape[r-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) {
        ${e}
      }
 
      void main() {
        vec4 a = getAAtOutCoords();
        vec4 b = getBAtOutCoords();
 
        vec4 result = binaryOperation(a, b);
        ${s}
 
        setOutput(result);
      }
    `}};function ra(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var RQ={kernelName:to,backendName:"webgl",kernelFunc:ra};function Ms(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.makeTensorInfo(a.shape,"complex64"),i=n.texData.get(s.dataId),o=ra({inputs:{x:a},backend:n}),l=ra({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},s}var MQ={kernelName:Om,backendName:"webgl",kernelFunc:Ms},SA="return (a < 0.) ? b * a : a;",NA=`
  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function PQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",w.createScalarValue(s,"float32")),o=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Np(NA,r.shape,i.shape):new Ii(SA,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}var OQ={kernelName:so,backendName:"webgl",kernelFunc:PQ},TA="return (a < 0.) ? b * a : a;",CA=`
  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function LQ(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Np(CA,a.shape,r.shape):new Ii(TA,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],"float32")}var zQ={kernelName:ko,backendName:"webgl",kernelFunc:LQ},Tp="if (isnan(x)) return x;";function Ze({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:a}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&n!=null){let d=o.texData.get(i.dataId),c=n(d.values,l);return o.makeTensorInfo(i.shape,l,c)}let u=G().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,p;return u?p=new os(i.shape,t):p=new ir(i.shape,e),o.runWebGLProgram(p,[i],l)}}function fn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,p=o;if(a&&l.dtype==="complex64"){let m=p.texData.get(l.dataId),f=p.texData.get(u.dataId),[g,b]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(x=>{let[v,I]=x,T={dataId:v.dataId,dtype:v.dtype,shape:l.shape},C={dataId:I.dataId,dtype:I.dtype,shape:u.shape},E=new Ii(e,l.shape,u.shape);return p.runWebGLProgram(E,[T,C],ba(v.dtype,I.dtype))}),y=Ms({inputs:{real:g,imag:b},backend:p});return p.disposeIntermediateTensorInfo(g),p.disposeIntermediateTensorInfo(b),y}let d=s||ba(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||p.shouldExecuteOnCPU([l,u]))&&r!=null){let m=p.texData.get(l.dataId).values,f=p.texData.get(u.dataId).values,g=l.dtype==="string"?N.fromUint8ToStringArray(m):m,b=l.dtype==="string"?N.fromUint8ToStringArray(f):f,[y,x]=r(l.shape,u.shape,g,b,d),v=p.makeTensorInfo(x,d),I=p.texData.get(v.dataId);return I.values=y,v}let c=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return c?h=new Np(t,l.shape,u.shape,n):h=new Ii(e,l.shape,u.shape),p.runWebGLProgram(h,[l,u],d)}}function Fc(e,t=!1){if(e==="linear")return t?yQ:hQ;if(e==="relu")return t?vQ:fQ;if(e==="elu")return t?xQ:mQ;if(e==="relu6")return t?wQ:gQ;if(e==="prelu")return t?CA:TA;if(e==="leakyrelu")return t?NA:SA;if(e==="sigmoid")return t?kQ:bQ;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var _A=class{constructor(e,t,n,a=!1,r=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=vn(this.outputShape.length);let u=a?e[1]:e[2],p=Math.ceil(u/2),d=a?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",h=a?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f=`vec4 activation(vec4 a) {
          vec4 b = getPreluActivationWeightsAtOutCoords();
          ${i}
        }`:l?f=`vec4 activation(vec4 a) {
          vec4 b = getLeakyreluAlphaAtOutCoords();
          ${i}
        }`:f=`vec4 activation(vec4 x) {
          ${i}
        }`,g="result = activation(result);");let b=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let y="rc.x",x="rc.x";e[0]<t[0]?y=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`
      ${f}
      // Don't use uniform for sharedDimensionPacked for performance.
      const float sharedDimension = ${p}.0;
 
      vec4 dot2x2ARowBCol(ivec3 rc) {
        vec4 result = vec4(0);
        int batchA = ${y};
        int batchB = ${x};
        for (int i = 0; i < ${p}; i++) {
          vec4 a = getMatrixA(batchA, ${d});
          vec4 b = getMatrixB(batchB, ${c});
 
          // These swizzled products need to be separately added.
          // See: https://github.com/tensorflow/tfjs/issues/1735
          result += (${h[0]} * ${m[0]});
          result += (${h[1]} * ${m[1]});
        }
        return result;
      }
 
      void main() {
        ivec3 rc = getOutputCoords();
        vec4 result = dot2x2ARowBCol(rc);
 
        ${b}
 
        ${g}
 
        setOutput(result);
      }
    `}},vS={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},wS=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=N.assertAndGetBroadcastShape(t,n),this.userCode=`
      float binaryOpComplex(
          float areal, float aimag, float breal, float bimag) {
        ${e}
      }
 
      void main() {
        float areal = getARealAtOutCoords();
        float aimag = getAImagAtOutCoords();
        float breal = getBRealAtOutCoords();
        float bimag = getBImagAtOutCoords();
        setOutput(binaryOpComplex(areal, aimag, breal, bimag));
      }
    `}},kS="return a * b;";function pk(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=N.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),u=new wS(vS.REAL,a.shape,r.shape),p=new wS(vS.IMAG,a.shape,r.shape),d=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:a.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],c=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(p,d,"float32"),m=Ms({inputs:{real:c,imag:h},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}if(n.shouldExecuteOnCPU([a,r])){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),[u,p]=P9(a.shape,r.shape,o.values,l.values,s),d=n.makeTensorInfo(p,s),c=n.texData.get(d.dataId);return c.values=u,d}let i;return G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Np(kS,a.shape,r.shape):i=new Ii(kS,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var WQ={kernelName:yo,backendName:"webgl",kernelFunc:pk};function BQ(e,t,n){let a=[wi(e.shape),...ki(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[wi(t),...ki(t)],i=new kA(s,a),o=!0,l=[a],u=n.runWebGLProgram(i,[r],e.dtype,l,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function ce(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=n,o=w.sizeFromShape(r.shape),l=w.inferFromImplicitShape(s,o),u=w.sizeFromShape(l);w.assert(o===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let p=i.texData.get(r.dataId);return p.isPacked&&!Ac(r.shape,l)&&!(p.texture!==null&&Ac(p.shape,l))?BQ(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var VQ={kernelName:qu,backendName:"webgl",kernelFunc:ce},IS=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i=Math.floor(n/4)*4,o=n%4,l="sumValue += dot(values, ones);";if(t!=null){let p=1/t;l=`sumValue += dot(values * ${w.isInt(p)?p.toPrecision(2):p}, ones);`}let u="";r%n>0&&(u=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return 0.0;
        }
      `),this.userCode=`
      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
 
      float getValue(int batch, int inIdx) {
        ${u}
        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 < ${i}; 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 + ${i};
        if (${o===1}) {
          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
 
          ${l}
        } else if (${o===2}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1), 0.0, 0.0);
 
          ${l}
        } else if (${o===3}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2), 0.0);
 
          ${l}
        }
        setOutput(sumValue);
      }
    `}},UQ=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(n/4)*4,p=n%4,d=`
      if (${t==="sum"}) {
        sumValue += dot(values, ones);
      } else if (${t==="prod"}) {
        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
        prodValue *= tmp[0] * tmp[1];
      } else {
        minMaxValue = ${o}(values, minMaxValue);
        if (${t==="min"} || ${t==="max"}) {
          minMaxValue = ${o}(values, minMaxValue);
          bvec4 isNaN = isnan(values);
          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
            minMaxValue = vec4(NAN);
          }
        }
      }
    `,c="vec4";t==="all"?(i="1.0",d=`
        bool reducedAllValue = all(values);
        float floatedReducedAllValue = float(reducedAllValue);
        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
      `,c="bvec4"):t==="any"&&(i="0.0",d=`
        bool reducedAnyValue = any(values);
        float floatedReducedAnyValue = float(reducedAnyValue);
        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
      `,c="bvec4");let h="";r%n>0&&(h=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return initializationValue;
        }
      `),this.userCode=`
      const float initializationValue = ${i};
      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
 
      float getValue(int batch, int inIdx) {
        ${h}
        return getX(batch, inIdx);
      }
 
      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = outIdx * ${n};
 
        vec4 minMaxValue = vec4(${i});
        float prodValue = 1.0;
        float sumValue = 0.0;
        float allValue = 1.0;
        float anyValue = 0.0;
 
        for (int i = 0; i < ${u}; i += 4) {
          int inIdx = inOffset + i;
          ${c} values = ${c}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            getValue(batch, inIdx + 3)
          );
 
          ${d}
        }
 
        int inIdx = inOffset + ${u};
        if (${p===1}) {
          ${c} values = ${c}(
            getValue(batch, inIdx),
            initializationValue,
            initializationValue,
            initializationValue
          );
 
          ${d}
        } else if (${p===2}) {
          ${c} values = ${c}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            initializationValue,
            initializationValue
          );
 
          ${d}
        } else if (${p===3}) {
          ${c} values = ${c}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            initializationValue
          );
 
          ${d}
        }
        setOutput(${l});
      }
    `}};function GQ(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],a=N.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function tl(e,t,n,a){let r=GQ(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:u}=r[i],p,d;n==="mean"?p=i===0?new IS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new IS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):p=new UQ({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},n),d=s,s=a.runWebGLProgram(p,[s],t),d.dataId!==e.dataId&&a.disposeIntermediateTensorInfo(d)}return s}var HQ=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;let a=dt(this.rank),r=qQ(t);this.userCode=`
    void main() {
      ${a} resRC = getOutputCoords();
      setOutput(getA(${r}));
    }
    `}};function qQ(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],a=new Array(t);for(let r=0;r<e.length;r++)a[e[r]]=n[r];return a.join()}var jQ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let a=dt(this.rank),r=wA("rc",this.rank),s=new Array(this.rank);for(let u=0;u<t.length;u++)s[t[u]]=r[u];let i=`vec2(${s.slice(-2).join()})`,o=`++${r[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
    void main() {
      ${a} rc = getOutputCoords();
      vec4 result = vec4(0.);
      result[0] = ${l};
      if(${o}) {
        result[1] = ${l};
      }
      --${r[this.rank-1]};
      if(++${r[this.rank-2]} < ${n[this.rank-2]}) {
        result[2] = ${l};
        if(${o}) {
          result[3] = ${l};
        }
      }
      setOutput(result);
    }
    `}};function eg(e,t,n){let a=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jQ(e.shape,t):new HQ(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function KQ(e,t,n,a){let r=t,s=e.shape.length,i=w.parseAxisParam(r,e.shape),o=i,l=N.getAxesPermutation(o,s),u=l!=null,p=e;u&&(p=eg(e,l,a),o=N.getInnerMostAxes(o.length,s)),N.assertAxesAreInnerMostDims("sum",o,s);let[d,c]=N.computeOutAndReduceShapes(p.shape,o),h=d;n&&(h=N.expandShapeToKeepDim(d,i));let m=w.sizeFromShape(c),f=w.sizeFromShape(e.shape)/m,g=ce({inputs:{x:p},attrs:{shape:[f,m]},backend:a}),b=Ym(e.dtype),y=tl(g,b,"sum",a),x=ce({inputs:{x:y},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(y),u&&a.disposeIntermediateTensorInfo(p),x}function tg(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return KQ(r,s,i,n)}var XQ={kernelName:zo,backendName:"webgl",kernelFunc:tg};function Nn(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{perm:s}=a,i=n,o=r.shape.length,l=new Array(o);for(let p=0;p<l.length;p++)l[p]=r.shape[s[p]];let u;if(i.shouldExecuteOnCPU([r])){let p=i.texData.get(r.dataId).values,d=lk(p,r.shape,r.dtype,s,l);u=i.makeTensorInfo(l,r.dtype);let c=i.texData.get(u.dataId);c.values=d}else u=eg(r,s,i);return u}var YQ={kernelName:$r,backendName:"webgl",kernelFunc:Nn},EA=1e3;function Em({a:e,b:t,transposeA:n,transposeB:a,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,p=t.shape.length,d=n?e.shape[u-2]:e.shape[u-1],c=a?t.shape[p-1]:t.shape[p-2],h=n?e.shape[u-1]:e.shape[u-2],m=a?t.shape[p-2]:t.shape[p-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(f),y=w.sizeFromShape(g),x=pp.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,m]);w.assert(d===c,()=>`Error in matMul: inner shapes (${d}) and (${c}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`);let v=n?[b,d,h]:[b,h,d],I=a?[y,m,c]:[y,c,m],T=ce({inputs:{x:e},backend:r,attrs:{shape:v}}),C=ce({inputs:{x:t},backend:r,attrs:{shape:I}}),E=[T,C],F=Math.max(b,y),D=n?T.shape[1]:T.shape[2],$=s!=null,S=i!=null,M=l==="leakyrelu",B=l!=null?Fc(l,!0):null,U=$||S||M||B!=null,H;if((h===1||m===1)&&D>EA&&U===!1){let K=T,Z=C;n&&(K=Nn({inputs:{x:T},backend:r,attrs:{perm:[0,2,1]}}),E.push(K)),a&&(Z=Nn({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),E.push(Z));let J=m!==1,ee=m===1,ae=K;J&&(ae=ce({inputs:{x:K},backend:r,attrs:{shape:[F,D,1]}}),E.push(ae));let te=m===1?2:1,re=Z;ee&&(re=ce({inputs:{x:Z},backend:r,attrs:{shape:[F,1,D]}}),E.push(re));let ie=pk({inputs:{a:ae,b:re},backend:r});H=tg({inputs:{x:ie},backend:r,attrs:{axis:te,keepDims:!0}}),E.push(ie)}else{let K=ba(e.dtype,t.dtype),Z=new _A(v,I,[F,h,m],n,a,$,B,S,M),J=[T,C];if(s!=null&&J.push(s),S&&J.push(i),M){let ee=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));J.push(ee),E.push(ee)}H=r.runWebGLProgram(Z,J,K)}let j=ce({inputs:{x:H},backend:r,attrs:{shape:x}});E.push(H);for(let K of E)r.disposeIntermediateTensorInfo(K);return j}function ZQ(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a;return Em({a:r,b:s,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:d,activation:p})}var JQ={kernelName:oi,backendName:"webgl",kernelFunc:ZQ},SS="return abs(x);";function QQ(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])&&a.dtype!=="complex64"){let s=n.texData.get(a.dataId),i=xA(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new os(a.shape,SS):r=new ir(a.shape,SS),n.runWebGLProgram(r,[a],a.dtype)}var eee={kernelName:lu,backendName:"webgl",kernelFunc:QQ},tee=Oa+`
  if (abs(x) > 1.) {
    return NAN;
  }
  return acos(x);
`,nee=Ze({opSnippet:tee}),aee={kernelName:Ti,backendName:"webgl",kernelFunc:nee},ree=Oa+`
  if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,see=Ze({opSnippet:ree}),iee={kernelName:Ci,backendName:"webgl",kernelFunc:see},NS="return a + b;",oee=fn({opSnippet:NS,packedOpSnippet:NS,supportsComplex:!0,cpuKernelImpl:f9}),lee={kernelName:Is,backendName:"webgl",kernelFunc:oee},uee=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let n=[];this.variableNames.forEach(r=>{n.push(`float v${r} = get${r}AtOutCoords();`)});let a=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
      void main() {
        ${n.join(`
        `)}
 
        float result = ${a};
        setOutput(result);
      }
    `}},pee=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let n=[];this.variableNames.forEach(r=>{n.push(`vec4 v${r} = get${r}AtOutCoords();`)});let a=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
      void main() {
        ${n.join(`
        `)}
 
        vec4 result = ${a};
        setOutput(result);
      }
    `}};function nm(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return ra({inputs:{x:a[0]},backend:n});if(a.length>G().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=nm({inputs:a.slice(0,o),backend:n}),u=nm({inputs:a.slice(o),backend:n});return nm({inputs:[l,u],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>ba(o,l)),s=a.map(o=>o.shape),i=G().getBool("WEBGL_PACK")?new pee(a[0].shape,s):new uee(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var cee={kernelName:_i,backendName:"webgl",kernelFunc:nm};function dee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=N.getAxesPermutation(u,o),d=r;p!=null&&(d=Nn({inputs:{x:r},backend:n,attrs:{perm:p}}),u=N.getInnerMostAxes(u.length,o)),N.assertAxesAreInnerMostDims("all",u,o);let[c,h]=N.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=tl(f,f.dtype,"all",n),b;if(i){let y=N.expandShapeToKeepDim(c,l);b=ce({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ce({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),b}var hee={kernelName:uu,backendName:"webgl",kernelFunc:dee};function mee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=N.getAxesPermutation(u,o),d=r;p!=null&&(d=Nn({inputs:{x:r},backend:n,attrs:{perm:p}}),u=N.getInnerMostAxes(u.length,o)),N.assertAxesAreInnerMostDims("any",u,o);let[c,h]=N.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=tl(f,f.dtype,"any",n),b;if(i){let y=N.expandShapeToKeepDim(c,l);b=ce({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ce({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),b}var fee={kernelName:pu,backendName:"webgl",kernelFunc:mee},gee=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:a,batchSize:r,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];let i=t==="max"?">":"<",o=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 * ${a};
 
        int bestIndex = inOffset;
        float bestValue = getA(batch, bestIndex);
 
        for (int i = 0; i < ${a}; i++) {
          int inIdx = ${o};
          float candidate = getA(batch, inIdx);
          if (candidate ${i} bestValue) {
            bestValue = candidate;
            bestIndex = inIdx;
          }
        }
        setOutput(float(bestIndex));
      }
    `}},bee=class{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let r=e[e.length-1],s=Math.ceil(r/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=dt(o),u=Sn("coords",o),p,d;if(s===1){d=o+1;let C=dt(d);p=`
        ${C} sourceLocR = ${C}(${u.join()}, 0);
        ++${u[o-1]};
        ${C} sourceLocG = ${C}(${u.join()}, 0);
        ++${u[o-2]};
        ${C} sourceLocA = ${C}(${u.join()}, 0);
        --${u[o-1]};
        ${C} sourceLocB = ${C}(${u.join()}, 0);
        --${u[o-2]};`}else d=o,p=`
        ${l} sourceLocR = coords;
        ++${u[o-1]};
        ${l} sourceLocG = coords;
        ++${u[o-2]};
        ${l} sourceLocA = coords;
        --${u[o-1]};
        ${l} sourceLocB = coords;
        --${u[o-2]};`;let c=["x","y","z","w","u","v"].slice(0,d),h="."+c[d-1],m=c.map(C=>"int "+C),f=Sn("sourceLocR",d-1).concat("inIdx.r"),g=Sn("sourceLocG",d-1).concat("inIdx.g"),b=Sn("sourceLocB",d-1).concat("inIdx.b"),y=Sn("sourceLocA",d-1).concat("inIdx.a"),x=n==="max"?"greaterThan":"lessThan",v=a?"":`
          inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
                             getBestIndicesAChannel(${g.join()}),
                             getBestIndicesAChannel(${b.join()}),
                             getBestIndicesAChannel(${y.join()})));`,I=`vec4(
            getAChannel(${f.join()}),
            hasNextCol ? getAChannel(${g.join()}) : 0.,
            hasNextRow ? getAChannel(${b.join()}) : 0.,
            hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`,T=a?"":`
      float getBestIndicesAChannel(${m.join()}) {
        return getChannel(getBestIndicesA(${c.join()}),
                                          vec2(${c.slice(-2).join()}));
      }`;this.userCode=`
      float getAChannel(${m.join()}) {
        return getChannel(getA(${c.join()}),
                               vec2(${c.slice(-2).join()}));
      }
      ${T}
      void main() {
        ${l} coords = getOutputCoords();
        bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};
        bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};
        ${p}
        ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
          sourceLocB${h}, sourceLocA${h}) * ${t};
        ivec4 inIdx = srcIdx;
        vec4 bestIndex = vec4(inIdx);
        vec4 bestValue = ${I};
 
        for (int i = 0; i < ${t}; i++) {
          inIdx = srcIdx;
          ${v}
          vec4 candidate = ${I};
          bvec4 nan = isnan(candidate);
          bvec4 replace = bvec4(
            vec4(${x}(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 AA(e,t,n,a=null){let r=t.shape[0],s=t.shape[1];a!=null&&(r=a.shape[0],s=a.shape[1]);let i=N.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new gee(o,n,a==null),u=[t];a!=null&&u.push(a);let p=e.runWebGLProgram(l,u,"int32");if(p.shape[1]===1)return p;let d=AA(e,t,n,p);return e.disposeIntermediateTensorInfo(p),d}function FA(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=N.computeOptimalWindowSize(s),o=new bee(r,i,n,a==null),l=a==null?[t]:[t,a],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let p=FA(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}return u}function $A(e,t,n,a){let r=[n];if(N.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!G().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=e.texData.get(t.dataId),o=i!==null&&i.isPacked,l=t;o&&(l=e.unpackTensor(t),s.push(l));let[u,p]=N.computeOutAndReduceShapes(l.shape,r),d=w.sizeFromShape(p),c=ce({inputs:{x:l},backend:e,attrs:{shape:[-1,d]}});s.push(c);let h=AA(e,c,a);s.push(h);let m=ce({inputs:{x:h},backend:e,attrs:{shape:u}});return s.forEach(f=>e.disposeIntermediateTensorInfo(f)),m}return FA(e,t,a)}function yee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=N.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Nn({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let p=$A(n,l,i[0],"max");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),p}var xee={kernelName:cu,backendName:"webgl",kernelFunc:yee};function vee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=N.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Nn({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let p=$A(n,l,i[0],"min");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),p}var wee={kernelName:du,backendName:"webgl",kernelFunc:vee},kee=Oa+`
  if (abs(x) > 1.) {
    return NAN;
  }
  return asin(x);
`,Iee=Ze({opSnippet:kee}),See={kernelName:Ei,backendName:"webgl",kernelFunc:Iee},Nee=Oa+"return log(x + sqrt(x * x + 1.0));",Tee=Ze({opSnippet:Nee}),Cee={kernelName:Ai,backendName:"webgl",kernelFunc:Tee},_ee=Oa+`
  return atan(x);
`,Eee=Ze({opSnippet:_ee}),Aee={kernelName:Fi,backendName:"webgl",kernelFunc:Eee},Fee=uk+`
  return atan(a, b);
`,$ee=`
  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);
  `+el+`
  return result;
`,Dee=fn({opSnippet:Fee,packedOpSnippet:$ee}),Ree={kernelName:Di,backendName:"webgl",kernelFunc:Dee},Mee=Oa+`
  if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Pee=Ze({opSnippet:Mee}),Oee={kernelName:$i,backendName:"webgl",kernelFunc:Pee},$c=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,c=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f=`((batch  * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(m||(b="-1.0 / 1e-20"),n){let C=">=";this.userCode=`
        const ivec2 strides = ivec2(${i}, ${o});
        const ivec2 pads = ivec2(${c}, ${h});
 
        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 >= ${e.inHeight}) {
              continue;
            }
 
            for (int wC = 0; wC < ${d};
                wC += ${u}) {
              int xC = xCCorner + wC;
 
              if (xC < 0 || xC >= ${e.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 ${C} currMinMaxValue) {
                minMaxValue = value;
                minMaxValueFound = 1.0;
                minMaxPosition = ${a?r?f:g:`wR * ${d} + wC`};
              }
            }
          }
          setOutput(float(minMaxPosition));
        }
      `;return}let y="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / max(count, 1.0)");let v=Math.floor(s/4)*4,I=s%4,T=`
      if (${m}) {
        avgValue += dot(values, ones);
      } else {
        minMaxValue = ${y}(values, minMaxValue);
      }
    `;this.userCode=`
      const ivec2 strides = ivec2(${i}, ${o});
      const ivec2 pads = ivec2(${c}, ${h});
      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 >= ${e.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 >= ${e.inHeight}) {
            continue;
          }
 
          for (int wC = 0; wC < ${v}; wC += 4) {
            int xC = xCCorner + wC * ${u};
 
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${u}, d),
              getValue(batch, xR, xC + 2 * ${u}, d),
              getValue(batch, xR, xC + 3 * ${u}, d)
            );
 
            ${T}
          }
 
          int xC = xCCorner + ${v};
          if (${I===1}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              initializationValue,
              initializationValue,
              initializationValue
            );
 
            ${T}
          } else if (${I===2}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${u}, d),
              initializationValue,
              initializationValue
            );
 
            ${T}
          } else if (${I===3}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${u}, d),
              getValue(batch, xR, xC + 2 * ${u}, d),
              initializationValue
            );
 
            ${T}
          }
        }
        setOutput(${x});
      }
    `}},ck=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,p=e.dilationHeight,d=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",x="0.0";if(y||(x="-1.0 / 1e-20"),n){let F=">=";this.userCode=`
        const ivec3 strides =
            ivec3(${i}, ${o}, ${l});
        const ivec3 pads = ivec3(${f}, ${g}, ${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 < ${c};
              wD += ${u}) {
            int xD = xDCorner + wD;
 
            if (xD < 0 || xD >= ${e.inDepth}) {
              continue;
            }
 
            for (int wR = 0; wR < ${h};
                wR += ${p}) {
              int xR = xRCorner + wR;
 
              if (xR < 0 || xR >= ${e.inHeight}) {
                continue;
              }
 
              for (int wC = 0; wC < ${m};
                  wC += ${d}) {
                int xC = xCCorner + wC;
 
                if (xC < 0 || xC >= ${e.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 ${F} currMinMaxValue) {
                  minMaxValue = value;
                  minMaxValueFound = 1.0;
                  minMaxPosition = ${a?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${m} +
                      wR * ${m} + wC`};
                }
              }
            }
          }
          setOutput(float(minMaxPosition));
        }
      `;return}let v="max",I=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(I="avgValue / max(count, 1.0)");let T=Math.floor(s/4)*4,C=s%4,E=`
      if (${y}) {
        avgValue += dot(values, ones);
      } else {
        minMaxValue = ${v}(values, minMaxValue);
      }
    `;this.userCode=`
      const ivec3 strides =
        ivec3(${i}, ${o}, ${l});
      const ivec3 pads = ivec3(${f}, ${g}, ${b});
      const float initializationValue = ${x};
      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 >= ${e.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(${x});
        float avgValue = 0.0;
        count = 0.0;
 
        for (int wD = 0; wD < ${c};
            wD += ${u}) {
          int xD = xDCorner + wD;
 
          if (xD < 0 || xD >= ${e.inDepth}) {
            continue;
          }
 
          for (int wR = 0; wR < ${h};
            wR += ${p}) {
            int xR = xRCorner + wR;
 
            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }
 
            for (int wC = 0; wC < ${T}; wC += 4) {
              int xC = xCCorner + wC * ${d};
 
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${d}, ch),
                getValue(batch, xD, xR, xC + 2 * ${d}, ch),
                getValue(batch, xD, xR, xC + 3 * ${d}, ch)
              );
 
              ${E}
            }
 
            int xC = xCCorner + ${T};
            if (${C===1}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                initializationValue,
                initializationValue,
                initializationValue
              );
 
              ${E}
            } else if (${C===2}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${d}, ch),
                initializationValue,
                initializationValue
              );
 
              ${E}
            } else if (${C===3}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${d}, ch),
                getValue(batch, xD, xR, xC + 2 * ${d}, ch),
                initializationValue
              );
 
              ${E}
            }
          }
        }
        setOutput(${I});
      }
    `}};function Lee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;vp(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=N.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))return ra({inputs:{x:r},backend:n});let d=new $c(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var zee={kernelName:Ri,backendName:"webgl",kernelFunc:Lee};function Wee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=[1,1,1],d=N.computePool3DInfo(r.shape,s,i,p,o,l,u),c=new ck(d,"avg",!1);return n.runWebGLProgram(c,[r],"float32")}var Bee={kernelName:hu,backendName:"webgl",kernelFunc:Wee},Vee=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,p=l-1-e.padInfo.left,d=1/(t*n);this.userCode=`
      const ivec2 pads = ivec2(${u}, ${p});
      const float avgMultiplier = float(${d});
 
      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 < ${o};
            wR += ${s}) {
          float dyR = float(dyRCorner + wR) / ${a}.0;
 
          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
 
          for (int wC = 0; wC < ${l};
            wC+= ${i}) {
            float dyC = float(dyCCorner + wC) / ${r}.0;
 
            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
                fract(dyC) > 0.0) {
              continue;
            }
            int idyC = int(dyC);
 
            float dyValue = getDy(b, idyR, idyC, d);
 
            dotProd += dyValue * avgMultiplier;
          }
        }
        setOutput(dotProd);
      }
    `}},Uee=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,c=e.effectiveFilterWidth,h=p-1-e.padInfo.front,m=d-1-e.padInfo.top,f=c-1-e.padInfo.left,g=1/(t*n*a);this.userCode=`
      const ivec3 pads = ivec3(${h}, ${m}, ${f});
      const float avgMultiplier = float(${g});
 
      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 += ${o}) {
          float dyD = float(dyDCorner + wD) / ${r}.0;
 
          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
            continue;
          }
          int idyD = int(dyD);
 
          for (int wR = 0; wR < ${d};
              wR += ${l}) {
            float dyR = float(dyRCorner + wR) / ${s}.0;
 
            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
                fract(dyR) > 0.0) {
              continue;
            }
            int idyR = int(dyR);
 
            for (int wC = 0; wC < ${c};
                wC += ${u}) {
              float dyC = float(dyCCorner + wC) / ${i}.0;
 
              if (dyC < 0.0 || dyC >= ${e.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 Gee(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=a,d=[1,1,1],c=N.computePool3DInfo(i.shape,o,l,d,u,p),h=new Uee(c);return n.runWebGLProgram(h,[r],i.dtype)}var Hee={kernelName:Lc,backendName:"webgl",kernelFunc:Gee};function qee(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;vp([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,p=N.computePool2DInfo(i.shape,o,l,1,u),d=new Vee(p);return n.runWebGLProgram(d,[r],i.dtype)}var jee={kernelName:Oc,backendName:"webgl",kernelFunc:qee};function Kee(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return Em({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var Xee={kernelName:Mi,backendName:"webgl",kernelFunc:Kee},Yee=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(N.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(N.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
      void main() {
        float x = getXAtOutCoords();
        float mean = getMeanAtOutCoords();
        float variance = getVarianceAtOutCoords();
        float offset = ${i};
        float scale = ${o};
        float inv = scale * inversesqrt(variance + float(${s}));
        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
      }
    `}},Zee=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(N.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(N.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
      void main() {
        vec4 offset = ${i};
        vec4 scale = ${o};
 
        vec4 x = getXAtOutCoords();
        vec4 mean = getMeanAtOutCoords();
        vec4 variance = getVarianceAtOutCoords();
 
        vec4 inv = scale * inversesqrt(variance + vec4(${s}));
 
        setOutput((x - mean) * inv + offset);
      }
    `}},Jee=({inputs:e,backend:t,attrs:n})=>{let{x:a,mean:r,variance:s,offset:i,scale:o}=e;w.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let u=[a,r,s],p=null;i!=null&&(p=i.shape,u.push(i));let d=null;o!=null&&(d=o.shape,u.push(o));let c=G().getBool("WEBGL_PACK_NORMALIZATION")?new Zee(a.shape,r.shape,s.shape,p,d,l):new Yee(a.shape,r.shape,s.shape,p,d,l);return t.runWebGLProgram(c,u,u[0].dtype)},Qee={kernelName:Qi,backendName:"webgl",kernelFunc:Jee},ete=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=dt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=tte(this.rank),a,r=e.map((s,i)=>`sourceLoc.${gv[i]} = start[${i}] + coords.${gv[i]};`);a=`
        ${t} sourceLoc;
        ${t} coords = getOutputCoords();
        ${r.join(`
`)}
      `,this.userCode=`
      void main() {
        ${a}
        setOutput(getSource(${n}));
      }
    `}},gv=["x","y","z","w","u","v"];function tte(e){if(e===1)return"sourceLoc";if(e<=6)return gv.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var nte=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=dt(this.rank),n=Sn("coords",this.rank),a=Sn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${a.slice(-2).join()})`,s=`getChannel(getSource(${a.join()}), ${r})`,i=`
      result.x = ${s};
      if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
        ++${a[this.rank-1]};
        result.y = ${s};
        --${a[this.rank-1]};
      }
    `,o=this.rank===1?"":`
      --${n[this.rank-1]};
      if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
        ++${a[this.rank-2]};
        result.z = ${s};
        if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
          ++${a[this.rank-1]};
          result.w = ${s};
        }
      }
    `,l=this.rank<=4?`sourceLoc = coords +
            ${t}(${e.map((u,p)=>`start[${p}]`).join()});`:e.map((u,p)=>`${a[p]} = ${n[p]} + start[${p}];`).join(`
`);this.userCode=`
      void main() {
        ${t} coords = getOutputCoords();
        ${t} sourceLoc;
        ${l}
        vec4 result = vec4(0.);
        ${i}
        ${o}
        setOutput(result);
      }
    `}};function ate(e,t,n,a){let r=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=Xt.computeFlatOffset(t,w.computeStrides(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=a.dataRefCount.get(i.slice.origDataId)||1;return a.dataRefCount.set(i.slice.origDataId,l+1),s}function Cp(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a,[o,l]=Xt.parseSliceParams(r,s,i);if(Xt.assertParamsValid(r,o,l),w.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.texData.get(r.dataId),c=j9(d.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,c)}let{isPacked:u}=n.texData.get(r.dataId),p=Xt.isSliceContinous(r.shape,o,l);if(u||!p){let d=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new nte(l):new ete(l),c=[o];return n.runWebGLProgram(d,[r],r.dtype,c)}return n.uploadToGPU(r.dataId),ate(r,o,l,n)}var rte={kernelName:Qu,backendName:"webgl",kernelFunc:Cp},ste=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;w.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,x)=>y*x),l=N.getReshaped(r.shape,s,o),u=N.getPermuted(l.length,s.length),p=N.getReshapedPermuted(r.shape,s,o),d=N.getSliceBeginCoords(i,s.length),c=N.getSliceSize(p,i,s.length),h=[],m=ce({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Nn({inputs:{x:m},backend:n,attrs:{perm:u}}),g=ce({inputs:{x:f},backend:n,attrs:{shape:p}}),b=Cp({inputs:{x:g},backend:n,attrs:{begin:d,size:c}});return h.push(m),h.push(f),h.push(g),h.forEach(y=>n.disposeIntermediateTensorInfo(y)),b},ite={kernelName:mu,backendName:"webgl",kernelFunc:ste};function ote(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.readSync(r.dataId),l=n.readSync(s.dataId),u=yA(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var lte={kernelName:fu,backendName:"webgl",kernelFunc:ote},ute=`
  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);
`,pte=`
  return float(int(a.r) & int(b.r));
`;function cte(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=G().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([a,r])||i===1){let l=n.texData.get(a.dataId).values,u=n.texData.get(r.dataId).values,[p,d]=b9(a.shape,r.shape,l,u,a.dtype),c=n.makeTensorInfo(d,a.dtype),h=n.texData.get(c.dataId);return h.values=p,c}let o;return s?o=new Np(ute,a.shape,r.shape,!1):o=new Ii(pte,a.shape,r.shape),n.runWebGLProgram(o,[a,r],a.dtype)}var dte={kernelName:gu,backendName:"webgl",kernelFunc:cte};function hte(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.readSync(a.dataId),i=n.readSync(r.dataId),o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var mte={kernelName:zc,backendName:"webgl",kernelFunc:hte},fte="return float(a != b);",DA=fn({opSnippet:fte,cpuKernelImpl:L9,dtype:"bool"}),gte={kernelName:Wu,backendName:"webgl",kernelFunc:DA};function Od(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return ra({inputs:{x:r.complexTensorInfos.real},backend:n})}var bte={kernelName:Km,backendName:"webgl",kernelFunc:Od},yte="return float(int(x));";function xte(e,t){let n=new ir(e.shape,yte),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function bv(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return ra({inputs:{x:r},backend:n});let i=Nt(r.shape),o=bv({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Ms({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=Od({inputs:{input:r},backend:n}),o=bv({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(r.dtype,s)){let i=ra({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(n.shouldExecuteOnCPU([r])){let i=n.texData.get(r.dataId).values,[o,l,u]=y9(i,r.shape,r.dtype,s);return n.makeTensorInfo(o,l,u)}if(s==="int32")return xte(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=DA({inputs:{a:r,b:i},backend:n});return n.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var vte={kernelName:Pi,backendName:"webgl",kernelFunc:bv},TS="return ceil(x);",wte=Ze({opSnippet:TS,packedOpSnippet:TS,cpuKernelImpl:x9}),kte={kernelName:Oi,backendName:"webgl",kernelFunc:wte},Ite=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
 
      void main() {
        float value = getAAtOutCoords();
        if (isnan(value)) {
          setOutput(value);
          return;
        }
 
        setOutput(clamp(value, minVal, maxVal));
      }
    `}},Ste=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
      void main() {
        vec4 value = getAAtOutCoords();
 
        if (any(isnan(value))) {
          setOutput(value);
          return;
        }
 
        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
      }
    `}};function Nte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;G().getBool("WEBGL_PACK_CLIP")?o=new Ste(r.shape):o=new Ite(r.shape);let l=[[s],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}var Tte={kernelName:Ss,backendName:"webgl",kernelFunc:Nte},Cte=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,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 CS(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function _te(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new Cte(a.shape),i=[CS(a,r.complexTensorInfos.real),CS(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var Ete={kernelName:Wc,backendName:"webgl",kernelFunc:_te},Ate=class{constructor(e){this.outputShape=[],this.outputShape=N.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];n.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let a=t.length,r=t[t.length-1];n.push(`else setOutput(getT${a}(yR, yC-${r}));`),this.userCode=`
      void main() {
        ivec2 coords = getOutputCoords();
        int yR = coords.x;
        int yC = coords.y;
 
        ${n.join(`
        `)}
      }
    `}},Fte=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=dt(a),s=Sn("coords",a),i=["x","y","z","w","u","v"].slice(0,a);this.variableNames=e.map((m,f)=>`T${f}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],u=i.slice(-2),p=i.join(),d=`if (${l} < ${o[0]}) {
        return getChannel(
            getT0(${p}), vec2(${u.join()}));
        }`;for(let m=1;m<o.length;m++){let f=o[m-1];d+=`
        if (${l} < ${o[m]}  && ${l} >= ${o[m-1]}) {
          return getChannel(
            getT${m}(${jh(i,l,f)}),
            vec2(${jh(u,l,f)}));
        }`}let c=o.length,h=o[o.length-1];d+=`
        return getChannel(
          getT${c}(${jh(i,l,h)}),
          vec2(${jh(u,l,h)}));`,this.userCode=`
      float getValue(${i.map(m=>"int "+m)}) {
        ${d}
      }
 
      void main() {
        ${r} coords = getOutputCoords();
        vec4 result = vec4(getValue(${s}), 0., 0., 0.);
 
        ${s[a-1]} = ${s[a-1]} + 1;
        if (${s[a-1]} < ${n[a-1]}) {
          result.g = getValue(${s});
        }
 
        ${s[a-2]} = ${s[a-2]} + 1;
        if (${s[a-2]} < ${n[a-2]}) {
          result.a = getValue(${s});
        }
 
        ${s[a-1]} = ${s[a-1]} - 1;
        if (${s[a-2]} < ${n[a-2]} &&
            ${s[a-1]} < ${n[a-1]}) {
          result.b = getValue(${s});
        }
        setOutput(result);
      }
    `}};function jh(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a?`${r} - ${n}`:r).join()}function ng(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return ra({inputs:{x:r.complexTensorInfos.imag},backend:n})}var $te={kernelName:Gm,backendName:"webgl",kernelFunc:ng};function cc(e,t,n){let a=e[0].dtype;if(a==="complex64"){let h=e.map(y=>Od({inputs:{input:y},backend:n})),m=e.map(y=>ng({inputs:{input:y},backend:n})),f=cc(h,t,n),g=cc(m,t,n),b=Ms({inputs:{real:f,imag:g},backend:n});return h.forEach(y=>n.disposeIntermediateTensorInfo(y)),m.forEach(y=>n.disposeIntermediateTensorInfo(y)),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),b}let r=n.shouldExecuteOnCPU(e);if(a==="string"&&(r=!0),r){let h=e.map(v=>{let I=[-1,w.sizeFromShape(v.shape.slice(t))];return ce({inputs:{x:v},backend:n,attrs:{shape:I}})}),m=h.map(v=>({vals:n.readSync(v.dataId),shape:v.shape})),f=N.computeOutShape(h.map(v=>v.shape),1),g=h[0].shape[0]===1,b=v9(m,f,a,g),y=N.computeOutShape(e.map(v=>v.shape),t),x=n.makeTensorInfo(y,a,b);return h.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}let s=e.filter(h=>w.sizeFromShape(h.shape)>0),i=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let h=i?new ir(e[0].shape,ns):new os(e[0].shape,ns);return n.runWebGLProgram(h,e,a)}let o=G().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>o){let h=[];for(let f=0;f<s.length;f+=o){let g=s.slice(f,f+o);h.push(cc(g,t,n))}let m=cc(h,t,n);for(let f of h)n.disposeIntermediateTensorInfo(f);return m}if(i){let h=new Fte(s.map(m=>m.shape),t);return n.runWebGLProgram(h,s,a)}let{tensors2D:l,outShape:u}=Dte(s,t,n),p=new Ate(l.map(h=>h.shape)),d=n.runWebGLProgram(p,l,a);l.forEach(h=>n.disposeIntermediateTensorInfo(h));let c=ce({inputs:{x:d},attrs:{shape:u},backend:n});return n.disposeIntermediateTensorInfo(d),c}function Dte(e,t,n){let a=N.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>ce({inputs:{x:r},attrs:{shape:[-1,w.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function RA(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=t.map(u=>u.shape);N.assertParamsConsistent(i,s);let o=N.computeOutShape(t.map(u=>u.shape),s);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(u=>w.sizeFromShape(u.shape)>0);return l.length===1?ra({inputs:{x:l[0]},backend:n}):cc(l,s,n)}var Rte={kernelName:bu,backendName:"webgl",kernelFunc:RA},MA=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,c=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,b=f?2:3,y=f?3:1,x="",v="";n&&(a?x=`float activation(float a) {
          float b = getPreluActivationWeightsAtOutCoords();
          ${n}
        }`:r?x=`float activation(float a) {
          float b = getLeakyreluAlphaAtOutCoords();
          ${n}
        }`:x=`
          float activation(float x) {
            ${n}
          }
        `,v="result = activation(result);");let I=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
      ${x}
 
      const ivec2 strides = ivec2(${o}, ${l});
      const ivec2 pads = ivec2(${s}, ${i});
 
      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d2 = coords[${y}];
 
        ivec2 xRCCorner =
            ivec2(coords[${g}], 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 < ${d}; wR++) {
          int xR = xRCorner + wR * ${u};
 
          if (xR < 0 || xR >= ${e.inHeight}) {
            continue;
          }
 
          for (int wC = 0; wC < ${c}; wC++) {
            int xC = xCCorner + wC * ${p};
 
            if (xC < 0 || xC >= ${e.inWidth}) {
              continue;
            }
 
            for (int d1 = 0; d1 < ${h}; 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 (${f}) {
                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 (${m===1}) {
 
              if (${f}) {
                dotProd +=
                    getX(batch, xR, xC, ${h}) *
                    getW(wR, wC, ${h}, d2);
              } else {
                dotProd +=
                    getX(batch, ${h}, xR, xC) *
                    getW(wR, wC, ${h}, d2);
              }
 
            } else if (${m===2}) {
              vec2 wValues = vec2(
                getW(wR, wC, ${h}, d2),
                getW(wR, wC, ${h} + 1, d2)
              );
 
              if (${f}) {
                vec2 xValues = vec2(
                  getX(batch, xR, xC, ${h}),
                  getX(batch, xR, xC, ${h} + 1)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec2 xValues = vec2(
                  getX(batch, ${h}, xR, xC),
                  getX(batch, ${h} + 1, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }
 
            } else if (${m===3}) {
              vec3 wValues = vec3(
                getW(wR, wC, ${h}, d2),
                getW(wR, wC, ${h} + 1, d2),
                getW(wR, wC, ${h} + 2, d2)
              );
 
              if (${f}) {
                vec3 xValues = vec3(
                  getX(batch, xR, xC, ${h}),
                  getX(batch, xR, xC, ${h} + 1),
                  getX(batch, xR, xC, ${h} + 2)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec3 xValues = vec3(
                  getX(batch, ${h}, xR, xC),
                  getX(batch, ${h} + 1, xR, xC),
                  getX(batch, ${h} + 2, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }
 
            }
          }
        }
 
        float result = dotProd;
        ${I}
        ${v}
        setOutput(result);
      }
    `}},Mte=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,a=e.padInfo.left,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.filterDepth,d=e.filterHeight,c=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
      const ivec3 strides = ivec3(${r}, ${s}, ${i});
      const ivec3 pads = ivec3(${t}, ${n}, ${a});
 
      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 * ${o};
 
          if (xF < 0 || xF >= ${e.inDepth}) {
            continue;
          }
 
          for (int wR = 0; wR < ${d}; wR++) {
            int xR = xRCorner + wR * ${l};
 
            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }
 
            for (int wC = 0; wC < ${c}; wC++) {
              int xC = xCCorner + wC * ${u};
 
              if (xC < 0 || xC >= ${e.inWidth}) {
                continue;
              }
 
              for (int d1 = 0; d1 < ${h}; 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 (${m===1}) {
                dotProd +=
                  getX(batch, xF, xR, xC, ${h}) *
                  getW(wF, wR, wC, ${h}, d2);
              } else if (${m===2}) {
                vec2 xValues = vec2(
                  getX(batch, xF, xR, xC, ${h}),
                  getX(batch, xF, xR, xC, ${h} + 1)
                );
                vec2 wValues = vec2(
                  getW(wF, wR, wC, ${h}, d2),
                  getW(wF, wR, wC, ${h} + 1, d2)
                );
                dotProd += dot(xValues, wValues);
              } else if (${m===3}) {
                vec3 xValues = vec3(
                  getX(batch, xF, xR, xC, ${h}),
                  getX(batch, xF, xR, xC, ${h} + 1),
                  getX(batch, xF, xR, xC, ${h} + 2)
                );
                vec3 wValues = vec3(
                  getW(wF, wR, wC, ${h}, d2),
                  getW(wF, wR, wC, ${h} + 1, d2),
                  getW(wF, wR, wC, ${h} + 2, d2)
                );
                dotProd += dot(xValues, wValues);
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `}},PA=class{constructor(e,t=!1,n=null,a=!1,r=!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=e.outShape,this.enableShapeUniforms=vn(this.outputShape.length);let s=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,p=u,d=`
       int xR; int xC; int xCOffset;
       vec4 wTexel; vec4 previous; vec4 final;`;for(let f=0;f<u;f++)d+=`
           vec4 xTexelC${f*2};
           int xTexelC${f*2}Ready;
           vec4 xTexelC${f*2+1};
           int xTexelC${f*2+1}Ready;
           vec4 xC${f};`;d+=`
     for (int r = 0; r < ${l}; r++) {
      for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
       `;for(let f=0;f<u;f++)d+=`
           xTexelC${f*2} = vec4(0.0);
           xTexelC${f*2}Ready = 0;
           xTexelC${f*2+1} = vec4(0.0);
           xTexelC${f*2+1}Ready = 0;
           xC${f} = vec4(0.0);`;d+=`
         xR = xRCorner + r * dilations[0];
         if (xR >=0 && xR < inDims[0]) {
       `;for(let f=0;f<(p+1)/2;f++){let g=f*2;if(d+=`
           xC = xCCorner + ${g*o};
           `,i===1){if(g<u&&(s%2===1?(d+=`
                 xCOffset = xC + 1;
                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) {
                   xTexelC${g} = 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${g}.zw = vec2(0.0);
                   }
                   xTexelC${g}Ready = 1;
                 }
               `,o===1&&g>0?d+=`
                 xC${g} = vec4(xTexelC${g-2}.zw, xTexelC${g}.xy);
                 `:d+=`
                   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${g} = vec4(previous.zw, xTexelC${g}.xy);
                   } else {
                     xC${g} = vec4(0.0, 0.0, xTexelC${g}.xy);
                   }
                   `):d+=`
                 if (xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) {
                   xTexelC${g} = getX(batch, xR, xC, d1);
                   if (xC + 1 >= inDims[1]) {
                     xTexelC${g}.zw = vec2(0.0);
                   }
                   xTexelC${g}Ready = 1;
                 }
 
                 xC${g} = xTexelC${g};
                 `,g+1<u)){let b=s%2===0?w.nearestLargerEven(o):o;o%2===0&&s%2===1||o%2!==0&&s%2!==1?(d+=`
                   xCOffset = xC + imod(pads[1], 2) + ${b};
 
                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
                     xTexelC${g+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${g+1}.zw = vec2(0.0);
                     }
                     xTexelC${g+1}Ready = 1;
                   }
                   `,o>1?d+=`
                     xCOffset -= 2;
                     if (xCOffset >= 0 && xCOffset < inDims[1]) {
                      previous = getX(batch, xR, xCOffset, d1);
                      xC${g+1} = vec4(previous.zw, xTexelC${g+1}.xy);
                     } else {
                      xC${g+1} = vec4(0.0, 0.0, xTexelC${g+1}.xy);
                     }
                     `:d+=`
                     xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.xy);
                     `):b===1?d+=`
                     xC${g+1} = xTexelC${g};
                     `:d+=`
                     xCOffset = xC + ${b};
 
                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
                       xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
                       if (xCOffset + 1 >= inDims[1]) {
                         xTexelC${g+1}.zw = vec2(0.0);
                       }
                       xTexelC${g+1}Ready = 1;
                     }
 
                     xC${g+1} = xTexelC${g+1};
                     `}}else g<u&&(s%2===1?(d+=`
                 xCOffset = xC + 1 - strides[1];
                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) {
                   xTexelC${g} = 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${g}.zw = vec2(0.0);
                   }
                   xTexelC${g}Ready = 1;
                 }
 
                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${g+1}Ready == 0) {
                   xTexelC${g+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${g+1}.zw = vec2(0.0);
                   }
                   xTexelC${g+1}Ready = 1;
                 }
 
                 xC${g} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
               `,g+1<u&&(d+=`
                   final = vec4(0.0);
                   xCOffset = xC + 1 + strides[1];
                   if(xCOffset >= 0 && xCOffset < inDims[1]) {
                     final = getX(batch, xR, xCOffset, d1);
                   }
                   xC${g+1} = vec4(xTexelC${g+1}.xy, final.xy);
                 `)):(d+=`
                 if(xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) {
                   xTexelC${g} = getX(batch, xR, xC, d1);
                   if (xC + 1 >= inDims[1]) {
                     xTexelC${g}.zw = vec2(0.0);
                   }
                   xTexelC${g}Ready = 1;
                 }
 
                 xCOffset = xC + strides[1];
                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
                   xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
                   if (xCOffset + 1 >= inDims[1]) {
                     xTexelC${g+1}.zw = vec2(0.);
                   }
                   xTexelC${g+1}Ready = 1;
                 }
 
                 xC${g} = vec4(
                   xTexelC${g}.xy, xTexelC${g+1}.xy);
               `,g+1<u&&(d+=`
                   xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
                 `)));g<u&&(d+=`
             wTexel = getW(r, ${g}, d1, d2);
             dotProd += xC${g}.xxzz * vec4(wTexel.xy, wTexel.xy);
             if(d1 + 1 < ${e.inChannels}) {
               dotProd += xC${g}.yyww * vec4(wTexel.zw, wTexel.zw);
             }
           `,g+1<u&&(d+=`
               wTexel = getW(r, ${g+1}, d1, d2);
               dotProd += xC${g+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
               if(d1 + 1 < ${e.inChannels}) {
                 dotProd += xC${g+1}.yyww * vec4(wTexel.zw, wTexel.zw);
               }
             `))}d+=`
     }
   `,d+=`
     }
   `,d+=`
     }
   `;let c="",h="";n&&(a?c=`vec4 activation(vec4 a) {
           vec4 b = getPreluActivationWeightsAtOutCoords();
           ${n}
         }`:r?c=`vec4 activation(vec4 a) {
           vec4 b = getLeakyreluAlphaAtOutCoords();
           ${n}
         }`:c=`vec4 activation(vec4 x) {
           ${n}
         }`,h="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
       ${c}
 
       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);
 
         ${d}
 
         vec4 result = dotProd - vec4(0.000000000000001);
         ${m}
         ${h}
         setOutput(result);
       }
     `}},Pte=class{constructor(e,t){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=e,this.enableShapeUniforms=vn(this.outputShape.length);let{dataFormat:n}=t,a=En(),r=n==="channelsLast",s=r?1:2,i=r?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`,l="";for(let u=0;u<=1;u++)for(let p=0;p<=1;p++)l+=`
          blockIndex = rc.z + ${p};
          pos = rc.y + ${u};
 
          ${o}
            offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
            d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
 
            if(d0 < inputShape[${s}] && 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[${i}] && d1 >= 0) {
 
                ch = imod(pos, inChannels);
 
                if (${r}) {
                  innerDims = vec2(d1, ch);
                  result[${u*2+p}] = getChannel(
                    getA(rc.x, d0, int(innerDims.x),
                    int(innerDims.y)), innerDims);
                } else {
                  innerDims = vec2(d0, d1);
                  result[${u*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}
 
        ${a.output} = result;
      }
    `}};function Am(e,t){let n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&n===1&&e[0]>1?[e[0],1]:null}function OA({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=a.texData.get(e.dataId),p=n.inChannels,d=l[0]*l[1]*l[2],c=n.outChannels,h=n.dataFormat==="channelsLast",m=!1,f=!1,g,b=[];if(s!=null){let y=Am(s.shape,h);y!=null&&(s=ce({inputs:{x:s},backend:a,attrs:{shape:y}}),b.push(s))}if(r!=null){let y=Am(r.shape,h);y!=null&&(r=ce({inputs:{x:r},backend:a,attrs:{shape:y}}),b.push(r))}if(!((d===1||c===1)&&p>EA)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&w.arraysEqual(u.shape.slice(-3),l.slice(-3))){let y=l[0]*l[1]*(l[2]+1),x={dataId:e.dataId,shape:[1,y,n.inChannels],dtype:e.dtype},v=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(Ac(u.shape,x.shape),()=>`packed reshape ${u.shape} to ${x.shape} isn't free`);let I=ce({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(I);let T=Em({a:x,b:I,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),C=a.texData.get(T.dataId);w.assert(C.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=v,C.shape=n.outShape,g=ra({inputs:{x:T},backend:a}),g.shape=n.outShape,b.push(T)}else{let y=n.outHeight*n.outWidth,x=ce({inputs:{x:e},backend:a,attrs:{shape:h?[n.batchSize,y,n.inChannels]:[n.batchSize,n.inChannels,y]}}),v=ce({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),I=Em({a:h?x:v,b:h?v:x,transposeA:!h,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ce({inputs:{x:I},backend:a,attrs:{shape:n.outShape}}),b.push(x),b.push(v),b.push(I)}for(let y of b)a.disposeIntermediateTensorInfo(y);return g}function LA({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:p,outWidth:d,outHeight:c,dataFormat:h}=n,m=h==="channelsLast",f=l*u*p,g=c*d,b=[n.batchSize,f,g],y=!0,x=!1,v=[];if(s!=null){let K=Am(s.shape,m);K!=null&&(s=ce({inputs:{x:s},backend:a,attrs:{shape:K}}),v.push(s))}if(r!=null){let K=Am(r.shape,m);K!=null&&(r=ce({inputs:{x:r},backend:a,attrs:{shape:K}}),v.push(r))}let I=ce({inputs:{x:t},backend:a,attrs:{shape:[1,f,w.sizeFromShape(t.shape)/f]}});v.push(I);let T=new Pte(b,n),C=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],E=a.runWebGLProgram(T,[e],"float32",C),F=ce({inputs:{x:E},backend:a,attrs:{shape:b}});v.push(E),v.push(F);let D=r!=null,$=s!=null,S=o==="leakyrelu",M=o?Fc(o,!0):null,B=new _A(m?F.shape:I.shape,m?I.shape:F.shape,m?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],y,x,D,M,$,S),U=m?[F,I]:[I,F];if(r&&U.push(r),$&&U.push(s),S){let K=a.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));U.push(K),v.push(K)}let H=a.runWebGLProgram(B,U,"float32"),j=ce({inputs:{x:H},backend:a,attrs:{shape:n.outShape}});v.push(H);for(let K of v)a.disposeIntermediateTensorInfo(K);return j}function Ote(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=a,d=N.convertConv2DDataFormat(l),c=N.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,d),h;if(c.filterHeight===1&&c.filterWidth===1&&c.dilationHeight===1&&c.dilationWidth===1&&c.strideHeight===1&&c.strideWidth===1&&(c.padInfo.type==="SAME"||c.padInfo.type==="VALID"))h=OA({x:r,filter:s,convInfo:c,backend:n});else if(c.strideWidth<=2&&d==="channelsLast"&&G().getBool("WEBGL_EXP_CONV")){let f=new PA(c),g=[[c.padInfo.top,c.padInfo.left],[c.strideHeight,c.strideWidth],[c.dilationHeight,c.dilationWidth],[c.inHeight,c.inWidth]];h=n.runWebGLProgram(f,[r,s],"float32",g)}else if(G().getBool("WEBGL_CONV_IM2COL"))h=LA({x:r,filter:s,convInfo:c,backend:n});else{let f=new MA(c);h=n.runWebGLProgram(f,[r,s],"float32")}let m=ce({inputs:{x:h},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(h),m}var Lte={kernelName:Li,backendName:"webgl",kernelFunc:Ote},zte=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.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 < ${e.batchSize}; b++) {
          for (int yR = 0; yR < ${e.outHeight}; yR++) {
            int xR = wR + yR * ${t} - ${a};
 
            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }
 
            for (int yC = 0; yC < ${e.outWidth}; yC++) {
              int xC = wC + yC * ${n} - ${r};
 
              if (xC < 0 || xC >= ${e.inWidth}) {
                continue;
              }
 
              ${s?`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);
      }
    `}},Wte=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=s?1:2,u=s?2:3,p=s?3:1;this.userCode=`
      const ivec2 pads = ivec2(${i}, ${o});
 
      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d1 = coords[${p}];
 
        ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - 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 < ${t}; wR++) {
          float dyR = float(dyRCorner + wR) / ${a}.0;
 
          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
 
          int wRPerm = ${t} - 1 - wR;
 
          for (int wC = 0; wC < ${n}; wC++) {
            float dyC = float(dyCCorner + wC) / ${r}.0;
 
            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
                fract(dyC) > 0.0) {
              continue;
            }
            int idyC = int(dyC);
 
            int wCPerm = ${n} - 1 - wC;
 
            for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
 
              if (${s}) {
                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);
      }
    `}},Bte=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.padInfo.front,s=e.padInfo.top,i=e.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 < ${e.batchSize}; b++) {
          for (int yF = 0; yF < ${e.outDepth}; yF++) {
            int xF = wF + yF * ${t} - ${r};
 
            if (xF < 0 || xF >= ${e.inDepth}) {
              continue;
            }
 
            for (int yR = 0; yR < ${e.outHeight}; yR++) {
              int xR = wR + yR * ${n} - ${s};
 
              if (xR < 0 || xR >= ${e.inHeight}) {
                continue;
              }
 
              for (int yC = 0; yC < ${e.outWidth}; yC++) {
                int xC = wC + yC * ${a} - ${i};
 
                if (xC < 0 || xC >= ${e.inWidth}) {
                  continue;
                }
 
                float dyValue = getDy(b, yF, yR, yC, d2);
                float xValue = getX(b, xF, xR, xC, d1);
                dotProd += (xValue * dyValue);
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `}},Vte=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=a-1-e.padInfo.left;this.userCode=`
      const ivec3 pads = ivec3(${o}, ${l}, ${u});
 
      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 < ${t}; wF++) {
          float dyF = float(dyFCorner + wF) / ${r}.0;
 
          if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
            continue;
          }
          int idyF = int(dyF);
 
          int wFPerm = ${t} - 1 - wF;
 
          for (int wR = 0; wR < ${n}; wR++) {
            float dyR = float(dyRCorner + wR) / ${s}.0;
 
            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
              fract(dyR) > 0.0) {
              continue;
            }
            int idyR = int(dyR);
 
            int wRPerm = ${n} - 1 - wR;
 
            for (int wC = 0; wC < ${a}; wC++) {
              float dyC = float(dyCCorner + wC) / ${i}.0;
 
              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
                  fract(dyC) > 0.0) {
                continue;
              }
              int idyC = int(dyC);
 
              int wCPerm = ${a} - 1 - wC;
 
              for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
                float xValue = getDy(batch, idyF, idyR, idyC, d2);
                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
                dotProd += xValue * wValue;
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `}};function Ute(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=a,d=N.convertConv2DDataFormat(l),c=N.computeConv2DInfo(r.shape,p,i,1,o,u,!1,d),h=new zte(c);return n.runWebGLProgram(h,[r,s],"float32")}var Gte={kernelName:Lm,backendName:"webgl",kernelFunc:Ute},Hte=class{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=vn(this.outputShape.length);let t=e.filterHeight,n=e.filterWidth,a=t-1-e.padInfo.top,r=n-1-e.padInfo.left;this.userCode=`
      const ivec2 pads = ivec2(${a}, ${r});
 
      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 < ${t}; wR++) {
          float dyR = float(dyRCorner + wR) / strides[0];
          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
          int wRPerm = ${t} - 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 < ${e.outWidth}.0)
              && (fract(dyC) == 0.0);
            int idyC = int(dyC);
 
            float dyC2 = float(dyCCorner + wC + 1) / strides[1];
            bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
              && (fract(dyC2) == 0.0);
            int idyC2 = int(dyC2);
 
            if (idyCVal && idyCVal2) {
              for (int d2 = 0; d2 < ${e.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 < ${e.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 < ${e.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 qte(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=a,d=N.convertConv2DDataFormat(u),c=N.computeConv2DInfo(i,s.shape,o,1,l,p,!1,d);if(G().getBool("WEBGL_PACK")&&d==="channelsLast"){let h=[[c.strideHeight,c.strideWidth]],m=new Hte(c);return n.runWebGLProgram(m,[r,s],"float32",h)}else{let h=new Wte(c);return n.runWebGLProgram(h,[r,s],"float32")}}var jte={kernelName:zi,backendName:"webgl",kernelFunc:qte};function Kte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=N.computeConv3DInfo(r.shape,s.shape,i,l,o),p=new Mte(u);return n.runWebGLProgram(p,[r,s],"float32")}var Xte={kernelName:Wi,backendName:"webgl",kernelFunc:Kte};function Yte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,u=N.computeConv3DInfo(r.shape,l,i,1,o),p=new Bte(u);return n.runWebGLProgram(p,[r,s],"float32")}var Zte={kernelName:yu,backendName:"webgl",kernelFunc:Yte};function Jte(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,u=N.computeConv3DInfo(l,s.shape,o,1,i),p=new Vte(u);return n.runWebGLProgram(p,[r,s],"float32")}var Qte={kernelName:xu,backendName:"webgl",kernelFunc:Jte},ene=Tp+`
  return cos(x);
`,tne=`
  vec4 result = cos(x);
  bvec4 isNaN = isnan(x);
  ${el}
  return result;
`,nne=Ze({opSnippet:ene,packedOpSnippet:tne}),ane={kernelName:Bi,backendName:"webgl",kernelFunc:nne},rne=`
  float e2x = exp(-x);
  return (e2x + 1.0 / e2x) / 2.0;
`,sne=Ze({opSnippet:rne}),ine={kernelName:Vi,backendName:"webgl",kernelFunc:sne},one=class{constructor(e,t,n,a,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[p,d]=n;this.outputShape=[u,p,d,l];let c=a==="bilinear"?1:0,[h,m]=[`${i-1}.0`,`${o-1}.0`],[f,g,b]=p>1?[`${(i-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[y,x,v]=d>1?[`${(o-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
      const float height_ratio = float(${f});
      const float width_ratio = float(${y});
      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 >= ${s}) {
          return;
        }
 
        float height_scale = ${g};
        float width_scale = ${x};
 
        float in_y = ${b};
        if( in_y < 0.0 || in_y > ${h} ) {
          setOutput(float(${r}));
          return;
        }
        float in_x = ${v};
        if( in_x < 0.0 || in_x > ${m} ) {
          setOutput(float(${r}));
          return;
        }
 
        vec2 sourceFracIndexCR = vec2(in_x,in_y);
        if(${c} == 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);
        }
      }
    `}},lne=e=>{let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,p=new one(r.shape,s.shape,o,l,u);return n.runWebGLProgram(p,[r,s,i],"float32")},une={kernelName:wu,backendName:"webgl",kernelFunc:lne},Dc;(function(e){e.Prod="*",e.Sum="+"})(Dc||(Dc={}));var _S=class{constructor(e,t,n,a){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let r=this.outputShape.length,s=this.op===Dc.Prod?"1.0":"0.0",i=n?s:`getX(${ES(r,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1],l="",u="";n?(l=a?`end != ${o-1}`:"end != 0",u=a?"end + 1":"end - 1"):(l=a?`end + pow2 < ${o}`:"end >= pow2",u=a?"end + pow2":"end - pow2"),this.userCode=`
      void main() {
        ${dt(r)} coords = getOutputCoords();
        int end = ${AS(r,"coords",this.op)};
        float val = ${i};
        int pow2 = int(pow(2.0, index));
        if (${l}) {
          int idx = ${u};
          ${AS(r,"coords",this.op)} = idx;
          val ${this.op}= getX(${ES(r,"coords",this.op)});
        }
        setOutput(val);
      }
    `}};function ES(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function AS(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function zA(e,t,n,a,r,s){let i=t.shape.length,o=N.getAxesPermutation([a],i),l=t;o!=null&&(l=Nn({inputs:{x:t},backend:n,attrs:{perm:o}}));let u=N.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${a}`);let p=l.shape[u],d=ra({inputs:{x:l},backend:n});for(let c=0;c<=Math.ceil(Math.log2(p))-1;c++){let h=new _S(e,l.shape,!1,s),m=[[c]],f=d;d=n.runWebGLProgram(h,[d],d.dtype,m),n.disposeIntermediateTensorInfo(f)}if(r){let c=new _S(e,l.shape,r,s),h=d;d=n.runWebGLProgram(c,[d],d.dtype),n.disposeIntermediateTensorInfo(h)}if(o!=null){let c=N.getUndoAxesPermutation(o),h=Nn({inputs:{x:d},backend:n,attrs:{perm:c}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(l),h}return d}function pne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;return zA(Dc.Prod,r,n,s,i,o)}var cne={kernelName:vu,backendName:"webgl",kernelFunc:pne};function dne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;return zA(Dc.Sum,r,n,s,i,o)}var hne={kernelName:Ui,backendName:"webgl",kernelFunc:dne};function mne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.readSync(r.dataId),u=n.readSync(s.dataId),p=yA(l,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(s),p=g9(l,u,i,o);return n.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var fne={kernelName:Bc,backendName:"webgl",kernelFunc:mne},gne=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,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 / ${t};
      int offset_h = imod(h, ${t});
      int in_w = w / ${t};
      int offset_w = imod(w, ${t});
      int offset_d = (offset_h * ${t} + 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 bne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],d=l*s,c=u*s,h=p/(s*s),m=i==="NHWC"?[o,d,c,h]:[o,h,d,c],f=new gne(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var yne={kernelName:ku,backendName:"webgl",kernelFunc:bne},WA=class{constructor(e,t=!1,n=null,a=!1,r=!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=e.outShape,this.enableShapeUniforms=vn(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",u="";n&&(a?l=`float activation(float a) {
          float b = getPreluActivationWeightsAtOutCoords();
          ${n}
        }`:r?l=`float activation(float a) {
          float b = getLeakyreluAlphaAtOutCoords();
          ${n}
        }`:l=`
          float activation(float x) {
            ${n}
          }
        `,u="result = activation(result);");let p=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&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 / ${o};
        int q = d2 - d1 * ${o};
 
        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 < ${s}; wR++) {
          int xR = xRCorner + wR * dilations[0];
 
          if (xR < 0 || xR >= inDims[0]) {
            continue;
          }
 
          for (int wC = 0; wC < ${i}; 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}
        ${u}
        setOutput(result);
      }
    `}},BA=class{constructor(e,t=!1,n=null,a=!1,r=!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=e.outShape,this.enableShapeUniforms=vn(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,p=e.filterWidth,d=p,c=`
      int xR; int xC; int xCOffset;
      vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<p;g++)c+=`
          vec4 xTexelC${g*2};
          int xTexelC${g*2}Ready;
          vec4 xTexelC${g*2+1};
          int xTexelC${g*2+1}Ready;
          vec4 xC${g};`;c+=`
    for (int r = 0; r < ${u}; r++) {
      `;for(let g=0;g<p;g++)c+=`
          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);`;c+=`
        xR = xRCorner + r * dilations[0];
        if (xR >=0 && xR < inDims[0]) {
      `;for(let g=0;g<(d+1)/2;g++){let b=g*2;if(c+=`
          xC = xCCorner + ${b*l};
          `,o===1){if(b<p&&(i%2===1?(c+=`
                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?c+=`
                xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
                `:c+=`
                  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);
                  }
                  `):c+=`
                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 y=i%2===0?w.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(c+=`
                  xCOffset = xC + imod(pads[1], 2) + ${y};
 
                  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?c+=`
                    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);
                    }
                    `:c+=`
                    xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
                    `):y===1?c+=`
                    xC${b+1} = xTexelC${b};
                    `:c+=`
                    xCOffset = xC + ${y};
 
                    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&&(i%2===1?(c+=`
                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&&(c+=`
                  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);
                `)):(c+=`
                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&&(c+=`
                  xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
                `)));b<p&&(c+=`
            wTexel = getW(r, ${b}, d1, q);
            dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
          `,b+1<p&&(c+=`
              wTexel = getW(r, ${b+1}, d1, q);
              dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
            `))}c+=`
    }
  `,c+=`
      }
    `;let h="",m="";n&&(a?h=`vec4 activation(vec4 a) {
          vec4 b = getPreluActivationWeightsAtOutCoords();
          ${n}
        }`:r?h=`vec4 activation(vec4 a) {
          vec4 b = getLeakyreluAlphaAtOutCoords();
          ${n}
        }`:h=`vec4 activation(vec4 x) {
          ${n}
        }`,m="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
      ${h}
 
      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords.x;
        ivec2 xRCCorner = coords.yz * strides - pads;
        int d2 = coords.w;
        int d1 = d2 / ${s};
        int q = d2 - d1 * ${s};
        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);
 
        ${c}
 
        vec4 result = dotProd - vec4(0.000000000000001);
        ${f}
        ${m}
        setOutput(result);
      }
    `}};function xne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=a,p=l;p==null&&(p=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let d=N.computeConv2DInfo(r.shape,s.shape,i,p,o,u,!0),c;G().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?c=new BA(d):c=new WA(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(c,[r,s],"float32",h)}var vne={kernelName:Gi,backendName:"webgl",kernelFunc:xne},wne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.outChannels/e.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 * ${s} + dm;
 
        float dotProd = 0.0;
 
        // TO DO: Vec4 over the batch size
        for (int b = 0; b < ${e.batchSize}; b++) {
          for (int yR = 0; yR < ${e.outHeight}; yR++) {
            int xR = wR + yR * ${t} - ${a};
 
            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }
 
            for (int yC = 0; yC < ${e.outWidth}; yC++) {
              int xC = wC + yC * ${n} - ${r};
 
              if (xC < 0 || xC >= ${e.inWidth}) {
                continue;
              }
 
              float dyValue = getDy(b, yR, yC, d2);
              float xValue = getX(b, xR, xC, d1);
              dotProd += (xValue * dyValue);
            }
          }
        }
        setOutput(dotProd);
      }
    `}},kne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
      const ivec2 pads = ivec2(${s}, ${i});
 
      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 < ${t}; wR++) {
          float dyR = float(dyRCorner + wR) / ${a}.0;
 
          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
 
          int wRPerm = ${t} - 1 - wR;
 
          for (int wC = 0; wC < ${n}; wC++) {
            float dyC = float(dyCCorner + wC) / ${r}.0;
 
            if (dyC < 0.0 || dyC >= ${e.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 < ${o}; dm++) {
              int d2 = d1 * ${o} + dm;
              float xValue = getDy(batch, idyR, idyC, d2);
              float wValue = getW(wRPerm, wCPerm, d1, dm);
              dotProd += xValue * wValue;
            }
          }
        }
        setOutput(dotProd);
      }
    `}};function Ine(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=a,d=N.computeConv2DInfo(r.shape,p,i,o,l,u,!0),c=new wne(d);return n.runWebGLProgram(c,[r,s],"float32")}var Sne={kernelName:zm,backendName:"webgl",kernelFunc:Ine};function Nne(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=a,d=N.computeConv2DInfo(p,s.shape,i,o,l,u,!0),c=new kne(d);return n.runWebGLProgram(c,[r,s],"float32")}var Tne={kernelName:Wm,backendName:"webgl",kernelFunc:Nne},Cne=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
      void main() {
          ivec2 coords = getOutputCoords();
          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
          setOutput(val);
      }
    `}};function _ne(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=w.sizeFromShape(a.shape),i=ce({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new Cne(s),l=n.runWebGLProgram(o,[i],i.dtype),u=ce({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var Ene={kernelName:Vc,backendName:"webgl",kernelFunc:_ne},Ane=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:a,strideHeight:r,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:p,left:d}=a;this.userCode=`
      const ivec2 strides = ivec2(${r}, ${s});
      const ivec2 pads = ivec2(${p}, ${d});
      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 < ${i}; h++) {
          int hIn = hBeg + h * ${l};
 
          if (hIn >= 0 && hIn < ${t}) {
            for (int w = 0; w < ${o}; w++) {
              int wIn = wBeg + w * ${u};
 
              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 Fne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=N.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),p,d=new Ane(u);p=n.runWebGLProgram(d,[r,s],"float32");let c=ce({inputs:{x:p},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(p),c}var $ne={kernelName:Hi,backendName:"webgl",kernelFunc:Fne};function Dne(e){let{inputs:t,backend:n,attrs:a}=e,{equation:r}=a,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(r,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=N.getEinsumComputePath(o,l),d=p.length,c=null,h=i.length,m=[];for(let f=0;f<d;++f){for(let g of p[f]){let{permutationIndices:b,expandDims:y}=N.getEinsumPermutation(h,l[g]),x;N.isIdentityPermutation(b)?x=s[g]:(x=Nn({inputs:{x:s[g]},backend:n,attrs:{perm:b}}),m.push(x));let v=x.shape.slice();for(let I=0;I<y.length;++I)v.splice(y[I],0,1);w.arraysEqual(x.shape,v)||(x=ce({inputs:{x},backend:n,attrs:{shape:v}}),m.push(x)),c===null?c=x:(c=pk({inputs:{a:x,b:c},backend:n}),m.push(c))}f<d-1&&(u[f]>=0&&(c=tg({inputs:{x:c},backend:n,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(c)),h--)}for(let f of m)f!==c&&n.disposeIntermediateTensorInfo(f);return c}var Rne={kernelName:Bm,backendName:"webgl",kernelFunc:Dne},Mne="return (x >= 0.0) ? x : (exp(x) - 1.0);",Pne=`
  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;
`,One=Ze({opSnippet:Mne,packedOpSnippet:Pne}),Lne={kernelName:ji,backendName:"webgl",kernelFunc:One},zne="return (b >= 0.0) ? a : a * (b + 1.0);",Wne=`
  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,Bne=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Np(Wne,a.shape,r.shape):new Ii(zne,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},Vne={kernelName:Iu,backendName:"webgl",kernelFunc:Bne},Une=`
  return vec4(equal(a, b));
`,Gne="return float(a == b);",Hne=fn({opSnippet:Gne,packedOpSnippet:Une,dtype:"bool",cpuKernelImpl:w9}),qne={kernelName:Su,backendName:"webgl",kernelFunc:Hne},jne=`
  // Error function is calculated approximately with elementary function.
  // See "Handbook of Mathematical Functions with Formulas,
  // Graphs, and Mathematical Tables", Abramowitz and Stegun.
  float p = ${N.ERF_P};
  float a1 = ${N.ERF_A1};
  float a2 = ${N.ERF_A2};
  float a3 = ${N.ERF_A3};
  float a4 = ${N.ERF_A4};
  float a5 = ${N.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));
`,Kne=Ze({opSnippet:jne}),Xne={kernelName:Ki,backendName:"webgl",kernelFunc:Kne},Yne=Tp+`
  return exp(x);
`,Zne=`
  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;
`,VA=Ze({opSnippet:Yne,packedOpSnippet:Zne,cpuKernelImpl:k9,dtype:"float32"}),Jne={kernelName:Xi,backendName:"webgl",kernelFunc:VA};function yv(e){let{inputs:t,attrs:n,backend:a}=e,{dim:r}=n,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(w.assert(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+r+1),o.splice(l,0,1),ce({inputs:{x:s},backend:a,attrs:{shape:o}})}var Qne={kernelName:Nu,backendName:"webgl",kernelFunc:yv},FS="return exp(x) - 1.0;",eae=Ze({opSnippet:FS,packedOpSnippet:FS,cpuKernelImpl:I9}),tae={kernelName:Yi,backendName:"webgl",kernelFunc:eae},$S=class{constructor(e,t,n){this.variableNames=["real","imag"];let a=t[1];this.outputShape=t;let r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=n?`${a}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
      const float exponentMultiplier = ${r};
 
      float unaryOpComplex(float real, float expR, float imag, float expI) {
        ${i}
      }
 
      float mulMatDFT(int batch, int index) {
        float indexRatio = float(index) / float(${a});
        float exponentMultiplierTimesIndexRatio =
            exponentMultiplier * indexRatio;
 
        float result = 0.0;
 
        for (int i = 0; i < ${a}; 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) / ${s};
        }
 
        return result;
      }
 
      void main() {
        ivec2 coords = getOutputCoords();
        setOutput(mulMatDFT(coords[0], coords[1]));
      }
    `}};function UA(e,t,n){let a=n.texData.get(e.dataId),r=w.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=ce({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}),l=o.shape,u=new $S("real",l,t),p=new $S("imag",l,t),d=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:l},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:l}],c=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(p,d,"float32"),m=Ms({inputs:{real:c,imag:h},backend:n});n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h);let f=ce({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function nae(e){let{inputs:t,backend:n}=e,{input:a}=t;return UA(a,!1,n)}var aae={kernelName:Vm,backendName:"webgl",kernelFunc:nae},rae=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
      void main() {
        // Input can be obtained from uniform value.
        setOutput(value);
      }
    `}};function Ld(e){let{backend:t,attrs:n}=e,{shape:a,value:r}=n,{dtype:s}=n;if(s=s||w.inferDtype(r),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(a));return i.fill(r),t.makeTensorInfo(a,s,i)}else{let i=new rae(a,r),o=[[r]];return t.runWebGLProgram(i,[],s,o)}}var sae={kernelName:Uc,backendName:"webgl",kernelFunc:Ld},iae=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
        void main() {
          ivec4 coords = getOutputCoords();
          int x = coords[2];
 
          int coordX = ${t} - x - 1;
          float outputValue;
          if(coordX >= 0 && coordX < ${t}) {
            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
          } else {
            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
          }
          setOutput(outputValue);
        }
    `}},oae={kernelName:Tu,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new iae(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},DS="return floor(x);",lae=Ze({opSnippet:DS,packedOpSnippet:DS,cpuKernelImpl:S9}),uae={kernelName:Zi,backendName:"webgl",kernelFunc:lae},pae=`
  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;
  }
`,cae=`
  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);
`,dae=fn({opSnippet:pae,packedOpSnippet:cae,dtype:"int32"}),hae={kernelName:Ji,backendName:"webgl",kernelFunc:dae},mae=class{constructor(e){this.variableNames=["A"];let t=En(),[n,a]=e;this.outputShape=e,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(${a}.0, ${n}.0);
 
        vec4 values = ${t.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));
      }
    `}},fae=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=En(),[n,a]=e;this.outputShape=e,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(${a}.0, ${n}.0);
            vec4 values = ${t.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);
          }
        }
 
        ${t.output} = result;
      }
    `}},gae={kernelName:im,backendName:"webgl",kernelFunc:bae},Rl,Nx=G().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function bae(e){let{inputs:t,backend:n,attrs:a}=e,{pixels:r}=t,{numChannels:s}=a,i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[u,l],d=[u,l,s];if(o||i){let f=G().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Rl==null||f!==Nx)&&(Nx=f,Rl=document.createElement("canvas").getContext("2d",{willReadFrequently:Nx})),Rl.canvas.width=l,Rl.canvas.height=u,Rl.drawImage(r,0,0,l,u),r=Rl.canvas}let c=n.makeTensorInfo(p,"int32");n.texData.get(c.dataId).usage=ha.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(c.dataId),r);let h=G().getBool("WEBGL_PACK")?new fae(d):new mae(d),m=n.runWebGLProgram(h,[c],"int32");return n.disposeData(c.dataId),m}function yae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=N.convertConv2DDataFormat(p),g=N.computeConv2DInfo(r.shape,s.shape,l,d,u,c,!1,f),b,y=[],x=i!=null,v=o!=null,I=h==="leakyrelu",T=()=>{let E=[r,s],F=(D,$)=>{if($==="NCHW"&&D.shape.length===1&&D.shape[0]!==1){let S=ce({inputs:{x:D},backend:n,attrs:{shape:[D.shape[0],1,1]}});return y.push(S),S}return D};if(x&&E.push(F(i,p)),v&&E.push(F(o,p)),I){let D=n.makeTensorInfo([],"float32",w.createScalarValue(m,"float32"));E.push(D),y.push(D)}return E};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"))b=OA({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(g.strideWidth<=2&&f==="channelsLast"&&G().getBool("WEBGL_EXP_CONV")){let E=h?Fc(h,!0):null,F=new PA(g,x,E,v,I),D=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],$=T();b=n.runWebGLProgram(F,$,"float32",D)}else if(G().getBool("WEBGL_CONV_IM2COL"))b=LA({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let E=h?Fc(h,!1):null,F=new MA(g,x,E,v,I),D=T();b=n.runWebGLProgram(F,D,"float32")}let C=ce({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(E=>n.disposeIntermediateTensorInfo(E)),C}var xae={kernelName:li,backendName:"webgl",kernelFunc:yae};function vae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dimRoundingMode:d,activation:c,leakyreluAlpha:h}=a,m=[],f=p;f==null&&(f=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=N.computeConv2DInfo(r.shape,s.shape,l,f,u,d,!0),b=G().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,y=c?Fc(c,b):null,x=[r,s],v=i!=null,I=o!=null,T=c==="leakyrelu";if(v&&x.push(i),I&&x.push(o),T){let D=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));x.push(D),m.push(D)}let C;b?C=new BA(g,v,y,I,T):C=new WA(g,v,y,I,T);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],F=n.runWebGLProgram(C,x,"float32",E);return m.forEach(D=>n.disposeIntermediateTensorInfo(D)),F}var wae={kernelName:ui,backendName:"webgl",kernelFunc:vae},kae=class{constructor(e,t,n,a){this.sliceDim=e,this.strides=t,this.paramsShape=a,this.variableNames=["x","indices"],this.outputShape=n;let r=dt(n.length),s=`
    int index;`;for(let i=0;i<this.sliceDim;i++)s+=`
          index = round(getIndices(coords[0], ${i}));
          out_of_bounds = out_of_bounds || index < 0;
          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};
          flattenIndex += index * ${this.strides[i]};`;this.userCode=`
         void main() {
          ${r} coords = getOutputCoords();
          int flattenIndex = 0;
          bool out_of_bounds = false;
 
          ${s}
 
          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
        }
      `}};function Iae(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],o=w.sizeFromShape(a.shape),[l,u,p,d]=N.prepareAndValidate(a,r),c=ce({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),h=ce({inputs:{x:a},backend:n,attrs:{shape:[w.sizeFromShape(a.shape)/p,p]}});if(n.shouldExecuteOnCPU([a,r])||a.dtype==="string"){let b=n.readSync(r.dataId),y=n.bufferSync(a),x=N9(b,y,a.dtype,u,i,p,d,a.shape,o);return n.makeTensorInfo(l,a.dtype,x.values)}let m=new kae(i,d,[u,p],a.shape),f=n.runWebGLProgram(m,[h,c],h.dtype),g=ce({inputs:{x:f},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),g}var Sae={kernelName:_u,backendName:"webgl",kernelFunc:Iae},Nae=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=dt(this.rank),a=Tae(e,2);this.userCode=`
      void main() {
        ${n} resRC = getOutputCoords();
        int index = int(getIndices(resRC.x, resRC.z));
        float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
        setOutput(inBounds * getA(${a}));
      }
    `}};function Tae(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let r=0;r<e.length;r++)r===2?a.push("index"):a.push(`${n[r]}`);return a.join()}function GA(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0];if(G().get("DEBUG")){let y=n.readSync(s.dataId),x=r.shape[l];for(let v=0;v<y.length;++v){let I=y[v];w.assert(I<=x-1&&I>=0,()=>`GatherV2: the index value ${I} is not in [0, ${x-1}]`)}}let u=N.segment_util.collectGatherOpShapeInfo(r,s,l,o),p=w.sizeFromShape(s.shape),d=[],c=ce({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=ce({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,p/u.batchSize]}});d.push(c),d.push(h);let m=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let y=n.bufferSync(h),x=n.bufferSync(c),v=T9(x,y,m);return d.forEach(I=>n.disposeIntermediateTensorInfo(I)),n.makeTensorInfo(u.outputShape,v.dtype,v.values)}let f=new Nae(c.shape,m),g=n.runWebGLProgram(f,[c,h],c.dtype);d.push(g);let b=ce({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return d.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}var Cae={kernelName:Cu,backendName:"webgl",kernelFunc:GA},_ae="return float(a > b);",Eae=`
  return vec4(greaterThan(a, b));
`,Aae=fn({opSnippet:_ae,packedOpSnippet:Eae,cpuKernelImpl:C9,dtype:"bool"}),Fae={kernelName:Eu,backendName:"webgl",kernelFunc:Aae},$ae="return float(a >= b);",Dae=`
  return vec4(greaterThanEqual(a, b));
`,Rae=fn({opSnippet:$ae,packedOpSnippet:Dae,dtype:"bool",cpuKernelImpl:_9}),Mae={kernelName:eo,backendName:"webgl",kernelFunc:Rae};function Pae(e){let{inputs:t,backend:n}=e,{input:a}=t;return UA(a,!0,n)}var Oae={kernelName:Um,backendName:"webgl",kernelFunc:Pae},Lae="return float(!isnan(x) && !isinf(x));",zae=Ze({opSnippet:Lae,dtype:"bool"}),Wae={kernelName:no,backendName:"webgl",kernelFunc:zae},Bae="return float(isinf(x));",Vae=Ze({opSnippet:Bae,dtype:"bool"}),Uae={kernelName:ao,backendName:"webgl",kernelFunc:Vae},Gae="return float(isnan(x));",Hae=Ze({opSnippet:Gae,dtype:"bool"}),qae={kernelName:ro,backendName:"webgl",kernelFunc:Hae},jae="return float(a < b);",Kae=`
  return vec4(lessThan(a, b));
`,Xae=fn({opSnippet:jae,packedOpSnippet:Kae,cpuKernelImpl:E9,dtype:"bool"}),Yae={kernelName:Au,backendName:"webgl",kernelFunc:Xae},Zae="return float(a <= b);",Jae=`
  return vec4(lessThanEqual(a, b));
`,Qae=fn({opSnippet:Zae,packedOpSnippet:Jae,cpuKernelImpl:A9,dtype:"bool"}),ere={kernelName:Fu,backendName:"webgl",kernelFunc:Qae};function tre(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=F9(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var nre={kernelName:$u,backendName:"webgl",kernelFunc:tre},are=Tp+`
  return x < 0.0 ? 0./0. : log(x);
`,rre=`
  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;
`,sre=Ze({opSnippet:are,packedOpSnippet:rre,cpuKernelImpl:$9}),ire={kernelName:io,backendName:"webgl",kernelFunc:sre},ore=Tp+`
  return log(1.0 + x);
`,lre=Ze({opSnippet:ore}),ure={kernelName:oo,backendName:"webgl",kernelFunc:lre},pre="return float(a >= 1.0 && b >= 1.0);",cre=`
  return vec4(
    vec4(greaterThanEqual(a, vec4(1.0))) *
    vec4(greaterThanEqual(b, vec4(1.0))));
`,dre=fn({opSnippet:pre,packedOpSnippet:cre,dtype:"bool"}),hre={kernelName:Du,backendName:"webgl",kernelFunc:dre},mre="return float(!(x >= 1.0));",fre=Ze({opSnippet:mre}),gre={kernelName:Ru,backendName:"webgl",kernelFunc:fre},bre="return float(a >= 1.0 || b >= 1.0);",yre=`
  return min(
    vec4(greaterThanEqual(a, vec4(1.0))) +
    vec4(greaterThanEqual(b, vec4(1.0))),
    vec4(1.0));
`,xre=fn({opSnippet:bre,packedOpSnippet:yre,dtype:"bool"}),vre={kernelName:Mu,backendName:"webgl",kernelFunc:xre},wre=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${n}) + float(${a}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${r}));`,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 = -${s}; j <= ${s}; j++) {
          int idx = d + j;
          if (idx >= 0 && idx <=  ${i}) {
            float z = getX(b, r, c, idx);
            sum += z * z;
          }
        }
        float val = x * ${o};
        setOutput(val);
      }
    `}},kre=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${n}) + float(${a}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${r}));`,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 - ${s};
        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 = - ${s}; j <= ${s}; j++) {
          ivec2 idx = depth + j;
          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
 
          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 * ${o};
        setOutput(result);
      }
    `}},Ire=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,u=G().getBool("WEBGL_PACK_NORMALIZATION")?new kre(r.shape,s,i,o,l):new wre(r.shape,s,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)},Sre={kernelName:lo,backendName:"webgl",kernelFunc:Ire},Nre=class{constructor(e,t,n,a,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=a,this.beta=r,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 - ${t})));
          int depthEnd = int(min(float(${this.depth}),
              float(d + ${t} + 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(${a}) * 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(${a})
                * float(${r})
                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
                / norm;
              if (k == d) {
                dyi += pow(norm, -1.0 * ${r});
              }
              if (k == coords[3]) {
                dyi *= getDy(b, r, c, d);
                result += dyi;
              }
            }
            else {
              break;
            }
          }
      }
      setOutput(result);
      }
    `}},Tre=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a,d=new Nre(r.shape,o,l,u,p);return n.runWebGLProgram(d,[r,s,i],r.dtype)},Cre={kernelName:Pu,backendName:"webgl",kernelFunc:Tre};function _re(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=ce({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=tl(i,e.dtype,"max",a),l=ce({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function HA(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=N.getAxesPermutation(u,o),d=p!=null,c=n.shouldExecuteOnCPU([r]),h=r;if(d){if(c){let y=n.texData.get(h.dataId).values,x=new Array(o);for(let T=0;T<x.length;T++)x[T]=r.shape[p[T]];let v=lk(y,r.shape,r.dtype,p,x);h=n.makeTensorInfo(x,r.dtype);let I=n.texData.get(h.dataId);I.values=v}else h=eg(r,p,n);u=N.getInnerMostAxes(u.length,o)}N.assertAxesAreInnerMostDims("max",u,o);let[m,f]=N.computeOutAndReduceShapes(h.shape,u),g=m;i&&(g=N.expandShapeToKeepDim(m,l));let b;if(c){let y=n.texData.get(h.dataId).values,x=D9(y,w.sizeFromShape(f),g,r.dtype);b=n.makeTensorInfo(g,r.dtype);let v=n.texData.get(b.dataId);v.values=x}else b=_re(h,f,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var Ere={kernelName:uo,backendName:"webgl",kernelFunc:HA},Are=uk+`
  return max(a, b);
`,Fre=`
  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);
  `+el+`
  return result;
`,$re=fn({opSnippet:Are,packedOpSnippet:Fre,cpuKernelImpl:R9}),Dre={kernelName:po,backendName:"webgl",kernelFunc:$re};function Rre(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;vp(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=N.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))return ra({inputs:{x:r},backend:n});let d=new $c(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var Mre={kernelName:co,backendName:"webgl",kernelFunc:Rre};function Pre(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=a,p=[1,1,1],d=N.computePool3DInfo(r.shape,s,i,p,o,u,l),c=new ck(d,"max",!1);return n.runWebGLProgram(c,[r],r.dtype)}var Ore={kernelName:Ou,backendName:"webgl",kernelFunc:Pre},Lre=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,a=e.dilationHeight,r=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=s-1-e.padInfo.left,l=r*s-1;this.userCode=`
      const ivec2 pads = ivec2(${i}, ${o});
 
      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 < ${r};
          wR += ${a}) {
          float dyR = float(dyRCorner + wR) / ${t}.0;
 
          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
 
          for (int wC = 0; wC < ${s}; wC++) {
            float dyC = float(dyCCorner + wC) / ${n}.0;
 
            if (dyC < 0.0 || dyC >= ${e.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 * ${s} + wC;
            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
 
            dotProd += dyValue * mask;
          }
        }
        setOutput(dotProd);
      }
    `}},zre=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,p=o-1-e.padInfo.front,d=l-1-e.padInfo.top,c=u-1-e.padInfo.left,h=o*l*u-1;this.userCode=`
      const ivec3 pads = ivec3(${p}, ${d}, ${c});
 
      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 < ${o};
           wD += ${r}) {
          float dyD = float(dyDCorner + wD) / ${t}.0;
 
          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
            continue;
          }
          int idyD = int(dyD);
 
          for (int wR = 0; wR < ${l};
              wR += ${s}) {
            float dyR = float(dyRCorner + wR) / ${n}.0;
 
            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
                fract(dyR) > 0.0) {
              continue;
            }
            int idyR = int(dyR);
 
            for (int wC = 0; wC < ${u};
                wC += ${i}) {
              float dyC = float(dyCCorner + wC) / ${a}.0;
 
              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
                  fract(dyC) > 0.0) {
                continue;
              }
              int idyC = int(dyC);
 
              float dyValue = getDy(batch, idyD, idyR, idyC, ch);
              int maxPosValue = ${h} -
                  int(getMaxPos(batch, idyD, idyR, idyC, ch));
 
              // Get the current value, check it against the value from the
              // position matrix.
              int curPosValue =
                  wD * ${l} * ${u} +
                  wR * ${u} + wC;
              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
 
              dotProd += dyValue * mask;
            }
          }
        }
        setOutput(dotProd);
      }
    `}};function Wre(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=a,d=[1,1,1],c=N.computePool3DInfo(i.shape,o,l,d,u,p),h=new ck(c,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new zre(c),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var Bre={kernelName:Hc,backendName:"webgl",kernelFunc:Wre};function Vre(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;vp([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:d}=a,c=N.computePool2DInfo(o.shape,l,u,1,p,d),h=!0,m=new $c(c,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new Lre(c),b=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),b}var Ure={kernelName:Gc,backendName:"webgl",kernelFunc:Vre};function Gre(e,t,n,a){let r=new $c(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new $c(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var Hre={kernelName:qc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;w.assert(a.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`);let u=[1,1];w.assert(N.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let p=N.computePool2DInfo(a.shape,r,s,u,i),[d,c]=Gre(a,o,p,l);return[d,c]}};function qre(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=ce({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=tl(i,"float32","mean",a),l=ce({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var jre={kernelName:ho,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{keepDims:r,axis:s}=t,i=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,p=N.getAxesPermutation(u,o),d=p!=null,c=i.shouldExecuteOnCPU([a]),h=[],m=a;if(d){if(c){let x=i.texData.get(m.dataId).values,v=new Array(o);for(let C=0;C<v.length;C++)v[C]=a.shape[p[C]];let I=lk(x,a.shape,a.dtype,p,v);m=i.makeTensorInfo(v,a.dtype);let T=i.texData.get(m.dataId);T.values=I}else m=eg(a,p,i);h.push(m),u=N.getInnerMostAxes(u.length,o)}N.assertAxesAreInnerMostDims("sum",u,o);let[f,g]=N.computeOutAndReduceShapes(m.shape,u),b=f;r&&(b=N.expandShapeToKeepDim(f,l));let y=qre(m,g,b,i);for(let x of h)i.disposeIntermediateTensorInfo(x);return y}};function Kre(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=N.getAxesPermutation(u,o),d=r;p!=null&&(d=Nn({inputs:{x:r},backend:n,attrs:{perm:p}}),u=N.getInnerMostAxes(u.length,r.shape.length)),N.assertAxesAreInnerMostDims("min",u,o);let[c,h]=N.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=tl(f,f.dtype,"min",n),b;if(i){let y=N.expandShapeToKeepDim(c,l);b=ce({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ce({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),b}var Xre={kernelName:mo,backendName:"webgl",kernelFunc:Kre},Yre=uk+`
  return min(a, b);
`,Zre=`
  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);
  `+el+`
  return result;
`,Jre=fn({opSnippet:Yre,packedOpSnippet:Zre,cpuKernelImpl:M9}),Qre={kernelName:fo,backendName:"webgl",kernelFunc:Jre},ese=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);let a=e.length,r=dt(a),s=t.map(u=>u[0]).join(","),i=t.map((u,p)=>u[0]+e[p]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a),l=n==="reflect"?0:1;if(a===1){this.userCode=`
        int start = ${s};
        int end = ${i};
 
        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=`
      ${r} start = ${r}(${s});
      ${r} end = ${r}(${i});
 
      void main() {
        ${r} outC = getOutputCoords();
        for (int i = 0; i < ${a}; 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};
          }
        }
        ${r} coords = outC - start;
        setOutput(getX(${o}));
      }
    `}},tse=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,m)=>h[0]+e[m]+h[1]);let a=e.length,r=dt(a),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=Sn("rc",a),l=Sn("source",a),u=`${o[a-1]} < ${this.outputShape[a-1]}`,p=a===1?"source":`vec2(${l.slice(-2).join()})`,d=n==="reflect"?0:1,c="";if(a===1){let h=`
        ${r} source = rc;
        if (source < start) {
          source = start * 2 - source - ${d};
        } else if (source >= end) {
          source = (end - 1) * 2 - source + ${d};
        }
        source -= start;
      `;c=`
        ${r} rc = outputLoc;
        ${h}
        result[0] = getChannel(getX(${l.join()}), ${p});
        ${o[a-1]} += 1;
        if(${u}) {
          ${h}
          result[1] = getChannel(getX(${l.join()}), ${p});
        }
      `}else{let h=`
        ${r} source = rc;
        ${r} lt = ${r}(lessThan(source, start));
        ${r} gte = ${r}(greaterThanEqual(source, end));
        ${r} orig = 1 - (lt + gte);
        source = orig * source +
                lt * (start * 2 - source - ${d}) +
                gte * ((end - 1) * 2 - source + ${d});
        source -= start;
      `;c=`
        ${r} rc = outputLoc;
        ${h}
        result[0] = getChannel(getX(${l.join()}), ${p});
        ${o[a-1]} += 1;
        if(${u}) {
          ${h}
          result[1] = getChannel(getX(${l.join()}), ${p});
        }
        rc = outputLoc;
        ${o[a-2]} += 1;
        if(${o[a-2]} < ${this.outputShape[a-2]}) {
          ${h}
          result[2] = getChannel(getX(${l.join()}), ${p});
          ${o[a-1]} += 1;
          if(${u}) {
            ${h}
            result[3] = getChannel(getX(${l.join()}), ${p});
          }
        }
      `}this.userCode=`
      const ${r} start = ${r}(${s});
      const ${r} end = ${r}(${i});
 
      void main() {
        ${r} outputLoc = getOutputCoords();
        vec4 result = vec4(0.);
        ${c}
        setOutput(result);
      }
    `}},nse=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tse(a.shape,r,s):new ese(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},ase={kernelName:go,backendName:"webgl",kernelFunc:nse},rse=`if (b == 0.0) return NAN;
  return mod(a, b);`,sse=`
  vec4 result = mod(a, b);
  bvec4 isNaN = equal(b, vec4(0.0));
  `+el+`
  return result;
`,ise=fn({opSnippet:rse,packedOpSnippet:sse}),ose={kernelName:bo,backendName:"webgl",kernelFunc:ise},lse=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,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 < ${t-1}; i++) {
          cdf += getProbs(batch, i);
 
          if (r < cdf) {
            setOutput(float(i));
            return;
          }
        }
 
        // If no other event happened, last event happened.
        setOutput(float(${t-1}));
      }
    `}},use=`
if (a == b) {
  return 1.0;
};
return a / b;`,pse=`
  // 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;
`,qA=fn({opSnippet:use,packedOpSnippet:pse,checkOutOfBounds:!0}),cse={kernelName:qi,backendName:"webgl",kernelFunc:qA},RS="return a - b;",jA=fn({opSnippet:RS,packedOpSnippet:RS,supportsComplex:!0,cpuKernelImpl:nQ}),dse={kernelName:Vo,backendName:"webgl",kernelFunc:jA};function KA(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=w.parseAxisParam([s],r.shape),o=HA({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=N.expandShapeToKeepDim(o.shape,i),u=ce({inputs:{x:o},backend:n,attrs:{shape:l}}),p=jA({inputs:{a:r,b:u},backend:n}),d=VA({inputs:{x:p},backend:n}),c=tg({inputs:{x:d},backend:n,attrs:{axis:i,keepDims:!1}}),h=ce({inputs:{x:c},backend:n,attrs:{shape:l}}),m=qA({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}var hse={kernelName:Wo,backendName:"webgl",kernelFunc:KA};function mse(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:KA({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],p=l.shape[1],d=new lse(u,p,s),c=[[i]],h=n.runWebGLProgram(d,[l],"int32",c);return o||n.disposeIntermediateTensorInfo(l),h}var fse={kernelName:Lu,backendName:"webgl",kernelFunc:mse},gse=Oa+`
  return -x;
`,bse=`
  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 yse(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=O9(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new os(a.shape,bse):r=new ir(a.shape,gse),n.runWebGLProgram(r,[a],a.dtype)}var xse={kernelName:zu,backendName:"webgl",kernelFunc:yse},vse=gr.nonMaxSuppressionV3Impl;function wse(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),{selectedIndices:d}=vse(u,p,i,o,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var kse={kernelName:Bu,backendName:"webgl",kernelFunc:wse},Ise=gr.nonMaxSuppressionV4Impl;function Sse(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=a,p=n.readSync(r.dataId),d=n.readSync(s.dataId),{selectedIndices:c,validOutputs:h}=Ise(p,d,i,o,l,u);return[n.makeTensorInfo([c.length],"int32",new Int32Array(c)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Nse={kernelName:Vu,backendName:"webgl",kernelFunc:Sse},Tse=gr.nonMaxSuppressionV5Impl;function Cse(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=a,p=n.readSync(r.dataId),d=n.readSync(s.dataId),c=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:b}=Tse(p,d,c,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var _se={kernelName:Uu,backendName:"webgl",kernelFunc:Cse},Ese=class{constructor(e,t,n,a){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
      void main() {
        ivec2 coords = getOutputCoords();
        int index = round(getIndices(coords.x));
        setOutput(mix(float(${a}), float(${n}),
                      float(index == coords.y)));
      }
    `}},Ase=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=a,u=w.sizeFromShape(r.shape),p=new Ese(u,i,o,l),d=ce({inputs:{x:r},backend:n,attrs:{shape:[u]}}),c=n.runWebGLProgram(p,[d],s);n.disposeIntermediateTensorInfo(d);let h=[...r.shape,i],m=ce({inputs:{x:c},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(c),m},Fse={kernelName:xo,backendName:"webgl",kernelFunc:Ase};function Fm(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=Od({inputs:{input:a},backend:n}),s=Fm({inputs:{x:r},backend:n}),i=ng({inputs:{input:a},backend:n}),o=Fm({inputs:{x:i},backend:n}),l=Ms({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Ld({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var $se={kernelName:lp,backendName:"webgl",kernelFunc:Fm};function XA(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let r=Od({inputs:{input:a},backend:n}),s=XA({inputs:{x:r},backend:n}),i=ng({inputs:{input:a},backend:n}),o=Fm({inputs:{x:i},backend:n}),l=Ms({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Ld({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var Dse={kernelName:Gu,backendName:"webgl",kernelFunc:XA};function Rse(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return yv({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=yv({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=RA({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var Mse={kernelName:Hu,backendName:"webgl",kernelFunc:Rse},Pse=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let a=e.length,r=dt(a),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===1){this.userCode=`
        int start = ${s};
        int end = ${i};
 
        void main() {
          int outC = getOutputCoords();
          if (outC < start || outC >= end) {
            setOutput(value);
          } else {
            setOutput(getX(outC - start));
          }
        }
      `;return}this.userCode=`
      ${r} start = ${r}(${s});
      ${r} end = ${r}(${i});
 
      void main() {
        ${r} outC = getOutputCoords();
        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
          setOutput(value);
        } else {
          ${r} coords = outC - start;
          setOutput(getX(${o}));
        }
      }
    `}},Ose=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let a=e.length,r=dt(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=Sn("rc",a),l=Sn("source",a),u=`${o[a-1]} < ${this.outputShape[a-1]}`,p=a===1?"source":`vec2(${l.slice(-2).join()})`,d=[`${r} rc = outputLoc;`,`${o[a-1]} += 1;
       if(${u}) {
      `,a===1?"":`}
       rc = outputLoc;
       ${o[a-2]} += 1;
       if(${o[a-2]} < ${this.outputShape[a-2]}) {`,a===1?"":`  ${o[a-1]} += 1;
         if(${u}) {`],c=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let m=0,f=a===1?2:4;m<f;m++)h+=`
        ${d[m]}
        if (${c}) {
          result[${m}] = float(value);
        } else {
          ${r} source = rc - start;
          result[${m}] = getChannel(getX(${l.join()}), ${p});
        }
      `;h+=a===1?"} ":"}}",this.userCode=`
      const ${r} start = ${r}(${s});
      const ${r} end = ${r}(${i});
 
      void main() {
        ${r} outputLoc = getOutputCoords();
        vec4 result = vec4(0.);
        ${h}
        setOutput(result);
      }
    `}},YA=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;if(w.sizeFromShape(r.shape)===0){let u=s.map((p,d)=>p[0]+r.shape[d]+p[1]);return Ld({backend:n,attrs:{shape:u,value:i,dtype:r.dtype}})}let o=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ose(r.shape,s,i):new Pse(r.shape,s,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},Lse={kernelName:vo,backendName:"webgl",kernelFunc:YA},zse=`
  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);
`,Wse=`
  // 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);
  `+el+`
  return result;
`,Bse=fn({opSnippet:zse,packedOpSnippet:Wse}),Vse={kernelName:wo,backendName:"webgl",kernelFunc:Bse};function Use(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],u=w.parseAxisParam(s,r.shape),p=u,d=N.getAxesPermutation(p,o),c=r;d!=null&&(c=Nn({inputs:{x:r},backend:n,attrs:{perm:d}}),p=N.getInnerMostAxes(p.length,o),l.push(c)),N.assertAxesAreInnerMostDims("prod",p,o);let h;if(n.shouldExecuteOnCPU([c])){let m=n.texData.get(c.dataId).values,{outVals:f,outShape:g,outDtype:b}=z9(c.shape,c.dtype,m,p);h=n.makeTensorInfo(g,b,f)}else{let[m,f]=N.computeOutAndReduceShapes(c.shape,p),g=w.sizeFromShape(f),b=ce({inputs:{x:c},backend:n,attrs:{shape:[-1,g]}}),y=Ym(r.dtype),x=tl(b,y,"prod",n);h=ce({inputs:{x},backend:n,attrs:{shape:m}}),l.push(b),l.push(x)}if(i){l.push(h);let m=N.expandShapeToKeepDim(h.shape,u);h=ce({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var Gse={kernelName:Io,backendName:"webgl",kernelFunc:Use};function Hse(e){let{inputs:t,backend:n,attrs:a}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=a,l=r.map(b=>n.readSync(b.dataId)),u=r.map(b=>b.shape),p=n.readSync(s.dataId),d=n.readSync(i.dataId),[c,h,m]=W9(l,u,p,s.shape,s.dtype,d,i.shape,o),f=c.map(b=>n.makeTensorInfo([b.length],"int32",b)),g=n.makeTensorInfo(m,s.dtype,h);return f.concat([g])}var qse={kernelName:Hm,backendName:"webgl",kernelFunc:Hse};function jse(e){let{inputs:t,backend:n}=e,{starts:a,limits:r,deltas:s}=t,i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=B9(i,a.shape,a.dtype,o,r.shape,l,s.shape),d=n.makeTensorInfo([u.length],"int32",u),c=n.makeTensorInfo([p.length],a.dtype,p);return[d,c]}var Kse={kernelName:qm,backendName:"webgl",kernelFunc:jse};function Xse(e){let{inputs:t,backend:n,attrs:a}=e,{shape:r,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),d=n.readSync(i.dataId),c=o.map(g=>n.readSync(g.dataId)),h=o.map(g=>g.shape),[m,f]=V9(u,r.shape,p,s.shape,s.dtype,d,i.shape,c,h,l);return n.makeTensorInfo(m,s.dtype,f)}var Yse={kernelName:jm,backendName:"webgl",kernelFunc:Xse},ZA=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=U9(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},Zse={kernelName:jc,backendName:"webgl",kernelFunc:ZA},Jse="return 1.0 / x;",Qse=Ze({opSnippet:Jse}),eie={kernelName:So,backendName:"webgl",kernelFunc:Qse},tie=Oa+`
  return (x < 0.0) ? 0.0 : x;
`,nie=`
  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;
`,aie=Ze({opSnippet:tie,packedOpSnippet:nie}),rie={kernelName:No,backendName:"webgl",kernelFunc:aie},sie=Oa+`
  return (x < 0.0) ? 0.0 : min(6.0, x);
`,iie=`
  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;
`,oie=Ze({opSnippet:sie,packedOpSnippet:iie}),lie={kernelName:_o,backendName:"webgl",kernelFunc:oie},uie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d;r?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec2 effectiveInputOverOutputRatioRC = vec2(
          ${u[0]/p[0]},
          ${u[1]/p[1]});
      const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
 
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        ivec2 yRC = coords.yz;
 
        // Fractional source index.
        vec2 sourceFracIndexRC = ${d};
 
        // 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);
      }
    `}},pie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d;r?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec3 effectiveInputOverOutputRatioRC = vec3(
          ${u[0]/p[0]},
          ${u[1]/p[1]},
          ${u[1]/p[1]});
      const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
                                     ${o}.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 = ${d};
 
        // 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 cie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,p=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new pie(r.shape,l,u,s,i):new uie(r.shape,l,u,s,i);return n.runWebGLProgram(p,[r],"float32")}var die={kernelName:Co,backendName:"webgl",kernelFunc:cie},hie=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],d=1/u,c=1/p,h=Math.ceil(d)*2+2,m=Math.ceil(c)*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(${u});
        const float widthScale = float(${p});
 
        const float invHeightScale = float(${d});
        const float invWidthScale = float(${c});
 
        const int winHeight = int(${h});
        const int winWidth = int(${m});
 
        // 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 >= ${s}) {
            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 >= ${i}) {
              continue;
            }
 
            float dxR = float(dyR) * heightScale;
            int topDxRIndex = int(floor(dxR));
            int bottomDxRIndex = int(min(ceil(dxR), ${a-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), ${r-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 mie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new hie(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var fie={kernelName:Ku,backendName:"webgl",kernelFunc:mie},gie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d=a?"0.5":"0.0",c;r?c="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":c="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec2 effectiveInputOverOutputRatioRC = vec2(
          ${u[0]/p[0]},
          ${u[1]/p[1]});
      const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
 
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        ivec2 yRC = coords.yz;
 
        // Fractional source index.
        vec2 sourceFracIndexRC = ${c};
 
        // Compute the coordinators of nearest neighbor point.
        ivec2 sourceNearestRC = ivec2(
          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
 
        setOutput(newValue);
      }
    `}},bie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d=a?"0.5":"0.0",c;r?c="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":c="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec3 effectiveInputOverOutputRatioRC = vec3(
          ${u[0]/p[0]},
          ${u[1]/p[1]},
          ${u[1]/p[1]});
      const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
                                     ${o}.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 = ${c};
 
        // Compute the coordinators of nearest neighbor point.
        ivec3 sourceNearestRC = ivec3(
          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
 
        // 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 yie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,p=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new bie(r.shape,l,u,s,i):new gie(r.shape,l,u,s,i);return n.runWebGLProgram(p,[r],r.dtype)}var xie={kernelName:To,backendName:"webgl",kernelFunc:yie},vie=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],d=1/u,c=1/p,h=Math.ceil(d)*2+2,m=Math.ceil(c)*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(${u});
        const float widthScale = float(${p});
 
        const float invHeightScale = float(${d});
        const float invWidthScale = float(${c});
 
        const int winHeight = int(${h});
        const int winWidth = int(${m});
 
        // 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 >= ${s}) {
            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 >= ${i}) {
              continue;
            }
 
            float sourceFracRow =
              float(${o[0]}) *
                (float(dyR) / float(${l[0]}));
 
            float sourceFracCol =
                float(${o[1]}) *
                  (float(dyC) / float(${l[1]}));
 
            int sourceNearestRow = int(min(
                float(int(${a}) - 1),
                ${n} ? float(round(sourceFracRow)) :
                                  float(floor(sourceFracRow))));
 
            int sourceNearestCol = int(min(
                float(int(${r}) - 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 wie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new vie(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var kie={kernelName:ju,backendName:"webgl",kernelFunc:wie},Iie=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
        void main() {
          int coord = getOutputCoords();
          setOutput(getX(${e[0]} - coord - 1));
        }
      `;return}let a=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,r=e.map((i,o)=>a(o)).join(","),s=dt(n);this.userCode=`
      void main() {
        ${s} coords = getOutputCoords();
        setOutput(getX(${r}));
      }
    `}},Sie=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let a=Sn("rc",n),r=`${a[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${a[n-2]} + 1 < ${this.outputShape[n-2]}`,i=dt(n);n===1?this.userCode=`
        void main(){
          int rc = getOutputCoords();
          vec4 result = vec4(0.);
          result.r = getChannel(getX(${e[0]} - rc - 1),
            ${e[0]} - rc - 1);
          if(${r}){
              result.g = getChannel(getX(${e[0]} - (rc  + 1) - 1),
                ${e[0]} - (rc  + 1) - 1);
          }
          setOutput(result);
        }
      `:this.userCode=`
        void main() {
          ${i} rc = getOutputCoords();
          vec4 result = vec4(0.);
          result.r = ${o(a.slice())};
          if(${r}){
            result.g = ${l(a.slice())};
          }
          if(${s}) {
            result.b = ${u(a.slice())};
            if(${r}) {
              result.a = ${p(a.slice())};
            }
          }
          setOutput(result);
        }
    `;function o(h){return d(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function p(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let m=e.map((b,y)=>c(y,h)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function c(h,m){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${m[h]} - 1`:`${m[h]}`}}};function Nie(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return ra({inputs:{x:r},backend:n});let l=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Sie(r.shape,o):new Iie(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var Tie={kernelName:Eo,backendName:"webgl",kernelFunc:Nie},Cie=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],a=e[2];this.outputShape=e;let r="";typeof t=="number"?r=`float outputValue = ${t.toFixed(2)};`:r=`
        vec3 fill = vec3(${t.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]));
          ${r}
          if(coordX >= 0 && coordX < ${a} && coordY >= 0 && coordY < ${n}) {
            outputValue = getImage(coords[0], coordY, coordX, coords[3]);
          }
          setOutput(outputValue);
        }
    `}},_ie={kernelName:up,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new Cie(a.shape,s),[u,p]=N.getImageCenter(i,a.shape[1],a.shape[2]),d=[[u,p,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[a],a.dtype,d)}},Eie=`
  // 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;
    }
  }
`,Aie=Ze({opSnippet:Eie}),Fie={kernelName:Ao,backendName:"webgl",kernelFunc:Aie},$ie="return inversesqrt(x);",Die=Ze({opSnippet:$ie,cpuKernelImpl:G9}),Rie={kernelName:Fo,backendName:"webgl",kernelFunc:Die},dk=class{constructor(e,t,n,a,r,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let l=dt(r.length),u=dt(s.length),p="";n===1?p="i":n===2&&(p="i, j");let d=`getIndices(${p})`,c="";a===1?c="i":a===2&&(c="i, coords[1]");let h=`getUpdates(${c})`,m="";o&&(m="coords[0], coords[1]");let f=`getDefaultValue(${m})`,g=t>1?"strides[j]":"strides";this.userCode=`
        ${l} strides = ${l}(${r});
 
        void main() {
          ${u} coords = getOutputCoords();
          float sum = 0.0;
          bool found = false;
          for (int i = 0; i < ${e}; i++) {
            int flattenedIndex = 0;
            for (int j = 0; j < ${t}; j++) {
              int index = round(${d});
              flattenedIndex += index * ${g};
            }
            if (flattenedIndex == coords[0]) {
              sum += ${h};
              found = true;
            }
          }
          setOutput(mix(${f}, sum, float(found)));
        }
      `}},Mie=class{constructor(e,t,n,a,r,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s;let l=dt(r.length),u=dt(s.length),p="";n===1?p="i":n===2&&(p="i, j");let d=`getIndices(${p})`,c="";a===1?c="i":a===2&&(c="i, coords[1]");let h=`getUpdates(${c})`,m="";o&&(m="coords[0], coords[1]");let f=`getDefaultValue(${m})`,g=t>1?"strides[j]":"strides",b=t>1?"strides[j + 1]":"strides";this.userCode=`
        ${l} strides = ${l}(${r});
 
        void main() {
          ${u} coords = getOutputCoords();
          vec4 sum = vec4(0.);
          vec4 found = vec4(0.);
          for (int i = 0; i < ${e}; i+=2) {
            ivec2 flattenedIndex = ivec2(0);
            for (int j = 0; j < ${t}; j+=2) {
              ivec4 index = round(${d});
              flattenedIndex += index.xz * ${g};
              if (j + 1 < ${t}) {
                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 = ${h};
              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(${f}, sum, found));
        }
      `}};function Pie(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=N.calculateShapes(s,r,i),c=[d/u,u];if(d===0)return n.makeTensorInfo(i,r.dtype);let h=ce({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=ce({inputs:{x:s},backend:n,attrs:{shape:[l,u]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g;G().getBool("WEBGL_PACK")?g=new Mie(l,o,h.shape.length,m.shape.length,p,c):g=new dk(l,o,h.shape.length,m.shape.length,p,c);let b=n.runWebGLProgram(g,[m,h,f],m.dtype),y=ce({inputs:{x:b},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(f),y}var Oie={kernelName:Xu,backendName:"webgl",kernelFunc:Pie},Lie=class{constructor(e,t,n,a){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];let r="while (left < right) {",s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=G().getNumber("WEBGL_VERSION")===2?r:s,o=a==="left"?"<":"<=";this.userCode=`
       int findBound(int batch, float value) {
         int left = 0;
         int right = numInputs;
         int mid;
         ${i}
           mid = (left + right) / 2;
           if (getSortedSequence(batch, mid) ${o} 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 zie(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a,o=new Lie(r.shape[0],r.shape[1],s.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,s],"int32",l)}var Wie={kernelName:Zu,backendName:"webgl",kernelFunc:zie},Bie=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let a,r;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)r="resRC",a="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u<t.length;u++)l.push(`${i[u]}`),u<e&&o.push(`${i[u]}`);a=o.join(),r=l.join()}let s=dt(n);this.userCode=`
      void main() {
        ${s} resRC = getOutputCoords();
        float cVal = getC(${a});
        if (cVal >= 1.0) {
          setOutput(getA(${r}));
        } else {
          setOutput(getB(${r}));
        }
      }
    `}};function Vie(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new Bie(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],ba(r.dtype,s.dtype))}var Uie={kernelName:Ju,backendName:"webgl",kernelFunc:Vie},Gie=`
  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
  // see: https://arxiv.org/abs/1706.02515
  float scaleAlpha = ${N.SELU_SCALEALPHA};
  float scale = ${N.SELU_SCALE};
  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`,Hie=Ze({opSnippet:Gie}),qie={kernelName:$o,backendName:"webgl",kernelFunc:Hie},jie=Tp+`
  return 1.0 / (1.0 + exp(-1.0 * x));
`,Kie=`
  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;
`,Xie=Ze({opSnippet:jie,packedOpSnippet:Kie,cpuKernelImpl:q9}),Yie={kernelName:Po,backendName:"webgl",kernelFunc:Xie},Zie=`
  if (isnan(x)) { return 0.0; }
  return sign(x);
`,Jie=Ze({opSnippet:Zie}),Qie={kernelName:Mo,backendName:"webgl",kernelFunc:Jie},eoe=Tp+`
  return sin(x);
`,toe=`
  vec4 result = sin(x);
  bvec4 isNaN = isnan(x);
  ${el}
  return result;
`,noe=Ze({opSnippet:eoe,packedOpSnippet:toe}),aoe={kernelName:Do,backendName:"webgl",kernelFunc:noe},roe=`
  float e2x = exp(x);
  return (e2x - 1.0 / e2x) / 2.0;
`,soe=Ze({opSnippet:roe}),ioe={kernelName:Ro,backendName:"webgl",kernelFunc:soe},ooe=`
  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;
`,loe=Ze({opSnippet:ooe}),uoe={kernelName:Oo,backendName:"webgl",kernelFunc:loe},poe=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;w.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((b,y)=>b*y),l=[[0,0]];l.push(...i);for(let b=1+s.length;b<r.shape.length;++b)l.push([0,0]);let u=[],p=YA({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),d=N.getReshaped(p.shape,s,o,!1),c=N.getPermuted(d.length,s.length,!1),h=N.getReshapedPermuted(p.shape,s,o,!1),m=ce({inputs:{x:p},backend:n,attrs:{shape:d}}),f=Nn({inputs:{x:m},backend:n,attrs:{perm:c}}),g=ce({inputs:{x:f},backend:n,attrs:{shape:h}});return u.push(p),u.push(m),u.push(f),u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},coe={kernelName:ep,backendName:"webgl",kernelFunc:poe};function doe(e){let{inputs:t,backend:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
         ${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
         ${a.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
         ${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
        ${i.shape}`);let o=n.readSync(a.dataId),l=n.readSync(r.dataId),u=n.readSync(s.dataId),p=n.readSync(i.dataId)[0],[d,c,h,m,f]=K9(o,a.shape,a.dtype,l,r.dtype,u,p);return[n.makeTensorInfo(c,a.dtype,d),n.makeTensorInfo([c[0]],r.dtype,h),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var hoe={kernelName:Kc,backendName:"webgl",kernelFunc:doe};function moe(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(n.readSync(r.dataId)),o=n.readSync(a.dataId),l=Array.from(n.readSync(s.dataId)),[u,p,d]=X9(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(p,a.dtype,u),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var foe={kernelName:np,backendName:"webgl",kernelFunc:moe};function goe(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
              ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
              ${s.shape}`);let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=vA(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(p,a.dtype,u)}var boe={kernelName:Xc,backendName:"webgl",kernelFunc:goe};function yoe(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
             ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
             ${s.shape}`);let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=vA(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(p,a.dtype,u)}var xoe={kernelName:Yc,backendName:"webgl",kernelFunc:yoe};function voe(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=N.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let b=n.bufferSync(r),y=n.bufferSync(s),x=w.decodeString(n.readSync(i.dataId)[0]),v=H9(b,y,o,c,p,u,l,d,x,h);return n.makeTensorInfo(o,v.dtype,v.values)}let m=new dk(u,l,r.shape.length,s.shape.length,d,[c,1],h),f=n.runWebGLProgram(m,[s,r,i],s.dtype),g=ce({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),g}var woe={kernelName:ap,backendName:"webgl",kernelFunc:voe};function koe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=N.prepareSplitSize(r,s,o),u=r.shape.length,p=new Array(u).fill(0),d=r.shape.slice();return l.map(c=>{let h=[...d];h[o]=c;let m=Cp({inputs:{x:r},backend:n,attrs:{begin:p,size:h}});return p[o]+=c,m})}var Ioe={kernelName:tp,backendName:"webgl",kernelFunc:koe},MS="return sqrt(x);",Soe=Ze({opSnippet:MS,packedOpSnippet:MS,cpuKernelImpl:Y9}),Noe={kernelName:Lo,backendName:"webgl",kernelFunc:Soe},Toe="return x * x;",Coe=Ze({opSnippet:Toe}),_oe={kernelName:Zc,backendName:"webgl",kernelFunc:Coe},PS="return (a - b) * (a - b);",Eoe=fn({opSnippet:PS,packedOpSnippet:PS}),Aoe={kernelName:Bo,backendName:"webgl",kernelFunc:Eoe};function Foe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");let s=n.readSync(r.dataId),i=N.fromUint8ToStringArray(s),o=Z9(i,"string",a);return n.makeTensorInfo(r.shape,"string",o)}var $oe={kernelName:Jc,backendName:"webgl",kernelFunc:Foe};function Doe({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=Oa+`
    return x > 0.0 ? 1.0 : float(${t.alpha});
  `,s=new ir(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var Roe={kernelName:Ts,backendName:"webgl",kernelFunc:Doe},Moe=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=dt(n.length),s=dt(n.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=n.map((l,u)=>(o++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${o-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
      ${r} begin = ${r}(${e});
      ${r} strides = ${r}(${t});
 
      void main() {
        ${s} coords = getOutputCoords();
        setOutput(getX(${i}));
      }
    `}};function Poe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:b,begin:y,end:x,strides:v}=Xt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),I;if(f)I=ce({inputs:{x:r},backend:n,attrs:{shape:m}});else if(g||b){w.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let C=Xt.computeOutShape(y,x,v),E=Cp({inputs:{x:r},backend:n,attrs:{begin:y,size:C}});I=ce({inputs:{x:E},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(E)}else if(n.shouldExecuteOnCPU([r])){let C=n.readSync(r.dataId),E=ze(r.shape,r.dtype,C),F=J9(h,E,v,y);I=n.makeTensorInfo(m,r.dtype,F.values)}else{let C=new Moe(y,v,h);I=n.runWebGLProgram(C,[r],r.dtype)}let T=ce({inputs:{x:I},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(I),T}var Ooe={kernelName:rp,backendName:"webgl",kernelFunc:Poe};function Loe(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:p,dataSplits:d}=t,c=n.readSync(p.dataId),h=n.readSync(d.dataId),[m,f]=Q9(c,h,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(d.shape,"int32",f)]}var zoe={kernelName:Qc,backendName:"webgl",kernelFunc:Loe};function Woe(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{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 o=n.readSync(s.dataId),l=n.readSync(i.dataId)[0],[u,p,d]=eQ(o,l,r),c=p.length;return[n.makeTensorInfo([c,2],"int32",u),n.makeTensorInfo([c],"string",p),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Boe={kernelName:ed,backendName:"webgl",kernelFunc:Woe};function Voe(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.readSync(s.dataId),o=tQ(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var Uoe={kernelName:td,backendName:"webgl",kernelFunc:Voe},Goe="return tan(x);",Hoe=Ze({opSnippet:Goe}),qoe={kernelName:Uo,backendName:"webgl",kernelFunc:Hoe},joe=`
  float e2x = exp(-2.0 * abs(x));
  return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,Koe=Ze({opSnippet:joe}),Xoe={kernelName:Go,backendName:"webgl",kernelFunc:Koe};function Yoe(e){let{inputs:t,backend:n,attrs:a}=e,{tensor:r,indices:s,updates:i}=t,{}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=N.calculateShapes(i,s,r.shape),c=[d/u,u];if(d===0)return n.makeTensorInfo(r.shape,s.dtype);let h=ce({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),m=ce({inputs:{x:i},backend:n,attrs:{shape:[l,u]}}),f=ce({inputs:{x:r},backend:n,attrs:{shape:c}}),g=new dk(l,o,h.shape.length,m.shape.length,p,c,!1,!0),b=n.runWebGLProgram(g,[m,h,f],f.dtype),y=ce({inputs:{x:b},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),y}var Zoe={kernelName:Yu,backendName:"webgl",kernelFunc:Yoe},Joe=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;let a=dt(this.rank),r=Qoe(e);this.userCode=`
      void main() {
        ${a} resRC = getOutputCoords();
        setOutput(getA(${r}));
      }
    `}};function Qoe(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],a=[];for(let r=0;r<e.length;r++)a.push(`imod(${n[r]}, ${e[r]})`);return a.join()}function JA(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;if(r.dtype==="string"||r.shape.length>5){let o=n.readSync(r.dataId),l=r.dtype==="string"?o.map(d=>w.decodeString(d)):o,u=ze(r.shape,r.dtype,l),p=aQ(u,s);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new Joe(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var ele={kernelName:Ns,backendName:"webgl",kernelFunc:JA},tle=class{constructor(e){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=e,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));
         }
       }
     `}},nle=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,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 js(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function OS(e){let t=1;for(;t<e;)t*=2;return t}function ale(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=G().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=G().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,p=u[u.length-1];if(n.shouldExecuteOnCPU([r])||p<o||s>l){let F=n.readSync(r.dataId),[D,$]=rQ(F,u,r.dtype,s,i);return[n.makeTensorInfo(D.shape,D.dtype,D.values),n.makeTensorInfo($.shape,$.dtype,$.values)]}if(s===0)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(p===1)return[r,Ld({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),c=d!==null&&d.isPacked,h=c?n.unpackTensor(r):r,m=w.sizeFromShape(u)/p,f=ce({inputs:{x:h},attrs:{shape:[m,p]},backend:n});c&&js(n,h);let g=OS(s),b=OS(p),y=null,x=()=>y===null?[f,f]:[f,y],v=(F,D,$)=>{let S=x(),M=new tle($),B=[[p],[y===null?1:0],[Number.NEGATIVE_INFINITY],[F],[D]],U=y;y=n.runWebGLProgram(M,S,"int32",B),js(n,U)};for(let F=1;F<g;F*=2){let D=F*2;for(let $=F;$>=1;$/=2)v(D,$,[m,b])}for(let F=b;F>g;F/=2){let D=x(),$=new nle([m,F/2]),S=[[p],[y===null?1:0],[g]],M=y;y=n.runWebGLProgram($,D,"int32",S),js(n,M);let B=g/2,U=B*2;for(let H=B;H>=1;H/=2)v(U,H,y.shape)}let I=y;y=Cp({inputs:{x:y},backend:n,attrs:{begin:0,size:[m,s]}}),js(n,I);let T=GA({inputs:{x:f,indices:y},backend:n,attrs:{axis:1,batchDims:1}});js(n,f);let C=u.slice(0,-1);C.push(s),I=y,y=ce({inputs:{x:y},attrs:{shape:C},backend:n}),js(n,I);let E=T;return T=ce({inputs:{x:T},attrs:{shape:C},backend:n}),js(n,E),[T,y]}var rle={kernelName:sp,backendName:"webgl",kernelFunc:ale},sle=class{constructor(e,t,n,a,r,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=n==="nearest"?1:2,o;switch(a){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=`
            float mapCoord(float outCoord, float len) {
              float inCoord = outCoord;
              if(${o} == 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 (${o} == 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 (${o} == 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 < ${e} && 0 <= coordX && coordX < ${t}) {
                  outputValue = getImage(batch, coordY, coordX, channel);
              } else {
                outputValue = float(${r});
              }
              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(${r});
              } else {
                float inX = (a1 * xf + a2 * yf + a3) / projection;
                float inY = (b1 * xf + b2 * yf + b3) / projection;
                float mapX = mapCoord(inX, float(${t}));
                float mapY = mapCoord(inY, float(${e}));
 
                if (${i} == 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 ile(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],b=new sle(d,c,i,o,l,g);return n.runWebGLProgram(b,[r,s],"float32")}var ole={kernelName:ip,backendName:"webgl",kernelFunc:ile};function lle(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;vp(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=sQ(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([u.length],"int32",u)]}var ule={kernelName:nd,backendName:"webgl",kernelFunc:lle};function ple(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],u=new Array(o-1),p=0;for(let f=0;f<o;f++)f!==s&&(u[p++]=i.shape[f]);let d=[],c=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){c[s]=f;let g=Cp({inputs:{x:i},backend:n,attrs:{begin:c,size:h}}),b=ce({inputs:{x:g},backend:n,attrs:{shape:u}});m[f]=b,d.push(g)}return d.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var cle={kernelName:op,backendName:"webgl",kernelFunc:ple},dle=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,a=e.batchSize,r=e.inSize,s=e.numSegments,i=s*Math.ceil(r/n);this.outputShape=[a,i];let o="0.0",l="sumValue",u=Math.floor(n/4)*4,p=n%4,d=`
        sumValue += dot(values, segFilter);
    `,c="";r%n>0&&(c=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return initializationValue;
        }
      `);let h="";r%n>0&&(h=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return -1.0;
        }
      `),this.userCode=`
      const float initializationValue = ${o};
 
      float getValue(int batch, int inIdx) {
        ${c}
        return getX(batch, inIdx);
      }
 
      float getSegmentIdAtIndex(int inIdx) {
        ${h}
        return getSegmentIds(inIdx);
      }
 
      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = int(floor(float(outIdx) / float(
          ${s})) * float(${n}));
        int currentSeg = int(mod(float(outIdx), float(${s})));
 
        float sumValue = 0.0;
 
        for (int i = 0; i < ${u}; 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
          );
 
          ${d}
        }
 
        int inIdx = inOffset + ${u};
        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
          );
 
          ${d}
        } 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
          );
 
          ${d}
        } 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
          );
 
          ${d}
        }
        setOutput(${l});
      }
    `}};function hle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],u=0,p=N.getAxesPermutation([u],o),d=r;p!=null&&(d=Nn({inputs:{x:r},backend:n,attrs:{perm:p}}),l.push(d),u=N.getInnerMostAxes(1,o)[0]);let c=N.segment_util.computeOutShape(d.shape,u,i),h=w.sizeFromShape([d.shape[u]]),m=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=Ym(r.dtype),g=(v,I,T,C,E)=>{let F=v.shape[0],D=v.shape[1],$=N.segment_util.segOpComputeOptimalWindowSize(D,E),S={windowSize:$,inSize:D,batchSize:F,numSegments:E},M=new dle(S,I),B=n.compileAndRun(M,[v,T],C);if(l.push(B),B.shape[1]===E)return B;let U=ZA({backend:n,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),H=JA({inputs:{x:U},backend:n,attrs:{reps:[D/$]}});return l.push(U),l.push(H),g(B,I,H,C,E)},b=g(m,"unsortedSegmentSum",s,f,i),y=ce({inputs:{x:b},backend:n,attrs:{shape:c}}),x=y;if(p!=null){l.push(y);let v=N.getUndoAxesPermutation(p);x=Nn({inputs:{x},backend:n,attrs:{perm:v}})}return l.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var mle={kernelName:ad,backendName:"webgl",kernelFunc:hle},fle=[JQ,eee,aee,iee,lee,cee,hee,fee,xee,wee,See,Cee,Aee,Ree,Oee,zee,Bee,Hee,jee,Xee,Qee,ite,lte,dte,mte,vte,kte,Tte,MQ,Ete,Rte,Lte,Gte,jte,Xte,Zte,Qte,ane,ine,une,cne,hne,fne,yne,vne,Sne,Tne,Ene,$ne,Rne,Lne,Vne,qne,Xne,Jne,Qne,tae,aae,sae,oae,uae,hae,gae,xae,wae,Sae,Cae,Fae,Mae,RQ,Oae,$te,Wae,Uae,qae,OQ,Yae,ere,nre,ire,ure,hre,gre,vre,Sre,Cre,Ere,Dre,Mre,Ore,Bre,Ure,Hre,jre,Xre,Qre,ase,ose,fse,WQ,xse,kse,Nse,_se,gte,Fse,Dse,Mse,Lse,Vse,zQ,Gse,qse,Kse,Yse,Zse,bte,cse,eie,rie,lie,VQ,die,fie,xie,kie,Tie,_ie,Fie,Rie,Oie,Wie,Uie,qie,Yie,Qie,aoe,ioe,rte,hse,uoe,coe,hoe,foe,boe,xoe,woe,Ioe,Noe,_oe,Aoe,$oe,Roe,Ooe,zoe,Boe,Uoe,dse,XQ,qoe,Xoe,Zoe,ele,rle,ole,YQ,ule,cle,mle,$se];for(let e of fle)rd(e);var Qe;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(Qe||(Qe={}));var Rc;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(Rc||(Rc={}));var QA;function gle(e){QA=e.wasm.cwrap(oi,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function ble(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a,c=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let E=n.dataIdMap.get(i.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);m=E.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=Rc[p];if(g==null)throw new Error(`${p} activation not yet supported for FusedConv2D in the wasm backend.`);let b=l?r.shape[2]:r.shape[1],y=u?s.shape[1]:s.shape[2],x=pp.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)),v=n.makeOutput([...x,b,y],r.dtype),I=n.dataIdMap.get(v.dataId).id,T=new Uint8Array(new Int32Array(r.shape).buffer),C=new Uint8Array(new Int32Array(s.shape).buffer);return QA(c,T,r.shape.length,h,C,s.shape.length,l,u,g,m,f,d||0,I),v}var yle={kernelName:oi,backendName:"wasm",setupFunc:gle,kernelFunc:ble};function Xe(e,t){let n;function a(s){n=s.wasm.cwrap(e,null,["number","number","number"])}function r(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,u=i.makeOutput(o.shape,t||o.dtype),p=i.dataIdMap.get(u.dataId).id;return w.sizeFromShape(u.shape)===0||n(l,Qe[o.dtype],p),u}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:r}}var xle=Xe(lu),vle=Xe(Ti),wle=Xe(Ci);function Ht(e,t,n){let a;function r(i){a=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:p}=l,d=o.dataIdMap.get(u.dataId).id,c=o.dataIdMap.get(p.dataId).id,h=n!=null?n:u.dtype,m=N.assertAndGetBroadcastShape(u.shape,p.shape),f=o.makeOutput(m,h);if(w.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(u.shape).buffer),b=new Uint8Array(new Int32Array(p.shape).buffer),y=o.dataIdMap.get(f.dataId).id;return a(d,g,u.shape.length,c,b,p.shape.length,Qe[u.dtype],y),f}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var kle=!0,Ile=Ht(Is,kle),eF;function Sle(e){eF=e.wasm.cwrap(_i,null,["array","number","number","number"])}function Nle(e){let{inputs:t,backend:n}=e,a=n.makeOutput(t[0].shape,t[0].dtype);if(w.sizeFromShape(a.shape)===0)return a;let r=t.map(o=>n.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(r).buffer),i=n.dataIdMap.get(a.dataId).id;return eF(s,r.length,Qe[a.dtype],i),a}var Tle={kernelName:_i,backendName:"wasm",setupFunc:Sle,kernelFunc:Nle};function ag(e){let{inputs:{x:t},backend:n}=e;if(t.dtype==="string")return bn(n.readSync(t.dataId),t.shape,t.dtype);let a=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(a).set(r),a}var Cle={kernelName:to,backendName:"wasm",kernelFunc:ag},tF;function _le(e){tF=e.wasm.cwrap($r,null,["number","array","number","number","number","array","number"])}function ws(e){let{inputs:t,backend:n,attrs:a}=e,[r,s]=Ale(t.x.shape,a.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=Ele(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let m=ag({inputs:t,backend:n});return m.shape=o,m}let u=n.makeOutput(o,l.dtype),p=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(u.dataId).id,c=new Uint8Array(new Int32Array(s).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return tF(p,h,l.shape.length,Qe[l.dtype],d,c,s.length),u}function Ele(e,t){let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];return n}function Ale(e,t){let n=[],a=[];for(let r=0;r<e.length;++r)e[r]!==1&&n.push(e[r]),e[t[r]]!==1&&a.push(t[r]);for(let r=0;r<a.length;++r){let s=-1;for(let i=0;i<a.length;++i)a[i]>=r&&(s===-1||a[s]>a[i])&&(s=i);a[s]=r}return[n,a]}var Fle={kernelName:$r,backendName:"wasm",kernelFunc:ws,setupFunc:_le};function Ps(e,t,n){let a=e.shape,r=e.shape.length,s=w.parseAxisParam(t,a),i=s,o=N.getAxesPermutation(i,r),l=null,u=!1;if(o!=null){let p=new Array(r);for(let c=0;c<p.length;c++)p[c]=a[o[c]];i=N.getInnerMostAxes(i.length,r),l=ws({inputs:{x:e},attrs:{perm:o},backend:n});let d=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(l.dataId).id!==d&&(u=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:u}}var nF;function $le(e){nF=e.wasm.cwrap(uu,null,["number, number, number"])}function Dle(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:c}=Ps(i,r,t);if(c){let y=t.dataIdMap.get(u.dataId).id;l=u,o=y}let h=l.shape.length;N.assertAxesAreInnerMostDims("all",p,h);let[m,f]=N.computeOutAndReduceShapes(l.shape,p),g=w.sizeFromShape(f),b=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let y=t.dataIdMap.get(b.dataId).id;nF(o,g,y)}if(c&&t.disposeData(u.dataId),s){let y=N.expandShapeToKeepDim(b.shape,d);b.shape=y}return b}var Rle={kernelName:uu,backendName:"wasm",setupFunc:$le,kernelFunc:Dle},aF;function Mle(e){aF=e.wasm.cwrap(pu,null,["number, number, number"])}function Ple(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:c}=Ps(i,r,t);if(c){let y=t.dataIdMap.get(u.dataId).id;l=u,o=y}let h=l.shape.length;N.assertAxesAreInnerMostDims("any",p,h);let[m,f]=N.computeOutAndReduceShapes(l.shape,p),g=w.sizeFromShape(f),b=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let y=t.dataIdMap.get(b.dataId).id;aF(o,g,y)}if(c&&t.disposeData(u.dataId),s){let y=N.expandShapeToKeepDim(b.shape,d);b.shape=y}return b}var Ole={kernelName:pu,backendName:"wasm",setupFunc:Mle,kernelFunc:Ple};function rF(e){let t;function n(r){t=r.wasm.cwrap(e,null,["number","number","number","number","number"])}function a(r){let{backend:s,inputs:i,attrs:o}=r,{axis:l}=o,{x:u}=i,p=s.dataIdMap.get(u.dataId).id,d=p,c=u,{transposed:h,axes:m,inputWasTransposed:f}=Ps(u,l,s);if(f){let I=s.dataIdMap.get(h.dataId).id;I!==p&&(c=h,d=I)}let g=c.shape.slice(0,-1),b=s.makeOutput(g,"int32"),y=s.dataIdMap.get(b.dataId).id,x=w.sizeFromShape(b.shape),v=c.shape[m[0]];return t(d,Qe[c.dtype],x,v,y),f&&s.disposeData(h.dataId),b}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var Lle=rF(cu),zle=rF(du),Wle=Xe(Ei),Ble=Xe(Ai),Vle=Xe(Fi),Ule=Ht(Di,!1),Gle=Xe($i),sF;function Hle(e){sF=e.wasm.cwrap(Ri,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function qle(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,p=N.computePool2DInfo(r.shape,i,o,1,l,u),d=p.filterHeight,c=p.filterWidth,h=p.padInfo.top,m=p.padInfo.right,f=p.padInfo.bottom,g=p.padInfo.left,b=p.strideHeight,y=p.strideWidth,x=p.inChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);if(p.dilationWidth!==1||p.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${p.dilationHeight}, ${p.dilationWidth}].`);let v=a.makeOutput(p.outShape,"float32"),I=a.dataIdMap.get(v.dataId).id;return sF(s,r.shape[0],r.shape[1],r.shape[2],d,c,h,m,f,g,b,y,x,I),v}var jle={kernelName:Ri,backendName:"wasm",setupFunc:Hle,kernelFunc:qle},iF;function Kle(e){iF=e.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 Xle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=N.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.makeOutput(p.outShape,r.dtype);return iF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),d}var Yle={kernelName:hu,backendName:"wasm",setupFunc:Kle,kernelFunc:Xle},oF;function Zle(e){oF=e.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 Jle(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=N.computePool3DInfo(s.shape,i,o,1,l,u),d=n.makeOutput(s.shape,s.dtype);return oF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left,p.filterDepth,p.filterHeight,p.filterWidth),d}var Qle={kernelName:Lc,backendName:"wasm",setupFunc:Zle,kernelFunc:Jle},lF;function eue(e){lF=e.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function tue(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l}=a,u=N.computePool2DInfo(s.shape,i,o,1,l),p=n.makeOutput(s.shape,s.dtype);return lF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left,u.filterHeight,u.filterWidth),p}var nue={kernelName:Oc,backendName:"wasm",setupFunc:eue,kernelFunc:tue};function Wn(e){let{inputs:t,attrs:n}=e,{x:a}=t,{shape:r}=n,s=w.sizeFromShape(a.shape),i=w.inferFromImplicitShape(r,s);return w.assert(s===w.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${a.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var aue={kernelName:qu,backendName:"wasm",kernelFunc:Wn},uF;function rue(e){uF=e.wasm.cwrap(Mi,null,["number","array","number","number","array","number","number","number","number"])}function sue(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,u=s.shape.length,p=i?r.shape[l-2]:r.shape[l-1],d=o?s.shape[u-1]:s.shape[u-2],c=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=w.sizeFromShape(m),b=w.sizeFromShape(f),y=pp.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([c,h]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,p,c]:[g,c,p],v=o?[b,h,d]:[b,d,h],I=Wn({inputs:{x:r},backend:n,attrs:{shape:x}}),T=Wn({inputs:{x:s},backend:n,attrs:{shape:v}}),C=n.dataIdMap.get(I.dataId).id,E=n.dataIdMap.get(T.dataId).id,F=i?I.shape[2]:I.shape[1],D=o?T.shape[1]:T.shape[2],$=Math.max(g,b),S=n.makeOutput([$,F,D],I.dtype),M=n.dataIdMap.get(S.dataId).id,B=new Uint8Array(new Int32Array(I.shape).buffer),U=new Uint8Array(new Int32Array(T.shape).buffer);return uF(C,B,I.shape.length,E,U,T.shape.length,i,o,M),n.disposeData(I.dataId),n.disposeData(T.dataId),S.shape=y,S}var iue={kernelName:Mi,backendName:"wasm",setupFunc:rue,kernelFunc:sue};function Si(e){let{inputs:{x:t},attrs:{begin:n,size:a},backend:r}=e,[s,i]=Xt.parseSliceParams(t,n,a),o=Xt.isSliceContinous(t.shape,s,i),l=r.readSync(t.dataId),u=r.makeOutput(i,t.dtype),p=w.computeStrides(t.shape),d=r.dataIdMap.get(u.dataId);if(o){let m=Xt.computeFlatOffset(s,p);return t.dtype==="string"?d.stringBytes=l.slice(m,m+w.sizeFromShape(i)):r.typedArrayFromHeap(u).set(l.subarray(m,m+w.sizeFromShape(i))),u}if(t.dtype==="string"){let m=Nm(l,s,i,t.shape,t.dtype);return d.stringBytes=m,u}let c=r.typedArrayFromHeap(u),h=t.shape.length;if(h===2)oue(l,p[0],c,s,i);else if(h===3)lue(l,p[0],p[1],c,s,i);else if(h===4)uue(l,p[0],p[1],p[2],c,s,i);else{let m=Nm(l,s,i,t.shape,t.dtype);c.set(m)}return u}function oue(e,t,n,a,r){let s=0,i=a[0],o=a[1],l=i+r[0];for(let u=i;u<l;u++){let p=u*t+o;n.set(e.subarray(p,p+r[1]),s),s+=r[1]}}function lue(e,t,n,a,r,s){let i=0,o=r[0],l=r[1],u=r[2],p=o+s[0],d=l+s[1];for(let c=o;c<p;c++)for(let h=l;h<d;h++){let m=c*t+h*n+u;a.set(e.subarray(m,m+s[2]),i),i+=s[2]}}function uue(e,t,n,a,r,s,i){let o=0,l=s[0],u=s[1],p=s[2],d=l+i[0],c=u+i[1],h=p+i[2],m=s[3];for(let f=l;f<d;f++)for(let g=u;g<c;g++)for(let b=p;b<h;b++){let y=f*t+g*n+b*a+m;r.set(e.subarray(y,y+i[3]),o),o+=i[3]}}var pue={kernelName:Qu,backendName:"wasm",kernelFunc:Si};function cue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a,o=s.reduce((b,y)=>b*y),l=N.getReshaped(r.shape,s,o),u=N.getPermuted(l.length,s.length),p=N.getReshapedPermuted(r.shape,s,o),d=N.getSliceBeginCoords(i,s.length),c=N.getSliceSize(p,i,s.length),h=Wn({inputs:{x:r},backend:n,attrs:{shape:l}}),m=ws({inputs:{x:h},backend:n,attrs:{perm:u}}),f=Wn({inputs:{x:m},backend:n,attrs:{shape:p}}),g=Si({inputs:{x:f},backend:n,attrs:{begin:d,size:c}});return n.disposeData(h.dataId),n.disposeData(m.dataId),n.disposeData(h.dataId),g}var due={kernelName:mu,backendName:"wasm",kernelFunc:cue},pF;function hue(e){pF=e.wasm.cwrap(fu,null,["number","number","boolean","number","number","number"])}function mue(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,weights:s}=n,{size:i}=a,o=s.shape.reduce((d,c)=>d*c,1)!==0,l=r.shape.length===1?[i]:[r.shape[0],i],u=t.makeOutput(l,s.dtype);function p(d){return t.dataIdMap.get(d.dataId).id}return pF(p(r),i,o,p(s),Qe[s.dtype],p(u)),u}var fue={kernelName:fu,backendName:"wasm",setupFunc:hue,kernelFunc:mue},gue=!0,bue=Ht(gu,gue);function yue(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.typedArrayFromHeap(a),i=n.typedArrayFromHeap(r),o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeOutput([o.length],"int32",void 0,new Int32Array(o))}var xue={kernelName:zc,backendName:"wasm",kernelFunc:yue};function Os(e){let{inputs:{x:t},attrs:{dtype:n},backend:a}=e,r=a.makeOutput(t.shape,n),s=a.typedArrayFromHeap(t);return a.typedArrayFromHeap(r).set(s),r}var vue={kernelName:Pi,backendName:"wasm",kernelFunc:Os},wue=Xe(Oi),cF;function kue(e){cF=e.wasm.cwrap(Ss,null,["number","number","number","number"])}function Iue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(l.dataId).id;return cF(o,s,i,u),l}var Sue={kernelName:Ss,backendName:"wasm",setupFunc:kue,kernelFunc:Iue};function dF(e){let{inputs:t,backend:n}=e,a=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=t.map(h=>h.shape);N.assertParamsConsistent(r,a);let s=N.computeOutShape(t.map(h=>h.shape),a),i=t.filter(h=>w.sizeFromShape(h.shape)>0);if(i.length===1)return ag({inputs:{x:i[0]},backend:n});let o=n.makeOutput(s,t[0].dtype);if(w.sizeFromShape(s)===0)return o;if(i[0].dtype==="string"){let h=i.map(x=>{let v=[-1,w.sizeFromShape(x.shape.slice(a))];return Wn({inputs:{x},backend:n,attrs:{shape:v}})}),m=h.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));s=N.computeOutShape(h.map(x=>x.shape),1);let f=h[0].shape[0]===1,g=z1(m,s,t[0].dtype,f),b=N.computeOutShape(i.map(x=>x.shape),a);o.shape=b;let y=n.dataIdMap.get(o.dataId);return y.stringBytes=N.fromStringArrayToUint8(g),h.forEach(x=>n.disposeData(x.dataId)),o}let l=w.sizeFromShape(i[0].shape.slice(0,a)),u=0,p=i.map(h=>{let m=w.sizeFromShape(h.shape.slice(a));return u+=m,m}),d=i.map(h=>n.typedArrayFromHeap(h)),c=n.typedArrayFromHeap(o);for(let h=0;h<l;h++){let m=h*u;for(let f=0;f<d.length;f++){let g=p[f],b=h*g,y=d[f].subarray(b,b+g);c.set(y,m),m+=g}}return o}var Nue={kernelName:bu,backendName:"wasm",kernelFunc:dF},hF;function Tue(e){hF=e.wasm.cwrap(Li,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Cue(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:d,dataFormat:c}=n,h=N.convertConv2DDataFormat(c),m=N.computeConv2DInfo(r.shape,s.shape,l,u,p,d,!1,h),f=m.filterHeight,g=m.filterWidth,b=m.padInfo.top,y=m.padInfo.right,x=m.padInfo.bottom,v=m.padInfo.left,I=m.dilationHeight,T=m.dilationWidth,C=m.strideHeight,E=m.strideWidth,F=m.inChannels,D=m.outChannels,$=m.padInfo.type==="SAME"?1:0;if(m.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);let S=a.makeOutput(m.outShape,"float32"),M=a.dataIdMap.get(S.dataId).id;return hF(i,r.shape[0],r.shape[1],r.shape[2],o,f,g,b,y,x,v,$,I,T,C,E,F,D,M),S}var _ue={kernelName:Li,backendName:"wasm",setupFunc:Tue,kernelFunc:Cue},mF;function Eue(e){mF=e.wasm.cwrap(zi,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 Aue(e){let{backend:t,inputs:n,attrs:a}=e,{dy:r,filter:s}=n,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,inputShape:p}=a,d=1,c=N.convertConv2DDataFormat(l),h=N.computeConv2DInfo(p,s.shape,i,d,o,u,!1,c),{batchSize:m,filterHeight:f,filterWidth:g,inChannels:b,inHeight:y,inWidth:x,outChannels:v,outHeight:I,outWidth:T,strideHeight:C,strideWidth:E}=h,F=f-1-h.padInfo.top,D=g-1-h.padInfo.left,$=h.dataFormat==="channelsLast",S=w.computeStrides(h.inShape),M=w.computeStrides(r.shape),[B,U,H]=w.computeStrides(s.shape),j=S[0],K=$?S[1]:S[2],Z=$?S[2]:1,J=$?1:S[1],ee=M[0],ae=$?M[1]:M[2],te=$?M[2]:1,re=$?1:M[1],ie=t.makeOutput(h.inShape,"float32"),ye=t.dataIdMap.get(ie.dataId).id,ue=t.dataIdMap.get(r.dataId).id,be=t.dataIdMap.get(s.dataId).id;return mF(ue,be,m,f,g,y,x,b,I,T,v,C,E,F,D,B,U,H,j,K,Z,J,ee,ae,te,re,ye),ie}var Fue={kernelName:zi,backendName:"wasm",setupFunc:Eue,kernelFunc:Aue},fF;function $ue(e){fF=e.wasm.cwrap(Wi,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 Due(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;if(r.dtype!=="float32")throw new Error(`Tensor x must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=N.computeConv3DInfo(r.shape,s.shape,i,l,o),p=n.makeOutput(u.outShape,r.dtype);return fF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),p}var Rue={kernelName:Wi,backendName:"wasm",setupFunc:$ue,kernelFunc:Due},gF;function Mue(e){gF=e.wasm.cwrap(yu,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 Pue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;if(r.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=N.computeConv3DInfo(r.shape,l,i,1,o),p=n.makeOutput(u.filterShape,s.dtype);return gF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),p}var Oue={kernelName:yu,backendName:"wasm",setupFunc:Mue,kernelFunc:Pue},bF;function Lue(e){bF=e.wasm.cwrap(xu,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 zue(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;if(r.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=N.computeConv3DInfo(l,s.shape,o,1,i),p=n.makeOutput(u.inShape,r.dtype);return bF(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),p}var Wue={kernelName:xu,backendName:"wasm",setupFunc:Lue,kernelFunc:zue},Bue=Xe(Bi),Vue=Xe(Vi),xv;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(xv||(xv={}));var yF;function Uue(e){yF=e.wasm.cwrap(wu,null,["number","number","number","number","array","number","number","number","number","number"])}function Gue(e){let{backend:t,inputs:n,attrs:a}=e,{method:r,extrapolationValue:s,cropSize:i}=a,{image:o,boxes:l,boxInd:u}=n,p=l.shape[0],[d,c]=i,h=[p,d,c,o.shape[3]],m=t.dataIdMap.get(o.dataId),f;o.dtype!=="float32"&&(f=Os({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));let g=m.id,b=t.dataIdMap.get(l.dataId).id,y=t.dataIdMap.get(u.dataId).id,x=t.makeOutput(h,"float32"),v=t.dataIdMap.get(x.dataId).id,I=new Uint8Array(new Int32Array(o.shape).buffer);return yF(g,b,y,p,I,d,c,xv[r],s,v),f!=null&&t.disposeData(f.dataId),x}var Hue={kernelName:wu,backendName:"wasm",setupFunc:Uue,kernelFunc:Gue},xF;function que(e){xF=e.wasm.cwrap(vu,null,["number","number","number","number","number","number"])}function jue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length;w.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumprod does not support ${r.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),p=r;u!==null&&(p=ws({inputs:{x:r},attrs:{perm:u},backend:n}));let d=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumprod",[d],l);let c=n.makeOutput(p.shape,p.dtype),h=p.shape[d],m=n.dataIdMap.get(p.dataId).id,f=n.dataIdMap.get(c.dataId).id;xF(m,i?1:0,o?1:0,h,f,Qe[r.dtype]);let g=c;if(u!==null){let b=N.getUndoAxesPermutation(u);g=ws({inputs:{x:c},attrs:{perm:b},backend:n}),n.disposeData(p.dataId),n.disposeData(c.dataId)}return g}var Kue={kernelName:vu,backendName:"wasm",setupFunc:que,kernelFunc:jue},vF;function Xue(e){vF=e.wasm.cwrap(Ui,null,["number","number","number","number","number","number"])}function Yue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length;w.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumsum does not support ${r.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),p=r;u!==null&&(p=ws({inputs:{x:r},attrs:{perm:u},backend:n}));let d=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumsum",[d],l);let c=n.makeOutput(p.shape,p.dtype),h=p.shape[d],m=n.dataIdMap.get(p.dataId).id,f=n.dataIdMap.get(c.dataId).id;vF(m,i?1:0,o?1:0,h,f,Qe[r.dtype]);let g=c;if(u!==null){let b=N.getUndoAxesPermutation(u);g=ws({inputs:{x:c},attrs:{perm:b},backend:n}),n.disposeData(p.dataId),n.disposeData(c.dataId)}return g}var Zue={kernelName:Ui,backendName:"wasm",setupFunc:Xue,kernelFunc:Yue},wF;function Jue(e){wF=e.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])}function Que(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,weights:s}=n,{size:i,binaryOutput:o}=a,l=s.shape.reduce((c,h)=>c*h,1)!==0,u=r.shape.length===1?[i]:[r.shape[0],i],p=t.makeOutput(u,s.dtype);function d(c){return t.dataIdMap.get(c.dataId).id}return wF(d(r),new Uint8Array(new Int32Array(r.shape).buffer),r.shape.length,i,l,d(s),Qe[s.dtype],o,d(p)),p}var epe={kernelName:Bc,backendName:"wasm",setupFunc:Jue,kernelFunc:Que},kF;function tpe(e){kF=e.wasm.cwrap(ku,null,["number","number","number","array","number","array","array","number","number"])}function npe(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{blockSize:s,dataFormat:i}=a,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],d=l*s,c=u*s,h=p/(s*s),m=i==="NHWC"?[o,d,c,h]:[o,h,d,c],f=t.makeOutput(m,"float32"),g=t.dataIdMap.get(r.dataId).id,b=new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer),y=new Uint8Array(new Int32Array(m).buffer),x=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer),v=t.dataIdMap.get(f.dataId).id;return kF(g,s,i==="NHWC"?1:0,b,r.shape.length-1,y,x,m.length,v),f}var ape={kernelName:ku,backendName:"wasm",setupFunc:tpe,kernelFunc:npe},IF;function rpe(e){IF=e.wasm.cwrap(Gi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function spe(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:d}=n,c=u==null?[1,1]:u,h=N.computeConv2DInfo(r.shape,s.shape,l,c,p,d,!0),m=h.filterHeight,f=h.filterWidth,g=h.padInfo.top,b=h.padInfo.right,y=h.padInfo.bottom,x=h.padInfo.left,v=h.dilationHeight,I=h.dilationWidth,T=h.strideHeight,C=h.strideWidth,E=h.inChannels,F=h.outChannels,D=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let $=a.makeOutput(h.outShape,"float32"),S=a.dataIdMap.get($.dataId).id;return IF(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,b,y,x,D,v,I,T,C,E,F,S),$}var ipe={kernelName:Gi,backendName:"wasm",setupFunc:rpe,kernelFunc:spe},SF;function ope(e){SF=e.wasm.cwrap("Diag",null,["number","number","number","number"])}function lpe(e){let{inputs:t,backend:n}=e,{x:a}=t,r=w.sizeFromShape(a.shape),s=n.makeOutput([...a.shape,...a.shape],a.dtype);return SF(n.dataIdMap.get(a.dataId).id,Qe[a.dtype],r,n.dataIdMap.get(s.dataId).id),s}var upe={kernelName:Vc,backendName:"wasm",setupFunc:ope,kernelFunc:lpe},NF;function ppe(e){NF=e.wasm.cwrap(Hi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function cpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;if(r.dtype!==s.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${r.dtype} and ${s.dtype}`);let u=N.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),p=n.makeOutput(u.outShape,r.dtype);return NF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(p.dataId).id,Qe[r.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),p}var dpe={kernelName:Hi,backendName:"wasm",setupFunc:ppe,kernelFunc:cpe},TF;function hpe(e){TF=e.wasm.cwrap(Ul,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function mpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=a;if(r.dtype!==s.dtype||r.dtype!==i.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${r.dtype}, ${s.dtype}, and ${i.dtype}`);let p=N.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),d=n.makeOutput(s.shape,s.dtype);return TF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,Qe[r.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),d}var fpe={kernelName:Ul,backendName:"wasm",setupFunc:hpe,kernelFunc:mpe},CF;function gpe(e){CF=e.wasm.cwrap(Vl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function bpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=a;if(r.dtype!==s.dtype||r.dtype!==i.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${r.dtype}, ${s.dtype}, and ${i.dtype}`);let p=N.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),d=n.makeOutput(r.shape,r.dtype);return CF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,Qe[r.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),d}var ype={kernelName:Vl,backendName:"wasm",setupFunc:gpe,kernelFunc:bpe},xpe=Xe(ji),_F;function vpe(e){_F=e.wasm.cwrap(Iu,null,["number","number","number"])}function wpe(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=n.makeOutput(r.shape,"float32"),i=o=>n.dataIdMap.get(o.dataId).id;return _F(i(r),i(a),i(s)),s}var kpe={kernelName:Iu,backendName:"wasm",setupFunc:vpe,kernelFunc:wpe},Ipe=!1,Spe=Ht(Su,Ipe,"bool"),Npe=Xe(Ki),Tpe=Xe(Xi,"float32");function vv(e){let{inputs:t,attrs:n,backend:a}=e,{input:r}=t,{dim:s}=n,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),Wn({inputs:{x:r},backend:a,attrs:{shape:o}})}var Cpe={kernelName:Nu,backendName:"wasm",kernelFunc:vv},_pe=Xe(Yi,"float32");function EF(e){let{attrs:{shape:t,value:n,dtype:a},backend:r}=e,s=r.makeOutput(t,a);return r.typedArrayFromHeap(s).fill(n),s}var Epe={kernelName:Uc,backendName:"wasm",kernelFunc:EF},AF;function Ape(e){AF=e.wasm.cwrap(Tu,null,["number","number","number","number","number","number"])}function Fpe(e){let{inputs:t,backend:n}=e,{image:a}=t,r=n.makeOutput(a.shape,a.dtype),s=n.dataIdMap.get(a.dataId).id,i=n.dataIdMap.get(r.dataId).id,[o,l,u,p]=a.shape;return AF(s,o,l,u,p,i),r}var $pe={kernelName:Tu,backendName:"wasm",kernelFunc:Fpe,setupFunc:Ape},Dpe=Xe(Zi),Rpe=!1,Mpe=Ht(Ji,Rpe),FF;function Ppe(e){FF=e.wasm.cwrap(Qi,null,["number","number","number","number","number","number","number"])}function Ope(e){let{backend:t,inputs:n,attrs:a}=e,{varianceEpsilon:r}=a,{x:s,mean:i,variance:o,offset:l,scale:u}=n,p=t.dataIdMap.get(s.dataId).id,d=t.dataIdMap.get(i.dataId).id,c=t.dataIdMap.get(o.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,m=u!=null?t.dataIdMap.get(u.dataId).id:0,f=t.makeOutput(s.shape,s.dtype);if(w.sizeFromShape(s.shape)===0)return f;let g=t.dataIdMap.get(f.dataId).id;return FF(p,d,c,h,m,r,g),f}var Lpe={kernelName:Qi,backendName:"wasm",setupFunc:Ppe,kernelFunc:Ope},$F;function zpe(e){$F=e.wasm.cwrap(li,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 Wpe(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dataFormat:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=n,f=N.computeConv2DInfo(r.shape,s.shape,l,p,u,c),g=Rc[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let b=a.dataIdMap.get(r.dataId).id,y=a.dataIdMap.get(s.dataId).id,x=f.outChannels,v=0;if(i!=null){let te=a.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let I=f.filterHeight,T=f.filterWidth,C=f.padInfo.top,E=f.padInfo.right,F=f.padInfo.bottom,D=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,M=f.strideHeight,B=f.strideWidth,U=f.inChannels,H=f.padInfo.type==="SAME"?1:0,j=f.batchSize,K=f.inHeight,Z=f.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let J=a.makeOutput(f.outShape,"float32"),ee=a.dataIdMap.get(J.dataId).id,ae=o==null?0:a.dataIdMap.get(o.dataId).id;return $F(b,j,K,Z,y,I,T,v,C,E,F,D,H,$,S,M,B,U,x,g,ae,m||0,ee),J}var Bpe={kernelName:li,backendName:"wasm",setupFunc:zpe,kernelFunc:Wpe},DF;function Vpe(e){DF=e.wasm.cwrap(ui,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 Upe(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dataFormat:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=n,f=N.computeConv2DInfo(r.shape,s.shape,l,p,u,c,!0),g=Rc[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let b=a.dataIdMap.get(r.dataId).id,y=a.dataIdMap.get(s.dataId).id,x=f.outChannels,v=0;if(i!=null){let te=a.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let I=f.filterHeight,T=f.filterWidth,C=f.padInfo.top,E=f.padInfo.right,F=f.padInfo.bottom,D=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,M=f.strideHeight,B=f.strideWidth,U=f.inChannels,H=f.padInfo.type==="SAME"?1:0,j=f.batchSize,K=f.inHeight,Z=f.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let J=a.makeOutput(f.outShape,"float32"),ee=a.dataIdMap.get(J.dataId).id,ae=o==null?0:a.dataIdMap.get(o.dataId).id;return DF(b,j,K,Z,y,I,T,v,C,E,F,D,H,$,S,M,B,U,x,g,ae,m||0,ee),J}var Gpe={kernelName:ui,backendName:"wasm",setupFunc:Vpe,kernelFunc:Upe},RF;function Hpe(e){RF=e.wasm.cwrap(_u,null,["number","number","number","number","number","number","array","number"])}function qpe(e){let{backend:t,inputs:n}=e,{params:a,indices:r}=n,[s,i,o,l]=Jw.prepareAndValidate(a,r),u=t.makeOutput(s,a.dtype);if(i===0)return u;let p=r.shape,d=p[p.length-1],c=t.dataIdMap.get(a.dataId).id,h=t.dataIdMap.get(r.dataId).id,m=new Uint8Array(new Int32Array(l).buffer),f=t.dataIdMap.get(u.dataId).id;return RF(c,Qe[a.dtype],h,i,d,o,m,f),u}var jpe={kernelName:_u,backendName:"wasm",setupFunc:Hpe,kernelFunc:qpe},MF;function Kpe(e){MF=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Xpe(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,indices:s}=n,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0],u=t.readSync(s.dataId),p=r.shape[l];for(let C=0;C<u.length;++C){let E=u[C];w.assert(E<=p-1&&E>=0,()=>`GatherV2: the index value ${E} is not in [0, ${p-1}]`)}let d=N.segment_util.collectGatherOpShapeInfo(r,s,l,o),c=Wn({inputs:{x:r},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),h=w.sizeFromShape(s.shape),m=Wn({inputs:{x:s},attrs:{shape:[d.batchSize,h/d.batchSize]},backend:t}),f=[d.batchSize,d.outerSize,h/d.batchSize,d.sliceSize],g=t.makeOutput(f,r.dtype);if(w.sizeFromShape(r.shape)===0)return g;let b=c.shape.length-1,y=t.dataIdMap.get(c.dataId).id,x=t.dataIdMap.get(m.dataId).id,v=t.dataIdMap.get(g.dataId).id,I=new Uint8Array(new Int32Array(w.computeStrides(c.shape)).buffer),T=new Uint8Array(new Int32Array(w.computeStrides(f)).buffer);return MF(y,Qe[r.dtype],I,b,x,d.batchSize,T,v),t.disposeData(c.dataId),t.disposeData(m.dataId),g.shape=d.outputShape,g}var Ype={kernelName:Cu,backendName:"wasm",setupFunc:Kpe,kernelFunc:Xpe},Zpe=!1,Jpe=Ht(Eu,Zpe,"bool"),Qpe=!1,ece=Ht(eo,Qpe,"bool"),tce=Xe(no,"bool"),nce=Xe(ao,"bool"),ace=Xe(ro,"bool"),PF;function rce(e){PF=e.wasm.cwrap(so,null,["number","number","number","number"])}function sce(e){let{inputs:{x:t},attrs:{alpha:n},backend:a}=e,r=a.dataIdMap.get(t.dataId).id,s=a.makeOutput(t.shape,"float32");if(w.sizeFromShape(t.shape)!==0){let i=a.dataIdMap.get(s.dataId).id;PF(r,Qe[t.dtype],n,i)}return s}var ice={kernelName:so,backendName:"wasm",setupFunc:rce,kernelFunc:sce},oce=!1,lce=Ht(Au,oce,"bool"),uce=!1,pce=Ht(Fu,uce,"bool"),OF;function cce(e){OF=e.wasm.cwrap($u,null,["number","number","number","number"])}function dce(e){let{attrs:t,backend:n}=e,{start:a,stop:r,num:s}=t,i=Math.floor(s),o=n.makeOutput([i],"float32");return OF(n.dataIdMap.get(o.dataId).id,a,r,i),o}var hce={kernelName:$u,backendName:"wasm",setupFunc:cce,kernelFunc:dce},mce=Xe(io),fce=Xe(oo),gce=!1,bce=Ht(Du,gce,"bool"),yce=Xe(Ru),xce=!1,vce=Ht(Mu,xce,"bool"),wce=!1,kce=Ht(rN,wce,"bool"),LF;function Ice(e){LF=e.wasm.cwrap(lo,null,["number","number","number","number","number","number","number"])}function Sce(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;if(r.dtype!=="float32")throw new Error("LRN error: x must have dtype float32");let u=n.makeOutput(r.shape,r.dtype);return LF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(u.dataId).id,r.shape[3],s,i,o,l),u}var Nce={kernelName:lo,backendName:"wasm",setupFunc:Ice,kernelFunc:Sce},zF;function Tce(e){zF=e.wasm.cwrap(Pu,null,["number","number","number","number","number","number","number","number","number"])}function Cce(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a;if(r.dtype!=="float32"||s.dtype!=="float32"||i.dtype!=="float32")throw new Error("LRNGrad error: x, y, and dy must have dtype float32");let d=n.makeOutput(r.shape,r.dtype);return zF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,i.shape[3],o,l,u,p),d}var _ce={kernelName:Pu,backendName:"wasm",setupFunc:Tce,kernelFunc:Cce},WF;function Ece(e){WF=e.wasm.cwrap(uo,null,["number","number","number","number"])}function Ace(e){let{backend:t,inputs:n,attrs:a}=e,{reductionIndices:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:c}=Ps(i,r,t);if(c){let y=t.dataIdMap.get(u.dataId).id;l=u,o=y}let h=l.shape.length;N.assertAxesAreInnerMostDims("max",p,h);let[m,f]=N.computeOutAndReduceShapes(l.shape,p),g=w.sizeFromShape(f),b=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let y=t.dataIdMap.get(b.dataId).id;WF(o,Qe[i.dtype],g,y)}if(c&&t.disposeData(u.dataId),s){let y=N.expandShapeToKeepDim(b.shape,d);b.shape=y}return b}var Fce={kernelName:uo,backendName:"wasm",setupFunc:Ece,kernelFunc:Ace},$ce=!1,Dce=Ht(po,$ce),BF;function Rce(e){BF=e.wasm.cwrap(co,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Mce(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id;w.assert(r.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,p=N.computePool2DInfo(r.shape,i,o,1,l,u),d=p.filterHeight,c=p.filterWidth,h=p.padInfo.top,m=p.padInfo.right,f=p.padInfo.bottom,g=p.padInfo.left,b=p.dilationHeight,y=p.dilationWidth,x=p.strideHeight,v=p.strideWidth,I=p.inChannels,T=p.outChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);let C=a.makeOutput(p.outShape,"float32"),E=a.dataIdMap.get(C.dataId).id;return BF(s,r.shape[0],r.shape[1],r.shape[2],d,c,h,m,f,g,b,y,x,v,I,T,E),C}var Pce={kernelName:co,backendName:"wasm",setupFunc:Rce,kernelFunc:Mce},VF;function Oce(e){VF=e.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 Lce(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=N.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.makeOutput(p.outShape,r.dtype);return VF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),d}var zce={kernelName:Ou,backendName:"wasm",setupFunc:Oce,kernelFunc:Lce},UF;function Wce(e){UF=e.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 Bce(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=N.computePool3DInfo(s.shape,i,o,1,l,u),d=n.makeOutput(s.shape,s.dtype);return UF(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),d}var Vce={kernelName:Hc,backendName:"wasm",setupFunc:Wce,kernelFunc:Bce},GF;function Uce(e){GF=e.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Gce(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=N.computePool2DInfo(s.shape,i,o,1,l,u),d=n.makeOutput(s.shape,s.dtype);return GF(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.top,p.padInfo.left),d}var Hce={kernelName:Gc,backendName:"wasm",setupFunc:Uce,kernelFunc:Gce},HF;function qce(e){HF=e.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function jce(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,includeBatchInIndex:l}=a;w.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let u=[1,1];w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=N.computePool2DInfo(r.shape,s,i,[1,1],o),d=n.makeOutput(p.outShape,r.dtype),c=n.makeOutput(p.outShape,"int32");return HF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,n.dataIdMap.get(c.dataId).id,Qe[r.dtype],l,p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.top,p.padInfo.left),[d,c]}var Kce={kernelName:qc,backendName:"wasm",setupFunc:qce,kernelFunc:jce},qF;function Xce(e){qF=e.wasm.cwrap(ho,null,["number, number, number"])}function Yce(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=Ps(i,r,t),m=d;if(h){let v=t.dataIdMap.get(p.dataId).id;v!==o&&(u=p,l=v,m=N.getInnerMostAxes(m.length,u.shape.length))}N.assertAxesAreInnerMostDims("mean",m,u.shape.length);let[f,g]=N.computeOutAndReduceShapes(u.shape,m),b=w.sizeFromShape(g),y=u;u.dtype!=="float32"&&(y=Os({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(y.dataId).id);let x=t.makeOutput(f,"float32");if(w.sizeFromShape(u.shape)!==0){let v=t.dataIdMap.get(x.dataId).id;qF(l,b,v)}if(h&&t.disposeData(p.dataId),s){let v=N.expandShapeToKeepDim(x.shape,c);x.shape=v}return u.dtype!=="float32"&&t.disposeData(y.dataId),x}var Zce={kernelName:ho,backendName:"wasm",setupFunc:Xce,kernelFunc:Yce},jF;function Jce(e){jF=e.wasm.cwrap(mo,null,["number","number","number","number"])}function Qce(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=Ps(i,r,t);if(h){let x=t.dataIdMap.get(p.dataId).id;x!==o&&(u=p,l=x)}let m=u.shape.length;N.assertAxesAreInnerMostDims("min",d,m);let[f,g]=N.computeOutAndReduceShapes(u.shape,d),b=w.sizeFromShape(g),y=t.makeOutput(f,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;jF(l,Qe[i.dtype],b,x)}if(h&&t.disposeData(p.dataId),s){let x=N.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var ede={kernelName:mo,backendName:"wasm",setupFunc:Jce,kernelFunc:Qce},tde=!1,nde=Ht(fo,tde),wv;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(wv||(wv={}));var KF;function ade(e){KF=e.wasm.cwrap(go,null,["number","array","number","number","array","array","number","number"])}function rde(e){let{inputs:{x:t},backend:n,attrs:{paddings:a,mode:r}}=e,s=a.map((m,f)=>m[0]+t.shape[f]+m[1]),i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(s,t.dtype),l=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),p=a.map(m=>m[0]),d=a.map(m=>m[1]),c=new Uint8Array(new Int32Array(p).buffer),h=new Uint8Array(new Int32Array(d).buffer);return KF(i,u,t.shape.length,Qe[t.dtype],c,h,wv[r],l),o}var sde={kernelName:go,backendName:"wasm",kernelFunc:rde,setupFunc:ade},XF;function ide(e){XF=e.wasm.cwrap(Wo,null,["number","number","number","number"])}function YF(e){let{backend:t,inputs:{logits:n},attrs:{dim:a}}=e,r=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),i=t.dataIdMap.get(s.dataId).id,o=n.shape[a],l=w.sizeFromShape(n.shape)/o;return w.sizeFromShape(s.shape)===0||XF(r,i,o,l),s}var ode={kernelName:Wo,backendName:"wasm",setupFunc:ide,kernelFunc:YF},ZF;function lde(e){ZF=e.wasm.cwrap(Lu,null,["number","number","number","number","number","number"])}function ude(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;if(r.dtype!=="float32")throw new Error(`Tensor logits must have dtype float32, got ${r.dtype}`);let l=o?r:YF({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),[u,p]=l.shape,d=n.makeOutput([u,s],"int32");return ZF(n.dataIdMap.get(l.dataId).id,u,p,s,i,n.dataIdMap.get(d.dataId).id),o||n.disposeData(l.dataId),d}var pde={kernelName:Lu,backendName:"wasm",setupFunc:lde,kernelFunc:ude},cde=Ht(bo,!0),dde=!0,hde=Ht(yo,dde),mde=Xe(zu);function hk(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),a=n[0],r=n[1],s=n[2],i=n[3];return e.wasm._free(t),{pSelectedIndices:a,selectedSize:r,pSelectedScores:s,pValidOutputs:i}}var JF;function fde(e){JF=e.wasm.cwrap(Bu,"number",["number","number","number","number","number"])}function gde(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i}=a,{boxes:o,scores:l}=n,u=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(l.dataId).id,d=JF(u,p,s,r,i),{pSelectedIndices:c,selectedSize:h,pSelectedScores:m,pValidOutputs:f}=hk(t,d);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([h],"int32",c)}var bde={kernelName:Bu,backendName:"wasm",setupFunc:fde,kernelFunc:gde},QF;function yde(e){QF=e.wasm.cwrap(Vu,"number",["number","number","number","number","number","bool"])}function xde(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=a,{boxes:l,scores:u}=n,p=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(u.dataId).id,c=QF(p,d,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=hk(t,c);t.wasm._free(f);let b=t.makeOutput([m],"int32",h),y=t.makeOutput([],"int32",g);return[b,y]}var vde={kernelName:Vu,backendName:"wasm",setupFunc:yde,kernelFunc:xde},e$;function wde(e){e$=e.wasm.cwrap(Uu,"number",["number","number","number","number","number","number"])}function kde(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=a,{boxes:l,scores:u}=n,p=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(u.dataId).id,c=e$(p,d,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=hk(t,c);t.wasm._free(g);let b=t.makeOutput([m],"int32",h),y=t.makeOutput([m],"float32",f);return[b,y]}var Ide={kernelName:Uu,backendName:"wasm",setupFunc:wde,kernelFunc:kde},Sde=!1,Nde=Ht(Wu,Sde,"bool"),t$;function Tde(e){t$=e.wasm.cwrap(xo,null,["number","number","number","number","number"])}function Cde(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=a,u=n.makeOutput([...r.shape,i],s),p=n.dataIdMap.get(u.dataId).id,d=n.dataIdMap.get(r.dataId).id;return t$(d,i,o,l,p),u}var _de={kernelName:xo,backendName:"wasm",setupFunc:Tde,kernelFunc:Cde};function Ede(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(1),a}var Ade={kernelName:Gu,backendName:"wasm",kernelFunc:Ede};function Fde(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return vv({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=vv({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=dF({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeData(p.dataId)),u}var $de={kernelName:Hu,backendName:"wasm",kernelFunc:Fde},n$;function Dde(e){n$=e.wasm.cwrap(vo,null,["number","array","number","number","array","array","number","number"])}function Rde(e){let{inputs:{x:t},backend:n,attrs:{paddings:a,constantValue:r}}=e,s=a.map((m,f)=>m[0]+t.shape[f]+m[1]);if(w.sizeFromShape(t.shape)===0)return EF({backend:n,attrs:{shape:s,value:r,dtype:t.dtype}});let i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(s,t.dtype),l=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),p=a.map(m=>m[0]),d=a.map(m=>m[1]),c=new Uint8Array(new Int32Array(p).buffer),h=new Uint8Array(new Int32Array(d).buffer);return n$(i,u,t.shape.length,Qe[t.dtype],c,h,r,l),o}var a$={kernelName:vo,backendName:"wasm",kernelFunc:Rde,setupFunc:Dde},Mde=!1,Pde=Ht(wo,Mde),r$;function Ode(e){r$=e.wasm.cwrap(ko,null,["number","number","number"])}function Lde(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=n.dataIdMap.get(a.dataId).id,i=n.dataIdMap.get(r.dataId).id,o=s,l=a,u=l;l.dtype!=="float32"&&(u=Os({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),o=n.dataIdMap.get(u.dataId).id);let p=n.makeOutput(a.shape,"float32"),d=n.dataIdMap.get(p.dataId).id;return r$(o,i,d),l.dtype!=="float32"&&n.disposeData(u.dataId),p}var zde={kernelName:ko,backendName:"wasm",setupFunc:Ode,kernelFunc:Lde},s$;function Wde(e){s$=e.wasm.cwrap(Io,null,["number","number","number","number"])}function Bde(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=Ps(i,r,t),m=d;if(h){let x=t.dataIdMap.get(p.dataId).id;x!==o&&(u=p,l=x,m=N.getInnerMostAxes(m.length,u.shape.length))}N.assertAxesAreInnerMostDims("prod",m,u.shape.length);let[f,g]=N.computeOutAndReduceShapes(u.shape,m),b=w.sizeFromShape(g),y=t.makeOutput(f,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;s$(l,b,Qe[y.dtype],x)}if(h&&t.disposeData(p.dataId),s){let x=N.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var Vde={kernelName:Io,backendName:"wasm",setupFunc:Wde,kernelFunc:Bde},Ude=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=V1(a,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},Gde={kernelName:jc,backendName:"wasm",kernelFunc:Ude},Hde=!0,qde=Ht(qi,Hde),jde=Xe(So),Kde=Xe(No),Xde=Xe(_o),i$;function Yde(e){i$=e.wasm.cwrap(Co,null,["number","number","number","number","number","number","number","number","number","number"])}function Zde(e){let{backend:t,inputs:n,attrs:a}=e,{images:r}=n,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,[p,d,c,h]=r.shape,m=[p,l,u,h],f=t.dataIdMap.get(r.dataId),g;f.dtype!=="float32"&&(g=Os({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let b=f.id,y=t.makeOutput(m,"float32");if(w.sizeFromShape(r.shape)===0)return y;let x=t.dataIdMap.get(y.dataId).id;return i$(b,p,d,c,h,l,u,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),y}var Jde={kernelName:Co,backendName:"wasm",setupFunc:Yde,kernelFunc:Zde},o$;function Qde(e){o$=e.wasm.cwrap(Ku,null,["number","number","number","array","array","boolean"])}function ehe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=n.makeOutput(r.shape,"float32"),l=n.dataIdMap.get(r.dataId),u;return l.dtype!=="float32"&&(u=Os({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),o$(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(r.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),u!=null&&n.disposeData(u.dataId),o}var the={kernelName:Ku,backendName:"wasm",setupFunc:Qde,kernelFunc:ehe},l$;function nhe(e){l$=e.wasm.cwrap(To,null,["number","number","number","number","number","number","number","number","number","number"])}function ahe(e){let{backend:t,inputs:n,attrs:a}=e,{images:r}=n,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,[p,d,c,h]=r.shape,m=[p,l,u,h],f=t.makeOutput(m,"float32");if(w.sizeFromShape(r.shape)===0)return f;let g=t.dataIdMap.get(r.dataId),b;g.dtype!=="float32"&&(b=Os({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(b.dataId));let y=g.id,x=t.dataIdMap.get(f.dataId).id;return l$(y,p,d,c,h,l,u,s?1:0,i?1:0,x),b!=null&&t.disposeData(b.dataId),f}var rhe={kernelName:To,backendName:"wasm",setupFunc:nhe,kernelFunc:ahe},u$;function she(e){u$=e.wasm.cwrap(ju,null,["number","number","number","array","array","boolean"])}function ihe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=n.makeOutput(r.shape,"float32"),l=n.dataIdMap.get(r.dataId),u;return l.dtype!=="float32"&&(u=Os({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),u$(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(r.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),u!=null&&n.disposeData(u.dataId),o}var ohe={kernelName:ju,backendName:"wasm",setupFunc:she,kernelFunc:ihe},p$;function lhe(e){p$=e.wasm.cwrap(Eo,null,["number","array","number","array","number","number"])}function uhe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=w.parseAxisParam(s,r.shape);if(r.shape.length===0)return ag({inputs:{x:r},backend:n});let o=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(o.dataId).id,p=new Uint8Array(new Int32Array(i).buffer),d=new Uint8Array(new Int32Array(r.shape).buffer);p$(l,p,i.length,d,r.shape.length,u);let c=Wn({inputs:{x:o},attrs:{shape:r.shape},backend:n});return n.disposeData(o.dataId),c}var phe={kernelName:Eo,backendName:"wasm",kernelFunc:uhe,setupFunc:lhe},c$;function che(e){c$=e.wasm.cwrap(up,null,["number","number","number","number","number","number","number","number","array","number","number"])}function dhe(e){let{inputs:t,backend:n,attrs:a}=e,{image:r}=t,{radians:s,fillValue:i,center:o}=a,l=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(r.dataId).id,p=n.dataIdMap.get(l.dataId).id,[d,c,h,m]=r.shape,[f,g]=N.getImageCenter(o,c,h),b=i===0,y=255,x=typeof i=="number"?[i,i,i,b?0:y]:[...i,y],v=new Uint8Array(new Int32Array(x).buffer);return c$(u,d,c,h,m,s,f,g,v,x.length,p),l}var hhe={kernelName:up,backendName:"wasm",kernelFunc:dhe,setupFunc:che},mhe=Xe(Ao),fhe=Xe(Fo),d$;function ghe(e){d$=e.wasm.cwrap(Xu,null,["number","number","number","number","number","number","array","number","number"])}function bhe(e){let{backend:t,inputs:n,attrs:a}=e,{indices:r,updates:s}=n,{shape:i}=a,o=t.makeOutput(i,s.dtype);if(w.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=wf.calculateShapes(s,r,i),h=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,f=new Uint8Array(new Int32Array(d).buffer),g=t.dataIdMap.get(o.dataId).id;return d$(h,m,Qe[s.dtype],l,u,p,f,c,g),o}var yhe={kernelName:Xu,backendName:"wasm",setupFunc:ghe,kernelFunc:bhe},h$;function xhe(e){h$=e.wasm.cwrap(Zu,null,["number","number","number","number","number","number","bool","number"])}function vhe(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a;if(r.dtype!==s.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${r.dtype} and ${s.dtype}`);let o=n.makeOutput(s.shape,"int32");function l(u){return n.dataIdMap.get(u.dataId).id}return h$(l(r),l(s),r.shape[0],r.shape[1],s.shape[1],Qe[r.dtype],i==="left",l(o)),o}var whe={kernelName:Zu,backendName:"wasm",setupFunc:xhe,kernelFunc:vhe},m$;function khe(e){m$=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Ihe(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(s.dataId).id,u=n.makeOutput(r.shape,r.dtype),p=n.dataIdMap.get(u.dataId).id,d=a.shape.length,c=r.shape.length,h=d===0||d>1||c===1?1:w.sizeFromShape(r.shape.slice(1));return m$(i,o,l,h,p),u}var She={kernelName:Ju,backendName:"wasm",kernelFunc:Ihe,setupFunc:khe},Nhe=Xe($o),f$;function The(e){f$=e.wasm.cwrap(Po,null,["number","number"])}function Che(e){let{backend:t,inputs:{x:n}}=e,a=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(r.dataId).id;return w.sizeFromShape(r.shape)===0||f$(a,s),r}var _he={kernelName:"Sigmoid",backendName:"wasm",setupFunc:The,kernelFunc:Che},Ehe=Xe(Mo),Ahe=Xe(Do),Fhe=Xe(Ro),$he=Xe(Oo);function Dhe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a,o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let u=a$.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=N.getReshaped(u.shape,s,o,!1),d=N.getPermuted(p.length,s.length,!1),c=N.getReshapedPermuted(u.shape,s,o,!1),h=Wn({inputs:{x:u},backend:n,attrs:{shape:p}}),m=ws({inputs:{x:h},backend:n,attrs:{perm:d}}),f=Wn({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeData(u.dataId),n.disposeData(h.dataId),n.disposeData(m.dataId),f}var Rhe={kernelName:ep,backendName:"wasm",kernelFunc:Dhe},g$;function Mhe(e){g$=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function Phe(e){let{backend:t,inputs:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=n,o=a.shape[0],l=a.shape[1],u=t.readSync(s.dataId)[0],p=[o+u,l],d=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(r.dataId).id,h=t.dataIdMap.get(i.dataId).id,m=t.makeOutput(p,a.dtype),f=t.dataIdMap.get(m.dataId).id,g=t.makeOutput(p.slice(0,1),r.dtype),b=t.dataIdMap.get(g.dataId).id,y=t.makeOutput([u],"bool"),x=t.dataIdMap.get(y.dataId).id,v=t.makeOutput([o],a.dtype),I=t.dataIdMap.get(v.dataId).id,T=t.makeOutput([4],"int32"),C=t.dataIdMap.get(T.dataId).id,E=g$(d,c,Qe[r.dtype],o,u,l,h,f,b,x,I,C),F=t.readSync(T.dataId),D;switch(F[0]){case 1:{D=N.getSparseFillEmptyRowsIndicesDenseShapeMismatch(F[1]);break}case 2:{D=N.getSparseFillEmptyRowsNegativeIndexErrorMessage(F[1],F[2]);break}case 3:D=N.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(F[1],F[2],F[3]);break;default:D=""}if(t.disposeData(T.dataId),D)throw t.disposeData(m.dataId),t.disposeData(g.dataId),t.disposeData(y.dataId),t.disposeData(v.dataId),new Error(D);let $=m,S=g;return E!==p[0]&&($=Si({inputs:{x:m},attrs:{begin:0,size:[E,l]},backend:t}),S=Si({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(m.dataId),t.disposeData(g.dataId)),[$,S,y,v]}var Ohe={kernelName:Kc,backendName:"wasm",setupFunc:Mhe,kernelFunc:Phe},b$;function Lhe(e){b$=e.wasm.cwrap(np,null,["number","number","number","number","number","number","number"])}function zhe(e){let{backend:t,inputs:n}=e,{inputIndices:a,inputShape:r,newShape:s}=n;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
        ${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
        ${r.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(a.dataId).id,o=t.dataIdMap.get(r.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=a.shape[0],p=w.sizeFromShape(s.shape),d=t.makeOutput([u,p],a.dtype),c=t.dataIdMap.get(d.dataId).id,h=t.makeOutput([p],s.dtype),m=t.dataIdMap.get(h.dataId).id,f=t.makeOutput([3],"int32"),g=t.dataIdMap.get(f.dataId).id;b$(i,o,l,u,c,m,g);let b=t.readSync(f.dataId),y;switch(b[0]){case 0:{y=N.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1],b[2]);break}case 1:{y=N.getSparseReshapeNegativeOutputDimErrorMessage(b[1],b[2]);break}case 2:y=N.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let x=Array.from(t.readSync(r.dataId)),v=Array.from(t.readSync(h.dataId));y=N.getSparseReshapeInputOutputMultipleErrorMessage(x,v);break}case 4:{let x=Array.from(t.readSync(r.dataId)),v=Array.from(t.readSync(h.dataId));y=N.getSparseReshapeInputOutputMismatchErrorMessage(x,v);break}default:y=""}if(t.disposeData(f.dataId),y)throw t.disposeData(d.dataId),t.disposeData(h.dataId),new Error(y);return[d,h]}var Whe={kernelName:np,backendName:"wasm",setupFunc:Lhe,kernelFunc:zhe},y$;function x$(e){y$=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function v$(e,t){let{backend:n,inputs:a}=e,{data:r,indices:s,segmentIds:i}=a,o=s.shape[0],l=n.readSync(i.dataId,o-1,o)[0],u=o>0?l+1:0;if(u<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=r.shape.slice();p[0]=u;let d=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(i.dataId).id,m=n.makeOutput(p,r.dtype),f=n.dataIdMap.get(m.dataId).id,g=n.makeOutput([4],"int32"),b=n.dataIdMap.get(g.dataId).id;y$(d,Qe[r.dtype],r.shape[0],c,h,f,b,t,0);let y=n.readSync(g.dataId),x;switch(y[0]){case 0:{x=N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=N.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=N.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y[1],y[2]);break;case 3:x=N.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(y[1],y[2],y[3]);break;default:x=""}if(n.disposeData(g.dataId),x)throw n.disposeData(m.dataId),new Error(x);return m}function Bhe(e){return v$(e,!0)}var Vhe={kernelName:Xc,backendName:"wasm",setupFunc:x$,kernelFunc:Bhe};function Uhe(e){return v$(e,!1)}var Ghe={kernelName:Yc,backendName:"wasm",setupFunc:x$,kernelFunc:Uhe},w$;function Hhe(e){w$=e.wasm.cwrap(ap,null,["number","number","number","number","number","number","number","number","array","number","number"])}function qhe(e){let{backend:t,inputs:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=n,{outputShape:o}=a,l=t.makeOutput(o,i.dtype);if(w.sizeFromShape(o)===0)return l;let{sliceRank:u,numUpdates:p,sliceSize:d,strides:c,outputSize:h}=N.calculateShapes(s,r,o),m=t.dataIdMap.get(r.dataId).id,f=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(i.dataId).id,b=new Uint8Array(new Int32Array(c).buffer),y=t.dataIdMap.get(l.dataId).id;return w$(m,f,s.shape.length,g,Qe[i.dtype],u,p,d,b,h,y),l}var jhe={kernelName:ap,backendName:"wasm",setupFunc:Hhe,kernelFunc:qhe};function Khe(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,r.shape)[0],l=N.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(d=>{let c=[...p];c[o]=d;let h=Si({inputs:{x:r},attrs:{begin:u,size:c},backend:a});return u[o]+=d,h})}var Xhe={kernelName:tp,backendName:"wasm",kernelFunc:Khe},Yhe=Xe(Lo),Zhe=Xe(Zc),Jhe=!0,Qhe=Ht(Bo,Jhe),k$;function eme(e){k$=e.wasm.cwrap(Ts,null,["number","number","number","number"])}function tme(e){let{backend:t,inputs:n,attrs:a}=e,{alpha:r}=a,{x:s}=n,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return k$(i,r,Qe[s.dtype],l),o}var nme={kernelName:Ts,backendName:"wasm",setupFunc:eme,kernelFunc:tme},I$;function ame(e){I$=e.wasm.cwrap(rp,null,["number","array","number","array","array","array","array","array","number","number"])}function rme(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:b,begin:y,end:x,strides:v}=Xt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),I;if(f)I=Wn({inputs:{x:r},backend:t,attrs:{shape:m}});else if(g||b){w.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let T=Xt.computeOutShape(y,x,v),C=Si({inputs:{x:r},backend:t,attrs:{begin:y,size:T}});I=Wn({inputs:{x:C},backend:t,attrs:{shape:m}}),t.disposeData(C.dataId)}else{let T=t.makeOutput(h,"float32"),C=t.dataIdMap.get(r.dataId).id,E=new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer),F=new Uint8Array(new Int32Array(y).buffer),D=new Uint8Array(new Int32Array(x).buffer),$=new Uint8Array(new Int32Array(v).buffer),S=new Uint8Array(new Int32Array(h).buffer),M=new Uint8Array(new Int32Array(w.computeStrides(h)).buffer),B=t.dataIdMap.get(T.dataId).id;I$(C,E,r.shape.length,F,D,$,S,M,h.length,B),I=Wn({inputs:{x:T},backend:t,attrs:{shape:m}}),t.disposeData(T.dataId)}return I}var sme={kernelName:rp,backendName:"wasm",setupFunc:ame,kernelFunc:rme};function ime(e){let{backend:t,inputs:n,attrs:a}=e,{data:r,dataSplits:s}=n,{separator:i,nGramWidths:o,leftPad:l,rightPad:u,padWidth:p,preserveShortSequences:d}=a,c=t.readSync(r.dataId),h=t.readSync(s.dataId),[m,f]=G1(c,h,i,o,l,u,p,d),g=t.makeOutput([m.length],"string"),b=t.dataIdMap.get(g.dataId);b.stringBytes=m;let y=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(y).set(f),[g,y]}var ome={kernelName:Qc,backendName:"wasm",kernelFunc:ime};function lme(e){let{backend:t,inputs:n,attrs:a}=e,{input:r,delimiter:s}=n,{skipEmpty:i}=a,o=t.readSync(r.dataId),l=t.readSync(s.dataId),[u,p,d]=H1(o,l[0],i),c=p.length,h=t.makeOutput([c,2],"int32");t.typedArrayFromHeap(h).set(u);let m=t.makeOutput([c],"string"),f=t.dataIdMap.get(m.dataId);f.stringBytes=p;let g=t.makeOutput([2],"int32");return t.typedArrayFromHeap(g).set(d),[h,m,g]}var ume={kernelName:ed,backendName:"wasm",kernelFunc:lme};function pme(e){let{backend:t,inputs:n,attrs:a}=e,{input:r}=n,{numBuckets:s}=a,i=t.readSync(r.dataId),o=q1(i,s),l=t.makeOutput(r.shape,"int32");return t.typedArrayFromHeap(l).set(o),l}var cme={kernelName:td,backendName:"wasm",kernelFunc:pme},dme=!0,hme=Ht(Vo,dme),S$;function mme(e){S$=e.wasm.cwrap(zo,null,["number","number","number","number"])}function fme(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=Ps(i,r,t),m=d;if(h){let x=t.dataIdMap.get(p.dataId).id;x!==o&&(u=p,l=x,m=N.getInnerMostAxes(m.length,u.shape.length))}N.assertAxesAreInnerMostDims("sum",m,u.shape.length);let[f,g]=N.computeOutAndReduceShapes(u.shape,m),b=w.sizeFromShape(g),y=t.makeOutput(f,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;S$(l,b,Qe[y.dtype],x)}if(h&&t.disposeData(p.dataId),s){let x=N.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var gme={kernelName:zo,backendName:"wasm",setupFunc:mme,kernelFunc:fme},bme=Xe(Uo),yme=Xe(Go),N$;function xme(e){N$=e.wasm.cwrap(Yu,null,["number","number","number","number","number","number","array","number","number","number"])}function vme(e){let{backend:t,inputs:n,attrs:a}=e,{tensor:r,indices:s,updates:i}=n,{}=a,o=t.makeOutput(r.shape,r.dtype);if(w.sizeFromShape(r.shape)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=wf.calculateShapes(i,s,r.shape),h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(i.dataId).id,f=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(d).buffer),b=t.dataIdMap.get(o.dataId).id;return N$(h,m,Qe[i.dtype],l,u,p,g,c,b,f),o}var wme={kernelName:Yu,backendName:"wasm",setupFunc:xme,kernelFunc:vme},T$;function kme(e){T$=e.wasm.cwrap(Ns,null,["number","array","number","array","number","number"])}function Ime(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,s=n.dataIdMap.get(r.dataId).id,{reps:i}=a,o=new Array(r.shape.length);for(let c=0;c<o.length;c++)o[c]=r.shape[c]*i[c];let l=new Uint8Array(new Int32Array(r.shape).buffer),u=new Uint8Array(new Int32Array(o).buffer),p=n.makeOutput(o,r.dtype),d=n.dataIdMap.get(p.dataId).id;return T$(s,l,r.shape.length,u,o.length,Qe[p.dtype],d),p}var Sme={kernelName:Ns,backendName:"wasm",setupFunc:kme,kernelFunc:Ime},C$;function Nme(e){C$=e.wasm.cwrap(sp,null,["number","array","number","number","number","bool","number","number"])}var Tme=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{k:r,sorted:s}=n,i=t.dataIdMap.get(a.dataId).id,o=new Uint8Array(new Int32Array(a.shape).buffer),l=a.shape.slice();l[l.length-1]=r;let u=t.makeOutput(l,a.dtype),p=t.dataIdMap.get(u.dataId).id,d=t.makeOutput(l,"int32"),c=t.dataIdMap.get(d.dataId).id;return C$(i,o,a.shape.length,Qe[a.dtype],r,s,p,c),[u,d]},Cme={kernelName:sp,backendName:"wasm",setupFunc:Nme,kernelFunc:Tme},_$;function _me(e){_$=e.wasm.cwrap(ip,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function Eme(e){let{backend:t,inputs:n,attrs:a}=e,{image:r,transforms:s}=n,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],b=new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer),y=new Uint8Array(new Int32Array(w.computeStrides(g)).buffer),x=t.makeOutput(g,r.dtype),v=t.dataIdMap.get(x.dataId).id,I=t.dataIdMap.get(r.dataId).id,T=t.dataIdMap.get(s.dataId).id,C=i==="nearest"?1:2,E;switch(o){case"constant":E=1;break;case"reflect":E=2;break;case"wrap":E=3;break;case"nearest":E=4;break;default:E=1;break}return _$(I,T,s.shape[0]>1,p,m,f,h,c,d,b,r.shape.length-1,y,g.length-1,C,E,l,v),x}var Ame={kernelName:ip,backendName:"wasm",setupFunc:_me,kernelFunc:Eme};function Fme(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t,{outputValues:i,outputShape:o,indices:l}=K1(a.readSync(s.dataId),r,s.shape,s.dtype);return[a.makeOutput(o,s.dtype,void 0,i),a.makeOutput([l.length],"int32",void 0,l)]}var $me={kernelName:nd,backendName:"wasm",kernelFunc:Fme};function Dme(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r.shape[s],o=r.shape.length,l=new Array(o-1),u=0;for(let h=0;h<o;h++)h!==s&&(l[u++]=r.shape[h]);let p=new Array(i),d=new Array(o).fill(0),c=r.shape.slice();c[s]=1;for(let h=0;h<p.length;h++)d[s]=h,p[h]=Si({inputs:{x:r},attrs:{begin:d,size:c},backend:n});return p.map(({dataId:h,dtype:m})=>({dataId:h,dtype:m,shape:l}))}var Rme={kernelName:op,backendName:"wasm",kernelFunc:Dme};function Mme(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(0),a}var Pme={kernelName:lp,backendName:"wasm",kernelFunc:Mme},Ome=[yle,xle,vle,wle,Ile,Tle,Rle,Ole,Lle,zle,Wle,Ble,Vle,Ule,Gle,jle,nue,Yle,Qle,iue,due,fue,bue,xue,vue,wue,Sue,Nue,_ue,Fue,Rue,Oue,Wue,Bue,Vue,Hue,Kue,Zue,epe,ape,ipe,upe,dpe,fpe,ype,xpe,kpe,Spe,Npe,Tpe,Cpe,_pe,Epe,$pe,Dpe,Mpe,Lpe,Bpe,Gpe,jpe,Ype,Jpe,ece,Cle,tce,nce,ace,ice,lce,pce,hce,fce,mce,bce,yce,vce,kce,Nce,_ce,Fce,Dce,Pce,zce,Vce,Hce,Kce,Zce,ede,nde,sde,pde,cde,hde,mde,bde,vde,Ide,Nde,_de,Ade,$de,a$,Pde,zde,Vde,Gde,qde,jde,Kde,Xde,aue,Jde,the,rhe,ohe,phe,hhe,mhe,fhe,yhe,whe,She,Nhe,_he,Ehe,Ahe,Fhe,pue,ode,$he,Rhe,Ohe,Whe,Vhe,Ghe,jhe,Xhe,Yhe,Zhe,Qhe,nme,sme,ome,ume,cme,hme,gme,bme,yme,wme,Sme,Cme,Ame,Fle,$me,Rme,Pme];for(let e of Ome)rd(e);var kv=G();kv.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(e){return!1}});kv.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(kv.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(e){return!1}});var LS=ks(kR()),Lme=ks(IR()),zS=ks(SR()),WS=LS.default||LS,zme=zS.default||zS,E$=class extends Mc{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(A$),Iv=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Rm(this,Aa())}write(e,t,n){let a={id:this.dataIdNextNumber++};return this.move(a,e,t,n,1),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,n,a,r){let s=this.dataIdNextNumber++;if(a==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:n,dtype:a,memoryOffset:null,refCount:r});return}let i=w.sizeFromShape(n),o=i*w.bytesPerElement(a),l=this.wasm._malloc(o)>>>0;this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:n,dtype:a,refCount:r}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e,t,n){let{memoryOffset:a,dtype:r,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(r==="string")return(t==null||t===0)&&(n==null||n>=i.length)?i:i.slice(t,n);t=t||0,n=n||w.sizeFromShape(s);let o=w.bytesPerElement(r),l=this.wasm.HEAPU8.slice(a+t*o,a+n*o);return Vme(l.buffer,r)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n,a){let r;if(n==null)r=this.write(a!=null?a:null,e,t);else{let s=this.dataIdNextNumber++;r={id:s},this.dataIdMap.set(r,{id:s,memoryOffset:n,shape:e,dtype:t,refCount:1});let i=w.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,i,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let a=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),s=w.sizeFromShape(e);switch(t){case"float32":return new Float32Array(a,r,s);case"int32":return new Int32Array(a,r,s);case"bool":return new Uint8Array(a,r,s);default:throw new Error(`Unknown dtype ${t}`)}}};function Wme(e){return(t,n)=>(w.fetch(e,{credentials:"same-origin"}).then(a=>{a.ok||t.env.a(`failed to load wasm binary file at '${e}'`),a.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(s=>{n(s.instance,s.module)})})}),{})}function BS(e,t,n){if($m!=null)return $m;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),fc!=null&&fc[a]!=null?fc[a]:n+a}async function Bme(){let[e,t]=await Promise.all([G().getAsync("WASM_HAS_SIMD_SUPPORT"),G().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,a)=>{let r={};r.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=Lme.wasmWorkerContents.replace(/\n/g,"\\n"),p=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(p)}return o.endsWith(".wasm")?BS(e,t,dc!=null?dc:l):l+o},mk&&(r.instantiateWasm=Wme(BS(e,t,dc!=null?dc:"")));let s=!1;r.onAbort=()=>{s||gc||(gc=!0,a({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&&e&&$m==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+WS.toString()],{type:"text/javascript"}),i=WS(r)):i=zme(r),i.then(o=>{s=!0,gc=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),initWithThreadsCount:o.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:o.cwrap("get_threads_count","number",[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},n({wasm:o})}).catch(a)})}function Vme(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}var Ume=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],$m=null,dc=null,fc={},gc=!1,mk=!1;function Gme(e,t=!1){if(Ov("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),gc)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");$m=e,mk=t}function Hme(e,t=!1){if(gc)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof e=="string")dc=e;else{fc=e;let n=Ume.filter(a=>fc[a]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.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.`)}mk=t}var A$=-1,Iv=-1;function qme(e){A$=e}function jme(){if(Iv===-1)throw new Error("WASM backend not initialized.");return Iv}var Kme="4.7.0",Xme=2;Zm("wasm",async()=>{let{wasm:e}=await Bme();return new E$(e)},Xme);var VS="4.7.0",Yme="4.7.0",Zme="4.7.0",Jme="4.7.0",Qme="4.7.0",efe={tfjs:VS,"tfjs-core":VS,"tfjs-converter":Yme,"tfjs-backend-cpu":Zme,"tfjs-backend-webgl":Jme,"tfjs-backend-wasm":Qme};var zk={};Dh(zk,{AnchorPosition:()=>Ak,DrawBox:()=>Bd,DrawBoxOptions:()=>og,DrawFaceLandmarks:()=>yg,DrawFaceLandmarksOptions:()=>bg,DrawTextField:()=>Gr,DrawTextFieldOptions:()=>Fp,drawContour:()=>Br,drawDetections:()=>ufe,drawFaceExpressions:()=>mfe,drawFaceLandmarks:()=>gfe});function Br(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:a,y:r},s)=>{let i=t[s];e.moveTo(i.x,i.y),e.lineTo(a,r)}),n){let a=t[t.length-1],r=t[0];if(!a||!r)return;e.moveTo(a.x,a.y),e.lineTo(r.x,r.y)}e.stroke()}var yk={};Dh(yk,{computeReshapedDimensions:()=>bk,getCenterPoint:()=>rl,isDimensions:()=>sg,isEven:()=>rg,isFloat:()=>gk,isTensor:()=>nl,isTensor1D:()=>tfe,isTensor2D:()=>fk,isTensor3D:()=>Vr,isTensor4D:()=>ka,isValidNumber:()=>Za,isValidProbablitiy:()=>_p,range:()=>xr,round:()=>al});var wn=class{constructor(t,n){if(!Za(t)||!Za(n))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:t,height:n})}`);this._width=t,this._height=n}get width(){return this._width}get height(){return this._height}reverse(){return new wn(1/this.width,1/this.height)}};function nl(e,t){return e instanceof Te&&e.shape.length===t}function tfe(e){return nl(e,1)}function fk(e){return nl(e,2)}function Vr(e){return nl(e,3)}function ka(e){return nl(e,4)}function gk(e){return e%1!==0}function rg(e){return e%2===0}function al(e,t=2){let n=10**t;return Math.floor(e*n)/n}function sg(e){return e&&e.width&&e.height}function bk({width:e,height:t},n){let a=n/Math.max(t,e);return new wn(Math.round(e*a),Math.round(t*a))}function rl(e){return e.reduce((t,n)=>t.add(n),new Re(0,0)).div(new Re(e.length,e.length))}function xr(e,t,n){return Array(e).fill(0).map((a,r)=>t+r*n)}function Za(e){return!!e&&e!==1/0&&e!==-1/0&&!Number.isNaN(e)||e===0}function _p(e){return Za(e)&&e>=0&&e<=1}var Re=class{constructor(t,n){this._x=t,this._y=n}get x(){return this._x}get y(){return this._y}add(t){return new Re(this.x+t.x,this.y+t.y)}sub(t){return new Re(this.x-t.x,this.y-t.y)}mul(t){return new Re(this.x*t.x,this.y*t.y)}div(t){return new Re(this.x/t.x,this.y/t.y)}abs(){return new Re(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new Re(Math.floor(this.x),Math.floor(this.y))}};var ot=class{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(Za)}static assertIsValidBox(t,n,a=!1){if(!ot.isRect(t))throw new Error(`${n} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!a&&(t.width<0||t.height<0))throw new Error(`${n} - width (${t.width}) and height (${t.height}) must be positive numbers`)}constructor(t,n=!0){let a=t||{},r=[a.left,a.top,a.right,a.bottom].every(Za),s=[a.x,a.y,a.width,a.height].every(Za);if(!s&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(a)}`);let[i,o,l,u]=s?[a.x,a.y,a.width,a.height]:[a.left,a.top,a.right-a.left,a.bottom-a.top];ot.assertIsValidBox({x:i,y:o,width:l,height:u},"Box.constructor",n),this._x=i,this._y=o,this._width=l,this._height=u}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new Re(this.left,this.top)}get topRight(){return new Re(this.right,this.top)}get bottomLeft(){return new Re(this.left,this.bottom)}get bottomRight(){return new Re(this.right,this.bottom)}round(){let[t,n,a,r]=[this.x,this.y,this.width,this.height].map(s=>Math.round(s));return new ot({x:t,y:n,width:a,height:r})}floor(){let[t,n,a,r]=[this.x,this.y,this.width,this.height].map(s=>Math.floor(s));return new ot({x:t,y:n,width:a,height:r})}toSquare(){let{x:t,y:n,width:a,height:r}=this,s=Math.abs(a-r);return a<r&&(t-=s/2,a+=s),r<a&&(n-=s/2,r+=s),new ot({x:t,y:n,width:a,height:r})}rescale(t){let n=sg(t)?t.width:t,a=sg(t)?t.height:t;return new ot({x:this.x*n,y:this.y*a,width:this.width*n,height:this.height*a})}pad(t,n){let[a,r,s,i]=[this.x-t/2,this.y-n/2,this.width+t,this.height+n];return new ot({x:a,y:r,width:s,height:i})}clipAtImageBorders(t,n){let{x:a,y:r,right:s,bottom:i}=this,o=Math.max(a,0),l=Math.max(r,0),u=s-o,p=i-l,d=Math.min(u,t-o),c=Math.min(p,n-l);return new ot({x:o,y:l,width:d,height:c}).floor()}shift(t,n){let{width:a,height:r}=this,s=this.x+t,i=this.y+n;return new ot({x:s,y:i,width:a,height:r})}padAtBorders(t,n){let a=this.width+1,r=this.height+1,s=1,i=1,o=a,l=r,u=this.left,p=this.top,d=this.right,c=this.bottom;return d>n&&(o=-d+n+a,d=n),c>t&&(l=-c+t+r,c=t),u<1&&(l=2-u,u=1),p<1&&(l=2-p,p=1),{dy:i,edy:l,dx:s,edx:o,y:p,ey:c,x:u,ex:d,w:a,h:r}}calibrate(t){return new ot({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()}};var sl=class extends ot{constructor(t,n,a,r,s=!1){super({left:t,top:n,right:a,bottom:r},s)}};var Ur=class{constructor(t,n,a,r,s){this._imageDims=new wn(s.width,s.height),this._score=t,this._classScore=n,this._className=a,this._box=new ot(r).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new ot(this._box).rescale(this.imageDims.reverse())}forSize(t,n){return new Ur(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})}};var vt=class extends Ur{constructor(t,n,a){super(t,t,"",n,a)}forSize(t,n){let{score:a,relativeBox:r,imageDims:s}=super.forSize(t,n);return new vt(a,r,s)}};function xk(e,t,n=!0){let a=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),r=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),s=a*r;return n?s/(e.area+t.area-s):s/Math.min(e.area,t.area)}function vk(e){let t=e.map(o=>o.x),n=e.map(o=>o.y),a=t.reduce((o,l)=>l<o?l:o,1/0),r=n.reduce((o,l)=>l<o?l:o,1/0),s=t.reduce((o,l)=>o<l?l:o,0),i=n.reduce((o,l)=>o<l?l:o,0);return new sl(a,r,s,i)}function wk(e,t,n,a=!0){let r=t.map((i,o)=>({score:i,boxIndex:o})).sort((i,o)=>i.score-o.score).map(i=>i.boxIndex),s=[];for(;r.length>0;){let i=r.pop();s.push(i);let o=r,l=[];for(let u=0;u<o.length;u++){let p=o[u],d=e[i],c=e[p];l.push(xk(d,c,a))}r=r.filter((u,p)=>l[p]<=n)}return s}function Ja(e,t){return P(()=>{let[n,a,r]=t,s=xn([...e.shape.slice(0,3),1],n,"float32"),i=xn([...e.shape.slice(0,3),1],a,"float32"),o=xn([...e.shape.slice(0,3),1],r,"float32"),l=et([s,i,o],3);return pe(e,l)})}function kk(e,t=!1){return P(()=>{let[n,a]=e.shape.slice(1);if(n===a)return e;let r=Math.abs(n-a),s=Math.round(r*(t?.5:1)),i=n>a?2:1,o=c=>{let h=e.shape.slice();return h[i]=c,xn(h,0,"float32")},l=o(s),u=r-l.shape[i],d=[t&&u?o(u):null,e,l].filter(c=>!!c).map(c=>se(c,"float32"));return et(d,i)})}function nfe(e){let t=e.slice();for(let n=t.length-1;n>0;n--){let a=Math.floor(Math.random()*(n+1)),r=t[n];t[n]=t[a],t[a]=r}return t}function zd(e){return 1/(1+Math.exp(-e))}function afe(e){return Math.log(e/(1-e))}var il=class extends ot{constructor(t,n,a,r,s=!1){super({x:t,y:n,width:a,height:r},s)}};var rfe=.5,sfe=.43,ife=.45,ia=class{constructor(t,n,a=new Re(0,0)){let{width:r,height:s}=n;this._imgDims=new wn(r,s),this._shift=a,this._positions=t.map(i=>i.mul(new Re(r,s)).add(a))}get shift(){return new Re(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(t=>t.sub(this._shift).div(new Re(this.imageWidth,this.imageHeight)))}forSize(t,n){return new this.constructor(this.relativePositions,{width:t,height:n})}shiftBy(t,n){return new this.constructor(this.relativePositions,this._imgDims,new Re(t,n))}shiftByPoint(t){return this.shiftBy(t.x,t.y)}align(t,n={}){if(t){let s=t instanceof vt?t.box.floor():new ot(t);return this.shiftBy(s.x,s.y).align(null,n)}let{useDlibAlignment:a,minBoxPadding:r}={useDlibAlignment:!1,minBoxPadding:.2,...n};return a?this.alignDlib():this.alignMinBbox(r)}alignDlib(){let t=this.getRefPointsForAlignment(),[n,a,r]=t,s=d=>r.sub(d).magnitude(),i=(s(n)+s(a))/2,o=Math.floor(i/ife),l=rl(t),u=Math.floor(Math.max(0,l.x-rfe*o)),p=Math.floor(Math.max(0,l.y-sfe*o));return new il(u,p,Math.min(o,this.imageWidth+u),Math.min(o,this.imageHeight+p))}alignMinBbox(t){let n=vk(this.positions);return n.pad(n.width*t,n.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var Ik=class extends ia{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],rl([t[3],t[4]])]}};var ol=class extends ia{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(rl)}};var Ep=class{constructor(t,n){this._label=t,this._distance=n}get label(){return this._label}get distance(){return this._distance}toString(t=!0){return`${this.label}${t?` (${al(this.distance)})`:""}`}};var Ap=class extends ot{constructor(n,a){super(n);this._label=a}static assertIsValidLabeledBox(n,a){if(ot.assertIsValidBox(n,a),!Za(n.label))throw new Error(`${a} - expected property label (${n.label}) to be a number`)}get label(){return this._label}};var vr=class{constructor(t,n){if(typeof t!="string")throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(n)||n.some(a=>!(a instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=n}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(t=>Array.from(t))}}static fromJSON(t){let n=t.descriptors.map(a=>new Float32Array(a));return new vr(t.label,n)}};var Sk=class extends Ap{constructor(n,a,r,s){super(n,a);this._score=r,this._classScore=s}static assertIsValidPredictedBox(n,a){if(Ap.assertIsValidLabeledBox(n,a),!_p(n.score)||!_p(n.classScore))throw new Error(`${a} - expected properties score (${n.score}) and (${n.classScore}) to be a number between [0, 1]`)}get score(){return this._score}get classScore(){return this._classScore}};function wr(e){return e.detection instanceof vt}function ll(e,t){return{...e,...{detection:t}}}function Nk(){let e=window.fetch;if(!e)throw new Error("fetch - missing fetch implementation for browser environment");return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),createVideoElement:()=>document.createElement("video"),fetch:e,readFile:()=>{throw new Error("readFile - filesystem not available for browser environment")}}}function Wd(){return typeof global=="object"&&typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null}function ig(e){let t="";if(!e&&Wd())try{e=QD("fs")}catch(a){t=a.toString()}return{readFile:e?a=>new Promise((r,s)=>{e.readFile(a,(i,o)=>i?s(i):r(o))}):()=>{throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)}}}function Tk(){let e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=global.Video||global.HTMLVideoElement,a=()=>{if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},r=()=>{if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},s=()=>{if(n)return new n;throw new Error("createVideoElement - missing Video implementation for nodejs environment")},i=global.fetch,o=ig();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:a,createImageElement:r,createVideoElement:s,fetch:i,...o}}function Ck(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var un;function ofe(){if(!un)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return un}function _k(e){un=e}function Ek(){return Ck()?_k(Nk()):Wd()?_k(Tk()):null}function lfe(e){if(un||Ek(),!un)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=un.Canvas,Image:n=un.Image}=e;un.Canvas=t,un.Image=n,un.createCanvasElement=e.createCanvasElement||(()=>new t),un.createImageElement=e.createImageElement||(()=>new n),un.ImageData=e.ImageData||un.ImageData,un.Video=e.Video||un.Video,un.fetch=e.fetch||un.fetch,un.readFile=e.readFile||un.readFile}var tt={getEnv:ofe,setEnv:_k,initialize:Ek,createBrowserEnv:Nk,createFileSystem:ig,createNodejsEnv:Tk,monkeyPatch:lfe,isBrowser:Ck,isNodejs:Wd};Ek();function ul(e){return!tt.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function Hn(e){let{Canvas:t,CanvasRenderingContext2D:n}=tt.getEnv();if(e instanceof n)return e;let a=ul(e);if(!(a instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");let r=a.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("resolveContext2d - canvas 2d context is null");return r}var Ak=(r=>(r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT",r))(Ak||{}),Fp=class{constructor(t={}){let{anchorPosition:n,backgroundColor:a,fontColor:r,fontSize:s,fontStyle:i,padding:o}=t;this.anchorPosition=n||"TOP_LEFT",this.backgroundColor=a||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=s||14,this.fontStyle=i||"Georgia",this.padding=o||4}},Gr=class{constructor(t,n,a={}){this.text=typeof t=="string"?[t]:t instanceof Gr?t.text:t,this.anchor=n,this.options=new Fp(a)}measureWidth(t){let{padding:n}=this.options;return this.text.map(a=>t.measureText(a).width).reduce((a,r)=>a<r?r:a,0)+2*n}measureHeight(){let{fontSize:t,padding:n}=this.options;return this.text.length*t+2*n}getUpperLeft(t,n){let{anchorPosition:a}=this.options,r=a==="BOTTOM_RIGHT"||a==="TOP_RIGHT",s=a==="BOTTOM_LEFT"||a==="BOTTOM_RIGHT",i=this.measureWidth(t),o=this.measureHeight(),l=r?this.anchor.x-i:this.anchor.x,u=s?this.anchor.y-o:this.anchor.y;if(n){let{width:p,height:d}=n,c=Math.max(Math.min(l,p-i),0),h=Math.max(Math.min(u,d-o),0);return{x:c,y:h}}return{x:l,y:u}}draw(t){let n=ul(t),a=Hn(n),{backgroundColor:r,fontColor:s,fontSize:i,fontStyle:o,padding:l}=this.options;a.font=`${i}px ${o}`;let u=this.measureWidth(a),p=this.measureHeight();a.fillStyle=r;let d=this.getUpperLeft(a,n);a.fillRect(d.x,d.y,u,p),a.fillStyle=s,this.text.forEach((c,h)=>{let m=l+d.x,f=l+d.y+(h+1)*i;a.fillText(c,m,f)})}};var og=class{constructor(t={}){let{boxColor:n,lineWidth:a,label:r,drawLabelOptions:s}=t;this.boxColor=n||"rgba(0, 0, 255, 1)",this.lineWidth=a||2,this.label=r;let i={anchorPosition:"BOTTOM_LEFT",backgroundColor:this.boxColor};this.drawLabelOptions=new Fp({...i,...s})}},Bd=class{constructor(t,n={}){this.box=new ot(t),this.options=new og(n)}draw(t){let n=Hn(t),{boxColor:a,lineWidth:r}=this.options,{x:s,y:i,width:o,height:l}=this.box;n.strokeStyle=a,n.lineWidth=r,n.strokeRect(s,i,o,l);let{label:u}=this.options;u&&new Gr([u],{x:s-r/2,y:i},this.options.drawLabelOptions).draw(t)}};function ufe(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof vt?a.score:wr(a)?a.detection.score:void 0,s=a instanceof vt?a.box:wr(a)?a.detection.box:new ot(a),i=r?`${al(r)}`:void 0;new Bd(s,{label:i}).draw(e)})}function Vd(e){let{Image:t,Video:n}=tt.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function Fk(e){return new Promise((t,n)=>{(e instanceof tt.getEnv().Canvas||Vd(e))&&t(null);function a(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",r),s.currentTarget.removeEventListener("error",a),n(s))}function r(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",r),s.currentTarget.removeEventListener("error",a),t(s))}e.addEventListener("load",r),e.addEventListener("error",a)})}function $k(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToImage - expected buf to be of type: Blob"));let a=new FileReader;a.onload=()=>{typeof a.result!="string"&&n(new Error("bufferToImage - expected reader.result to be a string, in onload"));let r=tt.getEnv().createImageElement();r.onload=()=>t(r),r.onerror=n,r.src=a.result},a.onerror=n,a.readAsDataURL(e)})}function pl(e){let{Image:t,Video:n}=tt.getEnv();return e instanceof t?new wn(e.naturalWidth,e.naturalHeight):e instanceof n?new wn(e.videoWidth,e.videoHeight):new wn(e.width,e.height)}function cl({width:e,height:t}){let{createCanvasElement:n}=tt.getEnv(),a=n();return a.width=e,a.height=t,a}function Ud(e,t){let{ImageData:n}=tt.getEnv();if(!(e instanceof n)&&!Vd(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:a,height:r}=t||pl(e),s=cl({width:a,height:r});return e instanceof n?Hn(s).putImageData(e,0,0):Hn(s).drawImage(e,0,0,a,r),s}async function Dk(e,t){let n=t||tt.getEnv().createCanvasElement(),[a,r,s]=e.shape.slice(ka(e)?1:0),i=P(()=>e.as3D(a,r,s).toInt());return await Ko.toPixels(i,n),i.dispose(),n}function lg(e){let{Image:t,Canvas:n,Video:a}=tt.getEnv();return e instanceof t||e instanceof n||e instanceof a}function Rk(e,t,n=!1){let{Image:a,Canvas:r}=tt.getEnv();if(!(e instanceof a||e instanceof r))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return cl({width:1,height:1});let s=pl(e),i=t/Math.max(s.height,s.width),o=i*s.width,l=i*s.height,u=cl({width:t,height:t}),p=e instanceof r?e:Ud(e),d=Math.abs(o-l)/2,c=n&&o<l?d:0,h=n&&l<o?d:0;return p.width>0&&p.height>0&&Hn(u).drawImage(p,c,h,o,l),u}var kr=class{constructor(t,n=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];this._inputSize=0;if(!Array.isArray(t))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${t}`);this._treatAsBatchInput=n,this._batchSize=t.length,t.forEach((a,r)=>{if(Vr(a)){this._imageTensors[r]=a,this._inputDimensions[r]=a.shape;return}if(ka(a)){let i=a.shape[0];if(i!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${i} passed, but not supported in input array`);this._imageTensors[r]=a,this._inputDimensions[r]=a.shape.slice(1);return}let s=a instanceof tt.getEnv().Canvas?a:Ud(a);this._canvases[r]=s,this._inputDimensions[r]=[s.height,s.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return xr(this.batchSize,0,1).map((t,n)=>this.getReshapedInputDimensions(n))}getInput(t){return this.canvases[t]||this.imageTensors[t]}getInputDimensions(t){return this._inputDimensions[t]}getInputHeight(t){return this._inputDimensions[t][0]}getInputWidth(t){return this._inputDimensions[t][1]}getReshapedInputDimensions(t){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");let n=this.getInputWidth(t),a=this.getInputHeight(t);return bk({width:n,height:a},this.inputSize)}toBatchTensor(t,n=!0){return this._inputSize=t,P(()=>{let a=xr(this.batchSize,0,1).map(s=>{let i=this.getInput(s);if(i instanceof Te){let o=ka(i)?i:nn(i);return o=kk(o,n),(o.shape[1]!==t||o.shape[2]!==t)&&(o=ea.resizeBilinear(o,[t,t],!1,!1)),o.as3D(t,t,3)}if(i instanceof tt.getEnv().Canvas)return Ko.fromPixels(Rk(i,t,n));throw new Error(`toBatchTensor - at batchIdx ${s}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)});return Dt(a.map(s=>se(s,"float32"))).as4D(this.batchSize,t,t,3)})}};async function wt(e){if(e instanceof kr)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");let n=r=>Array.isArray(e)?` at input index ${r}:`:"",a=t.map(ul);return a.forEach((r,s)=>{if(!lg(r)&&!Vr(r)&&!ka(r))throw typeof t[s]=="string"?new Error(`toNetInput -${n(s)} string passed, but could not resolve HTMLElement for element id ${t[s]}`):new Error(`toNetInput -${n(s)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(ka(r)){let i=r.shape[0];if(i!==1)throw new Error(`toNetInput -${n(s)} tf.Tensor4D with batchSize ${i} passed, but not supported in input array`)}}),await Promise.all(a.map(r=>lg(r)&&Fk(r))),new kr(a,Array.isArray(e))}async function $p(e,t){let{Canvas:n}=tt.getEnv(),a=e;if(!(e instanceof n)){let i=await wt(e);if(i.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let o=i.getInput(0);a=o instanceof n?o:await Dk(o)}let r=Hn(a);return t.map(i=>i instanceof vt?i.forSize(a.width,a.height).box.floor():i).map(i=>i.clipAtImageBorders(a.width,a.height)).map(({x:i,y:o,width:l,height:u})=>{let p=cl({width:l,height:u});return l>0&&u>0&&Hn(p).putImageData(r.getImageData(i,o,l,u),0,0),p})}async function Dp(e,t){if(!Vr(e)&&!ka(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(ka(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return P(()=>{let[n,a,r]=e.shape.slice(ka(e)?1:0);return t.map(o=>o instanceof vt?o.forSize(a,n).box:o).map(o=>o.clipAtImageBorders(a,n)).filter(o=>o.width>0&&o.height>0).map(({x:o,y:l,width:u,height:p})=>qo(e.as3D(n,a,r),[l,o,0],[p,u,r]))})}async function Hr(e,t){let{fetch:n}=tt.getEnv(),a=await n(e,t);if(!(a.status<400))throw new Error(`failed to fetch: (${a.status}) ${a.statusText}, from url: ${a.url}`);return a}async function pfe(e){let t=await Hr(e),n=await t.blob();if(!n.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${n.type}, for url: ${t.url}`);return $k(n)}async function Mk(e){return(await Hr(e)).json()}async function cfe(e){return new Float32Array(await(await Hr(e)).arrayBuffer())}function F$(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToVideo - expected buf to be of type: Blob"));let a=tt.getEnv().createVideoElement();a.oncanplay=()=>t(a),a.onerror=n,a.playsInline=!0,a.muted=!0,a.src=URL.createObjectURL(e),a.play()})}async function dfe(e){let t=await Hr(e),n=await t.blob();if(!n.type.startsWith("video/"))throw new Error(`fetchVideo - expected blob type to be of type video/*, instead have: ${n.type}, for url: ${t.url}`);return F$(n)}function ug(e,t){let n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};let a=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(a,"");let r=e.split("/").filter(o=>o),s=e.endsWith(".json")?r[r.length-1]:n,i=a+(e.endsWith(".json")?r.slice(0,r.length-1):r).join("/");return i=e.startsWith("/")?`/${i}`:i,{modelBaseUri:i,manifestUri:i==="/"?`/${s}`:`${i}/${s}`}}async function Pk(e,t){let{manifestUri:n,modelBaseUri:a}=ug(e,t),r=await Mk(n);return jt.loadWeights(r,a)}function hfe(e,t,n=!1){let{width:a,height:r}=n?pl(t):t;return e.width=a,e.height=r,{width:a,height:r}}var pn=class{constructor(t){this._params=void 0;this._paramMappings=[];this._name=t}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(t){let{obj:n,objProp:a}=this.traversePropertyPath(t);return n[a]}reassignParamFromPath(t,n){let{obj:a,objProp:r}=this.traversePropertyPath(t);a[r].dispose(),a[r]=n}getParamList(){return this._paramMappings.map(({paramPath:t})=>({path:t,tensor:this.getParamFromPath(t)}))}getTrainableParams(){return this.getParamList().filter(t=>t.tensor instanceof hs)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof hs))}variable(){this.getFrozenParams().forEach(({path:t,tensor:n})=>{this.reassignParamFromPath(t,n.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:n})=>{let a=bn(n.dataSync());n.dispose(),this.reassignParamFromPath(t,a)})}dispose(t=!0){this.getParamList().forEach(n=>{if(t&&n.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${n.path}`);n.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:t})=>Array.from(t.dataSync())).reduce((t,n)=>t.concat(n)))}async load(t){if(t instanceof Float32Array){this.extractWeights(t);return}await this.loadFromUri(t)}async loadFromUri(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);let n=await Pk(t,this.getDefaultModelName());this.loadFromWeightMap(n)}async loadFromDisk(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);let{readFile:n}=tt.getEnv(),{manifestUri:a,modelBaseUri:r}=ug(t,this.getDefaultModelName()),s=u=>Promise.all(u.map(p=>n(p).then(d=>d.buffer))),i=jt.weightsLoaderFactory(s),o=JSON.parse((await n(a)).toString()),l=await i(o,r);this.loadFromWeightMap(l)}loadFromWeightMap(t){let{paramMappings:n,params:a}=this.extractParamsFromWeightMap(t);this._paramMappings=n,this._params=a}extractWeights(t){let{paramMappings:n,params:a}=this.extractParams(t);this._paramMappings=n,this._params=a}traversePropertyPath(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let n=t.split("/").reduce((s,i)=>{if(!s.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${t}`);return{obj:s.nextObj,objProp:i,nextObj:s.nextObj[i]}},{nextObj:this.params}),{obj:a,objProp:r}=n;if(!a||!r||!(a[r]instanceof Te))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:a,objProp:r}}};function qn(e,t,n){return P(()=>{let a=$s(e,t.depthwise_filter,t.pointwise_filter,n,"same");return a=X(a,t.bias),a})}function pg(e,t,n=!1){return P(()=>{let a=Ke(n?X(Rt(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):qn(e,t.conv0,[2,2])),r=qn(a,t.conv1,[1,1]),s=Ke(X(a,r)),i=qn(s,t.conv2,[1,1]);return Ke(X(a,X(r,i)))})}function Gd(e,t,n=!1,a=!0){return P(()=>{let r=Ke(n?X(Rt(e,t.conv0.filters,a?[2,2]:[1,1],"same"),t.conv0.bias):qn(e,t.conv0,a?[2,2]:[1,1])),s=qn(r,t.conv1,[1,1]),i=Ke(X(r,s)),o=qn(i,t.conv2,[1,1]),l=Ke(X(r,X(s,o))),u=qn(l,t.conv3,[1,1]);return Ke(X(r,X(s,X(o,u))))})}function dl(e,t,n="same",a=!1){return P(()=>{let r=X(Rt(e,t.filters,[1,1],n),t.bias);return a?Ke(r):r})}function An(e,t){Object.keys(e).forEach(n=>{t.some(a=>a.originalPath===n)||e[n].dispose()})}function Rp(e,t){return(n,a,r,s)=>{let i=Ma(e(n*a*r*r),[r,r,n,a]),o=je(e(a));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:i,bias:o}}}function cg(e,t){return(n,a,r)=>{let s=$a(e(n*a),[n,a]),i=je(e(a));return t.push({paramPath:`${r}/weights`},{paramPath:`${r}/bias`}),{weights:s,bias:i}}}var Hd=class{constructor(t,n,a){this.depthwise_filter=t;this.pointwise_filter=n;this.bias=a}};function Mp(e,t){return(n,a,r)=>{let s=Ma(e(9*n),[3,3,n,1]),i=Ma(e(n*a),[1,1,n,a]),o=je(e(a));return t.push({paramPath:`${r}/depthwise_filter`},{paramPath:`${r}/pointwise_filter`},{paramPath:`${r}/bias`}),new Hd(s,i,o)}}function Pp(e){return t=>{let n=e(`${t}/depthwise_filter`,4),a=e(`${t}/pointwise_filter`,4),r=e(`${t}/bias`,1);return new Hd(n,a,r)}}function oa(e,t){return(n,a,r)=>{let s=e[n];if(!nl(s,a))throw new Error(`expected weightMap[${n}] to be a Tensor${a}D, instead have ${s}`);return t.push({originalPath:n,paramPath:r||n}),s}}function Fn(e){let t=e;function n(r){let s=t.slice(0,r);return t=t.slice(r),s}function a(){return t}return{extractWeights:n,getRemainingWeights:a}}function dg(e,t){let n=Rp(e,t),a=Mp(e,t);function r(i,o,l,u=!1){let p=u?n(i,o,3,`${l}/conv0`):a(i,o,`${l}/conv0`),d=a(o,o,`${l}/conv1`),c=a(o,o,`${l}/conv2`);return{conv0:p,conv1:d,conv2:c}}function s(i,o,l,u=!1){let{conv0:p,conv1:d,conv2:c}=r(i,o,l,u),h=a(o,o,`${l}/conv3`);return{conv0:p,conv1:d,conv2:c,conv3:h}}return{extractDenseBlock3Params:r,extractDenseBlock4Params:s}}function $$(e){let t=[],{extractWeights:n,getRemainingWeights:a}=Fn(e),{extractDenseBlock4Params:r}=dg(n,t),s=r(3,32,"dense0",!0),i=r(32,64,"dense1"),o=r(64,128,"dense2"),l=r(128,256,"dense3");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o,dense3:l}}}function hg(e){return t=>{let n=e(`${t}/filters`,4),a=e(`${t}/bias`,1);return{filters:n,bias:a}}}function mg(e,t){let n=oa(e,t),a=hg(n),r=Pp(n);function s(o,l=!1){let u=l?a(`${o}/conv0`):r(`${o}/conv0`),p=r(`${o}/conv1`),d=r(`${o}/conv2`);return{conv0:u,conv1:p,conv2:d}}function i(o,l=!1){let u=l?a(`${o}/conv0`):r(`${o}/conv0`),p=r(`${o}/conv1`),d=r(`${o}/conv2`),c=r(`${o}/conv3`);return{conv0:u,conv1:p,conv2:d,conv3:c}}return{extractDenseBlock3Params:s,extractDenseBlock4Params:i}}function D$(e){let t=[],{extractDenseBlock4Params:n}=mg(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return An(e,t),{params:a,paramMappings:t}}var Op=class extends pn{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return P(()=>{let a=se(t.toBatchTensor(112,!0),"float32"),s=Ja(a,[122.782,117.001,104.298]).div(255),i=Gd(s,n.dense0,!0);return i=Gd(i,n.dense1),i=Gd(i,n.dense2),i=Gd(i,n.dense3),i=xa(i,[7,7],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await wt(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return D$(t)}extractParams(t){return $$(t)}};function qd(e,t){return P(()=>X($e(e,t.weights),t.bias))}function R$(e,t,n){let a=[],{extractWeights:r,getRemainingWeights:s}=Fn(e),o=cg(r,a)(t,n,"fc");if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{paramMappings:a,params:{fc:o}}}function M$(e){let t=[],n=oa(e,t);function a(s){let i=n(`${s}/weights`,2),o=n(`${s}/bias`,1);return{weights:i,bias:o}}let r={fc:a("fc")};return An(e,t),{params:r,paramMappings:t}}function fg(e){let t={},n={};return Object.keys(e).forEach(a=>{let r=a.startsWith("fc")?n:t;r[a]=e[a]}),{featureExtractorMap:t,classifierMap:n}}var Lp=class extends pn{constructor(n,a){super(n);this._faceFeatureExtractor=a}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(n){let{params:a}=this;if(!a)throw new Error(`${this._name} - load model before inference`);return P(()=>{let r=n instanceof kr?this.faceFeatureExtractor.forwardInput(n):n;return qd(r.as2D(r.shape[0],-1),a.fc)})}dispose(n=!0){this.faceFeatureExtractor.dispose(n),super.dispose(n)}loadClassifierParams(n){let{params:a,paramMappings:r}=this.extractClassifierParams(n);this._params=a,this._paramMappings=r}extractClassifierParams(n){return R$(n,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(n){let{featureExtractorMap:a,classifierMap:r}=fg(n);return this.faceFeatureExtractor.loadFromWeightMap(a),M$(r)}extractParams(n){let a=this.getClassifierChannelsIn(),r=this.getClassifierChannelsOut(),s=r*a+r,i=n.slice(0,n.length-s),o=n.slice(n.length-s);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(o)}};var Ok=["neutral","happy","sad","angry","fearful","disgusted","surprised"],qr=class{constructor(t){this.neutral=0;this.happy=0;this.sad=0;this.angry=0;this.fearful=0;this.disgusted=0;this.surprised=0;if(t.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${t.length}`);Ok.forEach((n,a)=>{this[n]=t[a]})}asSortedArray(){return Ok.map(t=>({expression:t,probability:this[t]})).sort((t,n)=>n.probability-t.probability)}};var jd=class extends Lp{constructor(t=new Op){super("FaceExpressionNet",t)}forwardInput(t){return P(()=>Xa(this.runNet(t)))}async forward(t){return this.forwardInput(await wt(t))}async predictExpressions(t){let n=await wt(t),a=await this.forwardInput(n),r=await Promise.all(ct(a).map(async i=>{let o=i.dataSync();return i.dispose(),o}));a.dispose();let s=r.map(i=>new qr(i));return n.isBatchInput?s:s[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function Lk(e){return e.expressions instanceof qr}function gg(e,t){return{...e,...{expressions:t}}}function mfe(e,t,n=.1,a){(Array.isArray(t)?t:[t]).forEach(s=>{let i=s instanceof qr?s:Lk(s)?s.expressions:void 0;if(!i)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");let l=i.asSortedArray().filter(d=>d.probability>n),u=wr(s)?s.detection.box.bottomLeft:a||new Re(0,0);new Gr(l.map(d=>`${d.expression} (${al(d.probability)})`),u).draw(e)})}function hl(e){return wr(e)&&e.landmarks instanceof ia&&e.unshiftedLandmarks instanceof ia&&e.alignedRect instanceof vt}function ffe(e){let t=l=>l*180/Math.PI,n=(l,u)=>Math.sqrt((l._x-u._x)**2+(l._y-u._y)**2),a={roll:void 0,pitch:void 0,yaw:void 0},r=(l,u,p)=>{let d=Math.floor(l._x-u._x),c=Math.floor(u._x-p._x);return d-c},s=(l,u)=>{let p=Math.hypot(u._x-l._x,u._y-l._y),d=u._y-l._y,c=Math.asin(d/p),h=t(c),m=Math.floor(90-h),f=u._x-l._x<0?-1:1;return m*f},i=(l,u,p)=>{let d=n(l,p),c={_x:(l._x+p._x)/2,_y:(l._y+p._y)/2},h=n(u,c),m=Math.atan(h/d),f=Math.floor(t(m)),g=c._y-u._y<0?-1:1;return f*g};if(!e||!e._positions||e._positions.length!==68)return a;let o=e._positions;return a.roll=s(o[27],o[66]),a.pitch=i(o[14],o[30],o[2]),a.yaw=r(o[14],o[33],o[2]),a}function zp(e,t){let{box:n}=e.detection,a=t.shiftBy(n.x,n.y),r=a.align(),{imageDims:s}=e.detection,i=new vt(e.detection.score,r.rescale(s.reverse()),s),o=ffe(t);return{...e,...{landmarks:a,unshiftedLandmarks:t,alignedRect:i,angle:o}}}var bg=class{constructor(t={}){let{drawLines:n=!0,drawPoints:a=!0,lineWidth:r,lineColor:s,pointSize:i,pointColor:o}=t;this.drawLines=n,this.drawPoints=a,this.lineWidth=r||1,this.pointSize=i||2,this.lineColor=s||"rgba(0, 255, 255, 1)",this.pointColor=o||"rgba(255, 0, 255, 1)"}},yg=class{constructor(t,n={}){this.faceLandmarks=t,this.options=new bg(n)}draw(t){let n=Hn(t),{drawLines:a,drawPoints:r,lineWidth:s,lineColor:i,pointSize:o,pointColor:l}=this.options;if(a&&this.faceLandmarks instanceof ol&&(n.strokeStyle=i,n.lineWidth=s,Br(n,this.faceLandmarks.getJawOutline()),Br(n,this.faceLandmarks.getLeftEyeBrow()),Br(n,this.faceLandmarks.getRightEyeBrow()),Br(n,this.faceLandmarks.getNose()),Br(n,this.faceLandmarks.getLeftEye(),!0),Br(n,this.faceLandmarks.getRightEye(),!0),Br(n,this.faceLandmarks.getMouth(),!0)),r){n.strokeStyle=l,n.fillStyle=l;let u=p=>{n.beginPath(),n.arc(p.x,p.y,o,0,2*Math.PI),n.fill()};this.faceLandmarks.positions.forEach(u)}}};function gfe(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof ia?a:hl(a)?a.landmarks:void 0;if(!r)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new yg(r).draw(e)})}var P$="1.7.12";function xfe(e,t){let n=Rp(e,t),a=Mp(e,t);function r(i,o,l){let u=a(i,o,`${l}/separable_conv0`),p=a(o,o,`${l}/separable_conv1`),d=n(i,o,1,`${l}/expansion_conv`);return{separable_conv0:u,separable_conv1:p,expansion_conv:d}}function s(i,o){let l=a(i,i,`${o}/separable_conv0`),u=a(i,i,`${o}/separable_conv1`),p=a(i,i,`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:u,separable_conv2:p}}return{extractConvParams:n,extractSeparableConvParams:a,extractReductionBlockParams:r,extractMainBlockParams:s}}function O$(e,t){let n=[],{extractWeights:a,getRemainingWeights:r}=Fn(e),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:l}=xfe(a,n),u=s(3,32,3,"entry_flow/conv_in"),p=o(32,64,"entry_flow/reduction_block_0"),d=o(64,128,"entry_flow/reduction_block_1"),c={conv_in:u,reduction_block_0:p,reduction_block_1:d},h={};xr(t,0,1).forEach(b=>{h[`main_block_${b}`]=l(128,`middle_flow/main_block_${b}`)});let m=o(128,256,"exit_flow/reduction_block"),f=i(256,512,"exit_flow/separable_conv"),g={reduction_block:m,separable_conv:f};if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{entry_flow:c,middle_flow:h,exit_flow:g}}}function vfe(e,t){let n=oa(e,t),a=hg(n),r=Pp(n);function s(o){let l=r(`${o}/separable_conv0`),u=r(`${o}/separable_conv1`),p=a(`${o}/expansion_conv`);return{separable_conv0:l,separable_conv1:u,expansion_conv:p}}function i(o){let l=r(`${o}/separable_conv0`),u=r(`${o}/separable_conv1`),p=r(`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:u,separable_conv2:p}}return{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}}function L$(e,t){let n=[],{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}=vfe(e,n),o=a("entry_flow/conv_in"),l=s("entry_flow/reduction_block_0"),u=s("entry_flow/reduction_block_1"),p={conv_in:o,reduction_block_0:l,reduction_block_1:u},d={};xr(t,0,1).forEach(f=>{d[`main_block_${f}`]=i(`middle_flow/main_block_${f}`)});let c=s("exit_flow/reduction_block"),h=r("exit_flow/separable_conv"),m={reduction_block:c,separable_conv:h};return An(e,n),{params:{entry_flow:p,middle_flow:d,exit_flow:m},paramMappings:n}}function z$(e,t,n){return X(Rt(e,t.filters,n,"same"),t.bias)}function Wk(e,t,n=!0){let a=n?Ke(e):e;return a=qn(a,t.separable_conv0,[1,1]),a=qn(Ke(a),t.separable_conv1,[1,1]),a=Mt(a,[3,3],[2,2],"same"),a=X(a,z$(e,t.expansion_conv,[2,2])),a}function wfe(e,t){let n=qn(Ke(e),t.separable_conv0,[1,1]);return n=qn(Ke(n),t.separable_conv1,[1,1]),n=qn(Ke(n),t.separable_conv2,[1,1]),n=X(n,e),n}var xg=class extends pn{constructor(n){super("TinyXception");this._numMainBlocks=n}forwardInput(n){let{params:a}=this;if(!a)throw new Error("TinyXception - load model before inference");return P(()=>{let r=se(n.toBatchTensor(112,!0),"float32"),i=Ja(r,[122.782,117.001,104.298]).div(255),o=Ke(z$(i,a.entry_flow.conv_in,[2,2]));return o=Wk(o,a.entry_flow.reduction_block_0,!1),o=Wk(o,a.entry_flow.reduction_block_1),xr(this._numMainBlocks,0,1).forEach(l=>{o=wfe(o,a.middle_flow[`main_block_${l}`])}),o=Wk(o,a.exit_flow.reduction_block),o=Ke(qn(o,a.exit_flow.separable_conv,[1,1])),o})}async forward(n){return this.forwardInput(await wt(n))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(n){return L$(n,this._numMainBlocks)}extractParams(n){return O$(n,this._numMainBlocks)}};function W$(e){let t=[],{extractWeights:n,getRemainingWeights:a}=Fn(e),r=cg(n,t),s=r(512,1,"fc/age"),i=r(512,2,"fc/gender");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{fc:{age:s,gender:i}}}}function B$(e){let t=[],n=oa(e,t);function a(s){let i=n(`${s}/weights`,2),o=n(`${s}/bias`,1);return{weights:i,bias:o}}let r={fc:{age:a("fc/age"),gender:a("fc/gender")}};return An(e,t),{params:r,paramMappings:t}}var vg=(n=>(n.FEMALE="female",n.MALE="male",n))(vg||{});var Kd=class extends pn{constructor(n=new xg(2)){super("AgeGenderNet");this._faceFeatureExtractor=n}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(n){let{params:a}=this;if(!a)throw new Error(`${this._name} - load model before inference`);return P(()=>{let r=n instanceof kr?this.faceFeatureExtractor.forwardInput(n):n,s=xa(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1),i=qd(s,a.fc.age).as1D(),o=qd(s,a.fc.gender);return{age:i,gender:o}})}forwardInput(n){return P(()=>{let{age:a,gender:r}=this.runNet(n);return{age:a,gender:Xa(r)}})}async forward(n){return this.forwardInput(await wt(n))}async predictAgeAndGender(n){let a=await wt(n),r=await this.forwardInput(a),s=ct(r.age),i=ct(r.gender),o=s.map((u,p)=>({ageTensor:u,genderTensor:i[p]})),l=await Promise.all(o.map(async({ageTensor:u,genderTensor:p})=>{let d=u.dataSync()[0],c=p.dataSync()[0],h=c>.5,m=h?"male":"female",f=h?c:1-c;return u.dispose(),p.dispose(),{age:d,gender:m,genderProbability:f}}));return r.age.dispose(),r.gender.dispose(),a.isBatchInput?l:l[0]}getDefaultModelName(){return"age_gender_model"}dispose(n=!0){this.faceFeatureExtractor.dispose(n),super.dispose(n)}loadClassifierParams(n){let{params:a,paramMappings:r}=this.extractClassifierParams(n);this._params=a,this._paramMappings=r}extractClassifierParams(n){return W$(n)}extractParamsFromWeightMap(n){let{featureExtractorMap:a,classifierMap:r}=fg(n);return this.faceFeatureExtractor.loadFromWeightMap(a),B$(r)}extractParams(n){let r=n.slice(0,n.length-1539),s=n.slice(n.length-1539);return this.faceFeatureExtractor.extractWeights(r),this.extractClassifierParams(s)}};var Wp=class extends Lp{postProcess(t,n,a){let r=a.map(({width:i,height:o})=>{let l=n/Math.max(o,i);return{width:i*l,height:o*l}}),s=r.length;return P(()=>{let i=(d,c)=>Dt([xn([68],d,"float32"),xn([68],c,"float32")],1).as2D(1,136).as1D(),o=(d,c)=>{let{width:h,height:m}=r[d];return c(h,m)?Math.abs(h-m)/2:0},l=d=>o(d,(c,h)=>c<h),u=d=>o(d,(c,h)=>h<c);return t.mul(xn([s,136],n,"float32")).sub(Dt(Array.from(Array(s),(d,c)=>i(l(c),u(c))))).div(Dt(Array.from(Array(s),(d,c)=>i(r[c].width,r[c].height))))})}forwardInput(t){return P(()=>{let n=this.runNet(t);return this.postProcess(n,t.inputSize,t.inputDimensions.map(([a,r])=>({height:a,width:r})))})}async forward(t){return this.forwardInput(await wt(t))}async detectLandmarks(t){let n=await wt(t),a=P(()=>ct(this.forwardInput(n))),r=await Promise.all(a.map(async(s,i)=>{let o=Array.from(s.dataSync()),l=o.filter((p,d)=>rg(d)),u=o.filter((p,d)=>!rg(d));return new ol(Array(68).fill(0).map((p,d)=>new Re(l[d],u[d])),{height:n.getInputHeight(i),width:n.getInputWidth(i)})}));return a.forEach(s=>s.dispose()),n.isBatchInput?r:r[0]}getClassifierChannelsOut(){return 136}};var ml=class extends Wp{constructor(t=new Op){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function V$(e){let t=[],{extractDenseBlock3Params:n}=mg(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return An(e,t),{params:a,paramMappings:t}}function U$(e){let t=[],{extractWeights:n,getRemainingWeights:a}=Fn(e),{extractDenseBlock3Params:r}=dg(n,t),s=r(3,32,"dense0",!0),i=r(32,64,"dense1"),o=r(64,128,"dense2");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o}}}var wg=class extends pn{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return P(()=>{let a=se(t.toBatchTensor(112,!0),"float32"),s=Ja(a,[122.782,117.001,104.298]).div(255),i=pg(s,n.dense0,!0);return i=pg(i,n.dense1),i=pg(i,n.dense2),i=xa(i,[14,14],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await wt(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return V$(t)}extractParams(t){return U$(t)}};var Xd=class extends Wp{constructor(t=new wg){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var Bk=class extends ml{};function G$(e,t){return X(z(e,t.weights),t.biases)}function Vk(e,t,n,a,r="same"){let{filters:s,bias:i}=t.conv,o=Rt(e,s,n,r);return o=X(o,i),o=G$(o,t.scale),a?Ke(o):o}function H$(e,t){return Vk(e,t,[1,1],!0)}function Uk(e,t){return Vk(e,t,[1,1],!1)}function kg(e,t){return Vk(e,t,[2,2],!0,"valid")}function kfe(e,t){function n(o,l,u){let p=e(o),d=p.length/(l*u*u);if(gk(d))throw new Error(`depth has to be an integer: ${d}, weights.length: ${p.length}, numFilters: ${l}, filterSize: ${u}`);return P(()=>De(Ma(p,[l,d,u,u]),[2,3,1,0]))}function a(o,l,u,p){let d=n(o,l,u),c=je(e(l));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:d,bias:c}}function r(o,l){let u=je(e(o)),p=je(e(o));return t.push({paramPath:`${l}/weights`},{paramPath:`${l}/biases`}),{weights:u,biases:p}}function s(o,l,u,p){let d=a(o,l,u,`${p}/conv`),c=r(l,`${p}/scale`);return{conv:d,scale:c}}function i(o,l,u,p,d=!1){let c=s((d?.5:1)*o,l,u,`${p}/conv1`),h=s(o,l,u,`${p}/conv2`);return{conv1:c,conv2:h}}return{extractConvLayerParams:s,extractResidualLayerParams:i}}function q$(e){let{extractWeights:t,getRemainingWeights:n}=Fn(e),a=[],{extractConvLayerParams:r,extractResidualLayerParams:s}=kfe(t,a),i=r(4704,32,7,"conv32_down"),o=s(9216,32,3,"conv32_1"),l=s(9216,32,3,"conv32_2"),u=s(9216,32,3,"conv32_3"),p=s(36864,64,3,"conv64_down",!0),d=s(36864,64,3,"conv64_1"),c=s(36864,64,3,"conv64_2"),h=s(36864,64,3,"conv64_3"),m=s(147456,128,3,"conv128_down",!0),f=s(147456,128,3,"conv128_1"),g=s(147456,128,3,"conv128_2"),b=s(589824,256,3,"conv256_down",!0),y=s(589824,256,3,"conv256_1"),x=s(589824,256,3,"conv256_2"),v=s(589824,256,3,"conv256_down_out"),I=P(()=>De($a(t(256*128),[128,256]),[1,0]));if(a.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{conv32_down:i,conv32_1:o,conv32_2:l,conv32_3:u,conv64_down:p,conv64_1:d,conv64_2:c,conv64_3:h,conv128_down:m,conv128_1:f,conv128_2:g,conv256_down:b,conv256_1:y,conv256_2:x,conv256_down_out:v,fc:I},paramMappings:a}}function Ife(e,t){let n=oa(e,t);function a(i){let o=n(`${i}/scale/weights`,1),l=n(`${i}/scale/biases`,1);return{weights:o,biases:l}}function r(i){let o=n(`${i}/conv/filters`,4),l=n(`${i}/conv/bias`,1),u=a(i);return{conv:{filters:o,bias:l},scale:u}}function s(i){return{conv1:r(`${i}/conv1`),conv2:r(`${i}/conv2`)}}return{extractConvLayerParams:r,extractResidualLayerParams:s}}function j$(e){let t=[],{extractConvLayerParams:n,extractResidualLayerParams:a}=Ife(e,t),r=n("conv32_down"),s=a("conv32_1"),i=a("conv32_2"),o=a("conv32_3"),l=a("conv64_down"),u=a("conv64_1"),p=a("conv64_2"),d=a("conv64_3"),c=a("conv128_down"),h=a("conv128_1"),m=a("conv128_2"),f=a("conv256_down"),g=a("conv256_1"),b=a("conv256_2"),y=a("conv256_down_out"),{fc:x}=e;if(t.push({originalPath:"fc",paramPath:"fc"}),!fk(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);let v={conv32_down:r,conv32_1:s,conv32_2:i,conv32_3:o,conv64_down:l,conv64_1:u,conv64_2:p,conv64_3:d,conv128_down:c,conv128_1:h,conv128_2:m,conv256_down:f,conv256_1:g,conv256_2:b,conv256_down_out:y,fc:x};return An(e,t),{params:v,paramMappings:t}}function Qa(e,t){let n=H$(e,t.conv1);return n=Uk(n,t.conv2),n=X(n,e),n=Ke(n),n}function Yd(e,t){let n=kg(e,t.conv1);n=Uk(n,t.conv2);let a=xa(e,2,2,"valid"),r=Nt(a.shape),s=a.shape[3]!==n.shape[3];if(a.shape[1]!==n.shape[1]||a.shape[2]!==n.shape[2]){let o=[...n.shape];o[1]=1;let l=Nt(o);n=et([n,l],1);let u=[...n.shape];u[2]=1;let p=Nt(u);n=et([n,p],2)}return a=s?et([a,r],3):a,n=X(a,n),n=Ke(n),n}var fl=class extends pn{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return P(()=>{let a=se(t.toBatchTensor(150,!0),"float32"),s=Ja(a,[122.782,117.001,104.298]).div(255),i=kg(s,n.conv32_down);i=Mt(i,3,2,"valid"),i=Qa(i,n.conv32_1),i=Qa(i,n.conv32_2),i=Qa(i,n.conv32_3),i=Yd(i,n.conv64_down),i=Qa(i,n.conv64_1),i=Qa(i,n.conv64_2),i=Qa(i,n.conv64_3),i=Yd(i,n.conv128_down),i=Qa(i,n.conv128_1),i=Qa(i,n.conv128_2),i=Yd(i,n.conv256_down),i=Qa(i,n.conv256_1),i=Qa(i,n.conv256_2),i=Yd(i,n.conv256_down_out);let o=i.mean([1,2]);return $e(o,n.fc)})}async forward(t){return this.forwardInput(await wt(t))}async computeFaceDescriptor(t){var s;if((s=t==null?void 0:t.shape)!=null&&s.some(i=>i<=0))return new Float32Array(128);let n=await wt(t),a=P(()=>ct(this.forwardInput(n))),r=await Promise.all(a.map(i=>i.data()));return a.forEach(i=>i.dispose()),n.isBatchInput?r:r[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeightMap(t){return j$(t)}extractParams(t){return q$(t)}};function Sfe(e){let t=new fl;return t.extractWeights(e),t}function Ig(e,t){return{...e,...{descriptor:t}}}function Nfe(e){return typeof e.age=="number"}function Sg(e,t){return{...e,...{age:t}}}function Tfe(e){return(e.gender==="male"||e.gender==="female")&&_p(e.genderProbability)}function Ng(e,t,n){return{...e,...{gender:t,genderProbability:n}}}function Cfe(e,t){function n(l,u){let p=Ma(e(9*l),[3,3,l,1]),d=je(e(l)),c=je(e(l)),h=je(e(l)),m=je(e(l));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/batch_norm_scale`},{paramPath:`${u}/batch_norm_offset`},{paramPath:`${u}/batch_norm_mean`},{paramPath:`${u}/batch_norm_variance`}),{filters:p,batch_norm_scale:d,batch_norm_offset:c,batch_norm_mean:h,batch_norm_variance:m}}function a(l,u,p,d,c){let h=Ma(e(l*u*p*p),[p,p,l,u]),m=je(e(u));return t.push({paramPath:`${d}/filters`},{paramPath:`${d}/${c?"batch_norm_offset":"bias"}`}),{filters:h,bias:m}}function r(l,u,p,d){let{filters:c,bias:h}=a(l,u,p,d,!0);return{filters:c,batch_norm_offset:h}}function s(l,u,p){let d=n(l,`${p}/depthwise_conv`),c=r(l,u,1,`${p}/pointwise_conv`);return{depthwise_conv:d,pointwise_conv:c}}function i(){let l=r(3,32,3,"mobilenetv1/conv_0"),u=s(32,64,"mobilenetv1/conv_1"),p=s(64,128,"mobilenetv1/conv_2"),d=s(128,128,"mobilenetv1/conv_3"),c=s(128,256,"mobilenetv1/conv_4"),h=s(256,256,"mobilenetv1/conv_5"),m=s(256,512,"mobilenetv1/conv_6"),f=s(512,512,"mobilenetv1/conv_7"),g=s(512,512,"mobilenetv1/conv_8"),b=s(512,512,"mobilenetv1/conv_9"),y=s(512,512,"mobilenetv1/conv_10"),x=s(512,512,"mobilenetv1/conv_11"),v=s(512,1024,"mobilenetv1/conv_12"),I=s(1024,1024,"mobilenetv1/conv_13");return{conv_0:l,conv_1:u,conv_2:p,conv_3:d,conv_4:c,conv_5:h,conv_6:m,conv_7:f,conv_8:g,conv_9:b,conv_10:y,conv_11:x,conv_12:v,conv_13:I}}function o(){let l=r(1024,256,1,"prediction_layer/conv_0"),u=r(256,512,3,"prediction_layer/conv_1"),p=r(512,128,1,"prediction_layer/conv_2"),d=r(128,256,3,"prediction_layer/conv_3"),c=r(256,128,1,"prediction_layer/conv_4"),h=r(128,256,3,"prediction_layer/conv_5"),m=r(256,64,1,"prediction_layer/conv_6"),f=r(64,128,3,"prediction_layer/conv_7"),g=a(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),b=a(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),y=a(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),x=a(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),v=a(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),I=a(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),T=a(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),C=a(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),E=a(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),F=a(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),D=a(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),$=a(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:l,conv_1:u,conv_2:p,conv_3:d,conv_4:c,conv_5:h,conv_6:m,conv_7:f,box_predictor_0:{box_encoding_predictor:g,class_predictor:b},box_predictor_1:{box_encoding_predictor:y,class_predictor:x},box_predictor_2:{box_encoding_predictor:v,class_predictor:I},box_predictor_3:{box_encoding_predictor:T,class_predictor:C},box_predictor_4:{box_encoding_predictor:E,class_predictor:F},box_predictor_5:{box_encoding_predictor:D,class_predictor:$}}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:o}}function K$(e){let t=[],{extractWeights:n,getRemainingWeights:a}=Fn(e),{extractMobilenetV1Params:r,extractPredictionLayerParams:s}=Cfe(n,t),i=r(),o=s(),u={extra_dim:kd(n(5118*4),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{params:{mobilenetv1:i,prediction_layer:o,output_layer:u},paramMappings:t}}function _fe(e,t){let n=oa(e,t);function a(u,p,d){let c=n(`${u}/Conv2d_${p}_pointwise/weights`,4,`${d}/filters`),h=n(`${u}/Conv2d_${p}_pointwise/convolution_bn_offset`,1,`${d}/batch_norm_offset`);return{filters:c,batch_norm_offset:h}}function r(u){let p=`mobilenetv1/conv_${u}`,d=`MobilenetV1/Conv2d_${u}_depthwise`,c=`${p}/depthwise_conv`,h=`${p}/pointwise_conv`,m=n(`${d}/depthwise_weights`,4,`${c}/filters`),f=n(`${d}/BatchNorm/gamma`,1,`${c}/batch_norm_scale`),g=n(`${d}/BatchNorm/beta`,1,`${c}/batch_norm_offset`),b=n(`${d}/BatchNorm/moving_mean`,1,`${c}/batch_norm_mean`),y=n(`${d}/BatchNorm/moving_variance`,1,`${c}/batch_norm_variance`);return{depthwise_conv:{filters:m,batch_norm_scale:f,batch_norm_offset:g,batch_norm_mean:b,batch_norm_variance:y},pointwise_conv:a("MobilenetV1",u,h)}}function s(){return{conv_0:a("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:r(1),conv_2:r(2),conv_3:r(3),conv_4:r(4),conv_5:r(5),conv_6:r(6),conv_7:r(7),conv_8:r(8),conv_9:r(9),conv_10:r(10),conv_11:r(11),conv_12:r(12),conv_13:r(13)}}function i(u,p){let d=n(`${u}/weights`,4,`${p}/filters`),c=n(`${u}/biases`,1,`${p}/bias`);return{filters:d,bias:c}}function o(u){let p=i(`Prediction/BoxPredictor_${u}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${u}/box_encoding_predictor`),d=i(`Prediction/BoxPredictor_${u}/ClassPredictor`,`prediction_layer/box_predictor_${u}/class_predictor`);return{box_encoding_predictor:p,class_predictor:d}}function l(){return{conv_0:a("Prediction",0,"prediction_layer/conv_0"),conv_1:a("Prediction",1,"prediction_layer/conv_1"),conv_2:a("Prediction",2,"prediction_layer/conv_2"),conv_3:a("Prediction",3,"prediction_layer/conv_3"),conv_4:a("Prediction",4,"prediction_layer/conv_4"),conv_5:a("Prediction",5,"prediction_layer/conv_5"),conv_6:a("Prediction",6,"prediction_layer/conv_6"),conv_7:a("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:o(0),box_predictor_1:o(1),box_predictor_2:o(2),box_predictor_3:o(3),box_predictor_4:o(4),box_predictor_5:o(5)}}return{extractMobilenetV1Params:s,extractPredictionLayerParams:l}}function X$(e){let t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:a}=_fe(e,t),r=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Vr(r))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${r}`);let s={mobilenetv1:n(),prediction_layer:a(),output_layer:{extra_dim:r}};return An(e,t),{params:s,paramMappings:t}}function La(e,t,n){return P(()=>{let a=Rt(e,t.filters,n,"same");return a=X(a,t.batch_norm_offset),sn(a,0,6)})}var Efe=.0010000000474974513;function Afe(e,t,n){return P(()=>{let a=Es(e,t.filters,n,"same");return a=_s(a,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Efe),sn(a,0,6)})}function Ffe(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function Y$(e,t){return P(()=>{let n,a=La(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach((s,i)=>{let o=i+1,l=Ffe(o);a=Afe(a,s.depthwise_conv,l),a=La(a,s.pointwise_conv,[1,1]),o===11&&(n=a)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:a,conv11:n}})}function $fe(e,t,n){let a=e.arraySync(),r=Math.min(a[t][0],a[t][2]),s=Math.min(a[t][1],a[t][3]),i=Math.max(a[t][0],a[t][2]),o=Math.max(a[t][1],a[t][3]),l=Math.min(a[n][0],a[n][2]),u=Math.min(a[n][1],a[n][3]),p=Math.max(a[n][0],a[n][2]),d=Math.max(a[n][1],a[n][3]),c=(i-r)*(o-s),h=(p-l)*(d-u);if(c<=0||h<=0)return 0;let m=Math.max(r,l),f=Math.max(s,u),g=Math.min(i,p),b=Math.min(o,d),y=Math.max(g-m,0)*Math.max(b-f,0);return y/(c+h-y)}function Z$(e,t,n,a,r){let s=e.shape[0],i=Math.min(n,s),o=t.map((p,d)=>({score:p,boxIndex:d})).filter(p=>p.score>r).sort((p,d)=>d.score-p.score),l=p=>p<=a?1:0,u=[];return o.forEach(p=>{if(u.length>=i)return;let d=p.score;for(let c=u.length-1;c>=0;--c){let h=$fe(e,p.boxIndex,u[c]);if(h!==0&&(p.score*=l(h),p.score<=r))break}d===p.score&&u.push(p.boxIndex)}),u}function Dfe(e){let t=ct(De(e,[1,0])),n=[pe(t[2],t[0]),pe(t[3],t[1])],a=[X(t[0],he(n[0],2)),X(t[1],he(n[1],2))];return{sizes:n,centers:a}}function Rfe(e,t){let{sizes:n,centers:a}=Dfe(e),r=ct(De(t,[1,0])),s=he(z(yn(he(r[2],5)),n[0]),2),i=X(z(he(r[0],10),n[0]),a[0]),o=he(z(yn(he(r[3],5)),n[1]),2),l=X(z(he(r[1],10),n[1]),a[1]);return De(Dt([pe(i,s),pe(l,o),X(i,s),X(l,o)]),[1,0])}function J$(e,t,n){return P(()=>{let a=e.shape[0],r=Rfe(W(Ln(n.extra_dim,[a,1,1]),[-1,4]),W(e,[-1,4]));r=W(r,[a,r.shape[0]/a,4]);let s=fa(Ue(t,[0,0,1],[-1,-1,-1])),i=Ue(s,[0,0,0],[-1,-1,1]);i=W(i,[a,i.shape[1]]);let o=ct(r),l=ct(i);return{boxes:o,scores:l}})}function gl(e,t){return P(()=>{let n=e.shape[0],a=W(dl(e,t.box_encoding_predictor),[n,-1,1,4]),r=W(dl(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:a,classPrediction:r}})}function Q$(e,t,n){return P(()=>{let a=La(e,n.conv_0,[1,1]),r=La(a,n.conv_1,[2,2]),s=La(r,n.conv_2,[1,1]),i=La(s,n.conv_3,[2,2]),o=La(i,n.conv_4,[1,1]),l=La(o,n.conv_5,[2,2]),u=La(l,n.conv_6,[1,1]),p=La(u,n.conv_7,[2,2]),d=gl(t,n.box_predictor_0),c=gl(e,n.box_predictor_1),h=gl(r,n.box_predictor_2),m=gl(i,n.box_predictor_3),f=gl(l,n.box_predictor_4),g=gl(p,n.box_predictor_5),b=et([d.boxPredictionEncoding,c.boxPredictionEncoding,h.boxPredictionEncoding,m.boxPredictionEncoding,f.boxPredictionEncoding,g.boxPredictionEncoding],1),y=et([d.classPrediction,c.classPrediction,h.classPrediction,m.classPrediction,f.classPrediction,g.classPrediction],1);return{boxPredictions:b,classPredictions:y}})}var Ia=class{constructor({minConfidence:t,maxResults:n}={}){this._name="SsdMobilenetv1Options";if(this._minConfidence=t||.5,this._maxResults=n||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}};var Ls=class extends pn{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return P(()=>{let a=se(t.toBatchTensor(512,!1),"float32"),r=pe(he(a,127.5),1),s=Y$(r,n.mobilenetv1),{boxPredictions:i,classPredictions:o}=Q$(s.out,s.conv11,n.prediction_layer);return J$(i,o,n.output_layer)})}async forward(t){return this.forwardInput(await wt(t))}async locateFaces(t,n={}){let{maxResults:a,minConfidence:r}=new Ia(n),s=await wt(t),{boxes:i,scores:o}=this.forwardInput(s),l=i[0],u=o[0];for(let x=1;x<i.length;x++)i[x].dispose(),o[x].dispose();let p=Array.from(u.dataSync()),c=Z$(l,p,a,.5,r),h=s.getReshapedInputDimensions(0),m=s.inputSize,f=m/h.width,g=m/h.height,b=l.arraySync(),y=c.map(x=>{let[v,I]=[Math.max(0,b[x][0]),Math.min(1,b[x][2])].map(E=>E*g),[T,C]=[Math.max(0,b[x][1]),Math.min(1,b[x][3])].map(E=>E*f);return new vt(p[x],new il(T,v,C-T,I-v),{height:s.getInputHeight(0),width:s.getInputWidth(0)})});return l.dispose(),u.dispose(),y}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(t){return X$(t)}extractParams(t){return K$(t)}};function eD(e){let t=new Ls;return t.extractWeights(e),t}function Mfe(e){return eD(e)}var Gk=class extends Ls{};var tD=.4,nD=[new Re(.738768,.874946),new Re(2.42204,2.65704),new Re(4.30971,7.04493),new Re(10.246,4.59428),new Re(12.6868,11.8741)],aD=[new Re(1.603231,2.094468),new Re(6.041143,7.080126),new Re(2.882459,3.518061),new Re(4.266906,5.178857),new Re(9.041765,10.66308)],rD=[117.001,114.697,97.404],sD="tiny_yolov2_model",iD="tiny_yolov2_separable_conv_model";var Tg=e=>typeof e=="number";function Hk(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!Tg(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${e.iouThreshold}`);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(e.classes)}`);if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(t=>t||{}).every(t=>Tg(t.x)&&Tg(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(e.anchors)}`);if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(Tg)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Bp(e){return P(()=>{let t=z(e,ve(.10000000149011612));return X(Ke(pe(e,t)),t)})}function jr(e,t){return P(()=>{let n=va(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Rt(n,t.conv.filters,[1,1],"valid"),n=pe(n,t.bn.sub),n=z(n,t.bn.truediv),n=X(n,t.conv.bias),Bp(n)})}function Kr(e,t){return P(()=>{let n=va(e,[[0,0],[1,1],[1,1],[0,0]]);return n=$s(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=X(n,t.bias),Bp(n)})}function Pfe(e,t){let n=Rp(e,t);function a(i,o){let l=je(e(i)),u=je(e(i));return t.push({paramPath:`${o}/sub`},{paramPath:`${o}/truediv`}),{sub:l,truediv:u}}function r(i,o,l){let u=n(i,o,3,`${l}/conv`),p=a(o,`${l}/bn`);return{conv:u,bn:p}}let s=Mp(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}}function oD(e,t,n,a){let{extractWeights:r,getRemainingWeights:s}=Fn(e),i=[],{extractConvParams:o,extractConvWithBatchNormParams:l,extractSeparableConvParams:u}=Pfe(r,i),p;if(t.withSeparableConvs){let[d,c,h,m,f,g,b,y,x]=a,v=t.isFirstLayerConv2d?o(d,c,3,"conv0"):u(d,c,"conv0"),I=u(c,h,"conv1"),T=u(h,m,"conv2"),C=u(m,f,"conv3"),E=u(f,g,"conv4"),F=u(g,b,"conv5"),D=y?u(b,y,"conv6"):void 0,$=x?u(y,x,"conv7"):void 0,S=o(x||y||b,5*n,1,"conv8");p={conv0:v,conv1:I,conv2:T,conv3:C,conv4:E,conv5:F,conv6:D,conv7:$,conv8:S}}else{let[d,c,h,m,f,g,b,y,x]=a,v=l(d,c,"conv0"),I=l(c,h,"conv1"),T=l(h,m,"conv2"),C=l(m,f,"conv3"),E=l(f,g,"conv4"),F=l(g,b,"conv5"),D=l(b,y,"conv6"),$=l(y,x,"conv7"),S=o(x,5*n,1,"conv8");p={conv0:v,conv1:I,conv2:T,conv3:C,conv4:E,conv5:F,conv6:D,conv7:$,conv8:S}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:p,paramMappings:i}}function Ofe(e,t){let n=oa(e,t);function a(o){let l=n(`${o}/sub`,1),u=n(`${o}/truediv`,1);return{sub:l,truediv:u}}function r(o){let l=n(`${o}/filters`,4),u=n(`${o}/bias`,1);return{filters:l,bias:u}}function s(o){let l=r(`${o}/conv`),u=a(`${o}/bn`);return{conv:l,bn:u}}let i=Pp(n);return{extractConvParams:r,extractConvWithBatchNormParams:s,extractSeparableConvParams:i}}function lD(e,t){let n=[],{extractConvParams:a,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}=Ofe(e,n),i;if(t.withSeparableConvs){let o=t.filterSizes&&t.filterSizes.length||9;i={conv0:t.isFirstLayerConv2d?a("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:o>7?s("conv6"):void 0,conv7:o>8?s("conv7"):void 0,conv8:a("conv8")}}else i={conv0:r("conv0"),conv1:r("conv1"),conv2:r("conv2"),conv3:r("conv3"),conv4:r("conv4"),conv5:r("conv5"),conv6:r("conv6"),conv7:r("conv7"),conv8:a("conv8")};return An(e,n),{params:i,paramMappings:n}}var er=class{constructor({inputSize:t,scoreThreshold:n}={}){this._name="TinyYolov2Options";if(this._inputSize=t||416,this._scoreThreshold=n||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}};var qk=class extends pn{constructor(n){super("TinyYolov2");Hk(n),this._config=n}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(n,a){let r=jr(n,a.conv0);return r=Mt(r,[2,2],[2,2],"same"),r=jr(r,a.conv1),r=Mt(r,[2,2],[2,2],"same"),r=jr(r,a.conv2),r=Mt(r,[2,2],[2,2],"same"),r=jr(r,a.conv3),r=Mt(r,[2,2],[2,2],"same"),r=jr(r,a.conv4),r=Mt(r,[2,2],[2,2],"same"),r=jr(r,a.conv5),r=Mt(r,[2,2],[1,1],"same"),r=jr(r,a.conv6),r=jr(r,a.conv7),dl(r,a.conv8,"valid",!1)}runMobilenet(n,a){let r=this.config.isFirstLayerConv2d?Bp(dl(n,a.conv0,"valid",!1)):Kr(n,a.conv0);return r=Mt(r,[2,2],[2,2],"same"),r=Kr(r,a.conv1),r=Mt(r,[2,2],[2,2],"same"),r=Kr(r,a.conv2),r=Mt(r,[2,2],[2,2],"same"),r=Kr(r,a.conv3),r=Mt(r,[2,2],[2,2],"same"),r=Kr(r,a.conv4),r=Mt(r,[2,2],[2,2],"same"),r=Kr(r,a.conv5),r=Mt(r,[2,2],[1,1],"same"),r=a.conv6?Kr(r,a.conv6):r,r=a.conv7?Kr(r,a.conv7):r,dl(r,a.conv8,"valid",!1)}forwardInput(n,a){let{params:r}=this;if(!r)throw new Error("TinyYolov2 - load model before inference");return P(()=>{let s=se(n.toBatchTensor(a,!1),"float32");return s=this.config.meanRgb?Ja(s,this.config.meanRgb):s,s=s.div(255),this.config.withSeparableConvs?this.runMobilenet(s,r):this.runTinyYolov2(s,r)})}async forward(n,a){return this.forwardInput(await wt(n),a)}async detect(n,a={}){let{inputSize:r,scoreThreshold:s}=new er(a),i=await wt(n),o=await this.forwardInput(i,r),l=P(()=>ct(o)[0].expandDims()),u={width:i.getInputWidth(0),height:i.getInputHeight(0)},p=await this.extractBoxes(l,i.getReshapedInputDimensions(0),s);o.dispose(),l.dispose();let d=p.map(b=>b.box),c=p.map(b=>b.score),h=p.map(b=>b.classScore),m=p.map(b=>this.config.classes[b.label]);return wk(d.map(b=>b.rescale(r)),c,this.config.iouThreshold,!0).map(b=>new Ur(c[b],h[b],m[b],d[b],u))}getDefaultModelName(){return""}extractParamsFromWeightMap(n){return lD(n,this.config)}extractParams(n){let a=this.config.filterSizes||qk.DEFAULT_FILTER_SIZES,r=a?a.length:void 0;if(r!==7&&r!==8&&r!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${r} filterSizes in config`);return oD(n,this.config,this.boxEncodingSize,a)}async extractBoxes(n,a,r){let{width:s,height:i}=a,o=Math.max(s,i),l=o/s,u=o/i,p=n.shape[1],d=this.config.anchors.length,[c,h,m]=P(()=>{let y=n.reshape([p,p,d,this.boxEncodingSize]),x=y.slice([0,0,0,0],[p,p,d,4]),v=y.slice([0,0,0,4],[p,p,d,1]),I=this.withClassScores?Xa(y.slice([0,0,0,5],[p,p,d,this.config.classes.length]),3):ve(0);return[x,v,I]}),f=[],g=await h.array(),b=await c.array();for(let y=0;y<p;y++)for(let x=0;x<p;x++)for(let v=0;v<d;v++){let I=zd(g[y][x][v][0]);if(!r||I>r){let T=(x+zd(b[y][x][v][0]))/p*l,C=(y+zd(b[y][x][v][1]))/p*u,E=Math.exp(b[y][x][v][2])*this.config.anchors[v].x/p*l,F=Math.exp(b[y][x][v][3])*this.config.anchors[v].y/p*u,D=T-E/2,$=C-F/2,S={row:y,col:x,anchor:v},{classScore:M,label:B}=this.withClassScores?await this.extractPredictedClass(m,S):{classScore:1,label:0};f.push({box:new sl(D,$,D+E,$+F),score:I,classScore:I*M,label:B,...S})}}return c.dispose(),h.dispose(),m.dispose(),f}async extractPredictedClass(n,a){let{row:r,col:s,anchor:i}=a,o=await n.array();return Array(this.config.classes.length).fill(0).map((l,u)=>o[r][s][i][u]).map((l,u)=>({classScore:l,label:u})).reduce((l,u)=>l.classScore>u.classScore?l:u)}},bl=qk;bl.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var yl=class extends bl{constructor(t=!0){let n={withSeparableConvs:t,iouThreshold:tD,classes:["face"],...t?{anchors:aD,meanRgb:rD}:{anchors:nD,withClassScores:!0}};super(n)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(t,n){return(await this.detect(t,n)).map(r=>new vt(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?iD:sD}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function Lfe(e,t=!0){let n=new yl(t);return n.extractWeights(e),n}var Zd=class extends er{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}};var Sa=class{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};async function xl(e,t,n,a,r=({alignedRect:s})=>s){let s=e.map(l=>hl(l)?r(l):l.detection),i=a||(t instanceof Te?await Dp(t,s):await $p(t,s)),o=await n(i);return i.forEach(l=>l instanceof Te&&l.dispose()),o}async function Vp(e,t,n,a,r){return xl([e],t,async s=>n(s[0]),a,r)}var uD=.4,pD=[new Re(1.603231,2.094468),new Re(6.041143,7.080126),new Re(2.882459,3.518061),new Re(4.266906,5.178857),new Re(9.041765,10.66308)],cD=[117.001,114.697,97.404];var vl=class extends bl{constructor(){let t={withSeparableConvs:!0,iouThreshold:uD,classes:["face"],anchors:pD,meanRgb:cD,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(t)}get anchors(){return this.config.anchors}async locateFaces(t,n){return(await this.detect(t,n)).map(r=>new vt(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};var nt={ssdMobilenetv1:new Ls,tinyFaceDetector:new vl,tinyYolov2:new yl,faceLandmark68Net:new ml,faceLandmark68TinyNet:new Xd,faceRecognitionNet:new fl,faceExpressionNet:new jd,ageGenderNet:new Kd},dD=(e,t)=>nt.ssdMobilenetv1.locateFaces(e,t),zfe=(e,t)=>nt.tinyFaceDetector.locateFaces(e,t),Wfe=(e,t)=>nt.tinyYolov2.locateFaces(e,t),hD=e=>nt.faceLandmark68Net.detectLandmarks(e),Bfe=e=>nt.faceLandmark68TinyNet.detectLandmarks(e),Vfe=e=>nt.faceRecognitionNet.computeFaceDescriptor(e),Ufe=e=>nt.faceExpressionNet.predictExpressions(e),Gfe=e=>nt.ageGenderNet.predictAgeAndGender(e),mD=e=>nt.ssdMobilenetv1.load(e),Hfe=e=>nt.tinyFaceDetector.load(e),qfe=e=>nt.tinyYolov2.load(e),jfe=e=>nt.faceLandmark68Net.load(e),Kfe=e=>nt.faceLandmark68TinyNet.load(e),Xfe=e=>nt.faceRecognitionNet.load(e),Yfe=e=>nt.faceExpressionNet.load(e),Zfe=e=>nt.ageGenderNet.load(e),Jfe=mD,Qfe=dD,ege=hD;var Cg=class extends Sa{constructor(n,a,r){super();this.parentTask=n;this.input=a;this.extractedFaces=r}},wl=class extends Cg{async run(){let t=await this.parentTask,n=await xl(t,this.input,async a=>Promise.all(a.map(r=>nt.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return t.map((a,r)=>gg(a,n[r]))}withAgeAndGender(){return new Il(this,this.input)}},kl=class extends Cg{async run(){let t=await this.parentTask;if(!t)return;let n=await Vp(t,this.input,a=>nt.faceExpressionNet.predictExpressions(a),this.extractedFaces);return gg(t,n)}withAgeAndGender(){return new Sl(this,this.input)}},zs=class extends wl{withAgeAndGender(){return new Bs(this,this.input)}withFaceDescriptors(){return new Xr(this,this.input)}},Ws=class extends kl{withAgeAndGender(){return new Vs(this,this.input)}withFaceDescriptor(){return new Yr(this,this.input)}};var _g=class extends Sa{constructor(n,a,r){super();this.parentTask=n;this.input=a;this.extractedFaces=r}},Il=class extends _g{async run(){let t=await this.parentTask,n=await xl(t,this.input,async a=>Promise.all(a.map(r=>nt.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return t.map((a,r)=>{let{age:s,gender:i,genderProbability:o}=n[r];return Sg(Ng(a,i,o),s)})}withFaceExpressions(){return new wl(this,this.input)}},Sl=class extends _g{async run(){let t=await this.parentTask;if(!t)return;let{age:n,gender:a,genderProbability:r}=await Vp(t,this.input,s=>nt.ageGenderNet.predictAgeAndGender(s),this.extractedFaces);return Sg(Ng(t,a,r),n)}withFaceExpressions(){return new kl(this,this.input)}},Bs=class extends Il{withFaceExpressions(){return new zs(this,this.input)}withFaceDescriptors(){return new Xr(this,this.input)}},Vs=class extends Sl{withFaceExpressions(){return new Ws(this,this.input)}withFaceDescriptor(){return new Yr(this,this.input)}};var Jd=class extends Sa{constructor(n,a){super();this.parentTask=n;this.input=a}},Xr=class extends Jd{async run(){let t=await this.parentTask;return(await xl(t,this.input,a=>Promise.all(a.map(r=>nt.faceRecognitionNet.computeFaceDescriptor(r))),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}))).map((a,r)=>Ig(t[r],a))}withFaceExpressions(){return new zs(this,this.input)}withAgeAndGender(){return new Bs(this,this.input)}},Yr=class extends Jd{async run(){let t=await this.parentTask;if(!t)return;let n=await Vp(t,this.input,a=>nt.faceRecognitionNet.computeFaceDescriptor(a),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}));return Ig(t,n)}withFaceExpressions(){return new Ws(this,this.input)}withAgeAndGender(){return new Vs(this,this.input)}};var Qd=class extends Sa{constructor(n,a,r){super();this.parentTask=n;this.input=a;this.useTinyLandmarkNet=r}get landmarkNet(){return this.useTinyLandmarkNet?nt.faceLandmark68TinyNet:nt.faceLandmark68Net}},eh=class extends Qd{async run(){let t=await this.parentTask,n=t.map(i=>i.detection),a=this.input instanceof Te?await Dp(this.input,n):await $p(this.input,n),r=await Promise.all(a.map(i=>this.landmarkNet.detectLandmarks(i)));return a.forEach(i=>i instanceof Te&&i.dispose()),t.filter((i,o)=>r[o]).map((i,o)=>zp(i,r[o]))}withFaceExpressions(){return new zs(this,this.input)}withAgeAndGender(){return new Bs(this,this.input)}withFaceDescriptors(){return new Xr(this,this.input)}},th=class extends Qd{async run(){let t=await this.parentTask;if(!t)return;let{detection:n}=t,a=this.input instanceof Te?await Dp(this.input,[n]):await $p(this.input,[n]),r=await this.landmarkNet.detectLandmarks(a[0]);return a.forEach(s=>s instanceof Te&&s.dispose()),zp(t,r)}withFaceExpressions(){return new Ws(this,this.input)}withAgeAndGender(){return new Vs(this,this.input)}withFaceDescriptor(){return new Yr(this,this.input)}};var nh=class extends Sa{constructor(n,a=new Ia){super();this.input=n;this.options=a}},Up=class extends nh{async run(){let{input:t,options:n}=this,a;if(n instanceof Zd)a=nt.tinyFaceDetector.locateFaces(t,n);else if(n instanceof Ia)a=nt.ssdMobilenetv1.locateFaces(t,n);else if(n instanceof er)a=nt.tinyYolov2.locateFaces(t,n);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return a}runAndExtendWithFaceDetections(){return new Promise((t,n)=>{this.run().then(a=>t(a.map(r=>ll({},r)))).catch(a=>n(a))})}withFaceLandmarks(t=!1){return new eh(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new wl(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Il(this.runAndExtendWithFaceDetections(),this.input)}},ah=class extends nh{async run(){let t=await new Up(this.input,this.options),n=t[0];return t.forEach(a=>{a.score>n.score&&(n=a)}),n}runAndExtendWithFaceDetection(){return new Promise(async t=>{let n=await this.run();t(n?ll({},n):void 0)})}withFaceLandmarks(t=!1){return new th(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new kl(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Sl(this.runAndExtendWithFaceDetection(),this.input)}};function tge(e,t=new Ia){return new ah(e,t)}function Eg(e,t=new Ia){return new Up(e,t)}async function fD(e,t){return Eg(e,new Ia(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function nge(e,t={}){return Eg(e,new er(t)).withFaceLandmarks().withFaceDescriptors()}var age=fD;function jk(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");let n=Array.from(e),a=Array.from(t);return Math.sqrt(n.map((r,s)=>r-a[s]).reduce((r,s)=>r+s*s,0))}var rh=class{constructor(t,n=.6){this._distanceThreshold=n;let a=Array.isArray(t)?t:[t];if(!a.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let r=1,s=()=>`person ${r++}`;this._labeledDescriptors=a.map(i=>{if(i instanceof vr)return i;if(i instanceof Float32Array)return new vr(s(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new vr(s(),[i.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(t,n){return n.map(a=>jk(a,t)).reduce((a,r)=>a+r,0)/(n.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:n,label:a})=>new Ep(a,this.computeMeanDistance(t,n))).reduce((n,a)=>n.distance<a.distance?n:a)}findBestMatch(t){let n=this.matchDescriptor(t);return n.distance<this._distanceThreshold?n:new Ep("unknown",n.distance)}toJSON(){return{distanceThreshold:this._distanceThreshold,labeledDescriptors:this._labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let n=t.labeledDescriptors.map(a=>vr.fromJSON(a));return new rh(n,t.distanceThreshold)}};function rge(e){let t=new vl;return t.extractWeights(e),t}function gD(e,t){let{width:n,height:a}=new wn(t.width,t.height);if(n<=0||a<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:a})}`);if(Array.isArray(e))return e.map(r=>gD(r,{width:n,height:a}));if(hl(e)){let r=e.detection.forSize(n,a),s=e.unshiftedLandmarks.forSize(r.box.width,r.box.height);return zp(ll(e,r),s)}return wr(e)?ll(e,e.detection.forSize(n,a)):e instanceof ia||e instanceof vt?e.forSize(n,a):e}var sge=P$;return tR(ige);})();