megenginelite-sys 1.8.2

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

from ..core import _config
from ..core._imperative_rt.core2 import Const, apply, dtype_promotion
from ..core._imperative_rt.ops import SubgraphBuilder as _SubgraphBuilder
from ..core._imperative_rt.ops import get_global_rng_seed as _get_global_rng_seed
from ..core.ops import builtin
from ..core.ops.builtin import (
    BatchNorm,
    Dimshuffle,
    Dropout,
    Elemwise,
    GetVarShape,
    Identity,
    Reduce,
    Reshape,
    TypeCvt,
)
from ..core.tensor import amp, megbrain_graph
from ..core.tensor.array_method import _elwise_apply
from ..core.tensor.utils import (
    astensor1d,
    cast_tensors,
    convert_single_value,
    make_shape_tuple,
    subgraph,
    subgraph_fn,
)
from ..device import get_default_device
from ..distributed import WORLD, is_distributed
from ..jit import exclude_from_trace
from ..tensor import Tensor
from ..utils.deprecation import deprecated_func
from .debug_param import get_execution_strategy
from .distributed import all_reduce_sum
from .elemwise import _elwise, exp, log, log1p, maximum, minimum
from .math import matmul, max, sum
from .tensor import broadcast_to, concat, expand_dims, ones, squeeze, zeros

__all__ = [
    "adaptive_avg_pool2d",
    "adaptive_max_pool2d",
    "avg_pool2d",
    "batch_norm",
    "conv1d",
    "conv2d",
    "conv3d",
    "conv_transpose2d",
    "conv_transpose3d",
    "deformable_conv2d",
    "deformable_psroi_pooling",
    "dropout",
    "embedding",
    "gelu",
    "hsigmoid",
    "hswish",
    "indexing_one_hot",
    "leaky_relu",
    "linear",
    "local_conv2d",
    "local_response_norm",
    "logsigmoid",
    "logsumexp",
    "logsoftmax",
    "max_pool2d",
    "one_hot",
    "prelu",
    "pad",
    "relu",
    "relu6",
    "remap",
    "sigmoid",
    "sliding_window",
    "sliding_window_transpose",
    "silu",
    "softmax",
    "softplus",
    "sync_batch_norm",
    "warp_affine",
    "warp_perspective",
    "pixel_shuffle",
]


def expand_hw(x):
    if isinstance(x, Sequence):
        return int(x[0]), int(x[1])
    return int(x), int(x)


def expand_dhw(x):
    if isinstance(x, Sequence):
        return int(x[0]), int(x[1]), int(x[2])
    return int(x), int(x), int(x)


def linear(
    inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None, compute_mode="default",
) -> Tensor:
    r"""Applies a linear transformation to the input tensor.

    Refer to :class:`~.module.linear.Linear` for more information.

    Args:
        inp: input tensor with shape `(N, in_features)`.
        weight: weight with shape `(out_features, in_features)`.
        bias: bias with shape `(out_features,)`. Default: None
    """
    compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
    ret = matmul(inp, weight, transpose_b=True, compute_mode=compute_mode)
    if bias is not None:
        if amp._enabled:
            bias = bias.astype("float16")
        ret += bias
    return ret


def conv1d(
    inp: Tensor,
    weight: Tensor,
    bias: Optional[Tensor] = None,
    stride: int = 1,
    padding: int = 0,
    dilation: int = 1,
    groups: int = 1,
    conv_mode="cross_correlation",
    compute_mode="default",
) -> Tensor:
    r"""1D convolution operation.

    Refer to :class:`~.Conv1d` for more information.

    Args:
        inp: The feature map of the convolution operation
        weight: The convolution kernel.
        bias: The bias added to the result of convolution (if given)
        stride: Stride of the 1D convolution operation. Default: 1
        padding: Size of the paddings added to the input on both sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: Dilation of the 1D convolution operation. Default: 1
        groups: number of groups to divide input and output channels into,
            so as to perform a "grouped convolution". When ``groups`` is not 1,
            ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
            and the shape of weight should be ``(groups, out_channel // groups,
            in_channels // groups, kernel_size)``. Default: 1
        conv_mode: Supports 'cross_correlation'. Default:
            'cross_correlation'.
        compute_mode: When set to 'default', no special requirements will be
            placed on the precision of intermediate results. When set to 'float32',
            float32 would be used for accumulator and intermediate result, but only
            effective when input and output are of float16 dtype.
    """
    assert (
        conv_mode.lower() == "cross_correlation"
        or conv_mode.name == "CROSS_CORRELATION"
    )
    assert compute_mode.lower() == "default" or compute_mode.name == "DEFAULT"
    assert inp.ndim == 3, "the input dimension of conv1d should be 3"
    assert weight.ndim == 3, "the weight dimension of conv1d should be 3"
    if amp._enabled:
        compute_mode = "float32"
        inp, weight, bias = cast_tensors(inp, weight, bias)
    else:
        dtype = dtype_promotion(inp, weight)
        if inp.dtype != dtype:
            inp = inp.astype(dtype)
        if weight.dtype != dtype:
            weight = weight.astype(dtype)

    if bias is not None:
        assert bias.ndim == 3, "the bias dimension of conv1d should be 3"

    stride_h = stride
    pad_h = padding
    dilate_h = dilation

    compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
    conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
    sparse_type = "dense" if groups == 1 else "group"
    op = builtin.Convolution(
        stride_h=stride_h,
        stride_w=1,
        pad_h=pad_h,
        pad_w=0,
        dilate_h=dilate_h,
        dilate_w=1,
        strategy=get_execution_strategy(),
        mode=conv_mode,
        compute_mode=compute_mode,
        sparse=sparse_type,
        format=conv_format,
    )
    (output,) = apply(op, inp, weight)
    if bias is not None:
        output += bias
    return output


def conv2d(
    inp: Tensor,
    weight: Tensor,
    bias: Optional[Tensor] = None,
    stride: Union[int, Tuple[int, int]] = 1,
    padding: Union[int, Tuple[int, int]] = 0,
    dilation: Union[int, Tuple[int, int]] = 1,
    groups: int = 1,
    conv_mode="cross_correlation",
    compute_mode="default",
) -> Tensor:
    r"""2D convolution operation.

    Refer to :class:`~.module.Conv2d` for more information.

    Args:
        inp: feature map of the convolution operation.
        weight: convolution kernel.
        bias: bias added to the result of convolution (if given).
        stride: stride of the 2D convolution operation. Default: 1
        padding: size of the paddings added to the input on both sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: dilation of the 2D convolution operation. Default: 1
        groups: number of groups into which the input and output channels are divided,
            so as to perform a ``grouped convolution``. When ``groups`` is not 1,
            ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
            and the shape of weight should be ``(groups, out_channel // groups,
            in_channels // groups, height, width)``. Default: 1
        conv_mode: supports "cross_correlation". Default: "cross_correlation"
        compute_mode: when set to "default", no special requirements will be
            placed on the precision of intermediate results. When set to "float32",
            "float32" would be used for accumulator and intermediate result, but only
            effective when input and output are of float16 dtype.

    Returns:
        output tensor.
    """
    assert (
        conv_mode.lower() == "cross_correlation"
        or conv_mode.name == "CROSS_CORRELATION"
    )

    stride_h, stride_w = expand_hw(stride)
    pad_h, pad_w = expand_hw(padding)
    dilate_h, dilate_w = expand_hw(dilation)

    sparse_type = "dense" if groups == 1 else "group"
    compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
    conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
    op = builtin.Convolution(
        stride_h=stride_h,
        stride_w=stride_w,
        pad_h=pad_h,
        pad_w=pad_w,
        dilate_h=dilate_h,
        dilate_w=dilate_w,
        strategy=get_execution_strategy(),
        mode=conv_mode,
        compute_mode=compute_mode,
        sparse=sparse_type,
        format=conv_format,
    )
    (output,) = apply(op, inp, weight)
    if bias is not None:
        output += bias
    return output


def conv3d(
    inp: Tensor,
    weight: Tensor,
    bias: Optional[Tensor] = None,
    stride: Union[int, Tuple[int, int, int]] = 1,
    padding: Union[int, Tuple[int, int, int]] = 0,
    dilation: Union[int, Tuple[int, int, int]] = 1,
    groups: int = 1,
    conv_mode: str = "cross_correlation",
) -> Tensor:
    r"""3D convolution operation.

    Refer to :class:`~.Conv3d` for more information.

    Args:
        inp: feature map of the convolution operation.
        weight: convolution kernel.
        bias: bias added to the result of convolution (if given).
        stride: stride of the 3D convolution operation. Default: 1
        padding: size of the paddings added to the input on both sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: dilation of the 3D convolution operation. Default: 1
        groups: number of groups into which the input and output channels are divided,
            so as to perform a ``grouped convolution``. When ``groups`` is not 1,
            ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
            and the shape of weight should be ``(groups, out_channel // groups,
            in_channels // groups, depth, height, width)``. Default: 1
        conv_mode: supports "cross_correlation". Default: "cross_correlation"

    Returns:
        output tensor.
    """
    assert conv_mode.lower() == "cross_correlation"

    D, H, W = 0, 1, 2

    pad = expand_dhw(padding)
    stride = expand_dhw(stride)
    dilate = expand_dhw(dilation)

    sparse_type = "dense" if groups == 1 else "group"
    op = builtin.Convolution3D(
        pad_d=pad[D],
        pad_h=pad[H],
        pad_w=pad[W],
        stride_d=stride[D],
        stride_h=stride[H],
        stride_w=stride[W],
        dilate_d=dilate[D],
        dilate_h=dilate[H],
        dilate_w=dilate[W],
        strategy=get_execution_strategy(),
        mode=conv_mode,
        sparse=sparse_type,
    )
    (output,) = apply(op, inp, weight)
    if bias is not None:
        output += bias
    return output


def conv_transpose2d(
    inp: Tensor,
    weight: Tensor,
    bias: Optional[Tensor] = None,
    stride: Union[int, Tuple[int, int]] = 1,
    padding: Union[int, Tuple[int, int]] = 0,
    dilation: Union[int, Tuple[int, int]] = 1,
    groups: int = 1,
    conv_mode="cross_correlation",
    compute_mode="default",
) -> Tensor:
    r"""2D transposed convolution operation.

    Refer to :class:`~.module.conv.ConvTranspose2d` for more information.

    Args:
        inp: feature map of the convolution operation.
        weight: convolution kernel.
            weight usually has shape ``(in_channels, out_channels, height, width)``.
        bias: bias added to the result of convolution (if given).
        stride: stride of the 2D convolution operation. Default: 1
        padding: size of the paddings added to the input on both sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: dilation of the 2D convolution operation. Default: 1
        groups: number of groups into which the input and output channels are divided,
            so as to perform a ``grouped convolution``. When ``groups`` is not 1,
            ``in_channels`` and ``out_channels`` must be divisible by groups,
            and the shape of weight should be ``(groups, in_channels // groups,
            out_channels // groups, height, width)``. Default: 1
        conv_mode: supports "cross_correlation". Default: "cross_correlation"
        compute_mode: when set to "default", no special requirements will be
            placed on the precision of intermediate results. When set to "float32",
            "float32" would be used for accumulator and intermediate result, but only
            effective when input and output are of float16 dtype.

    Returns:
        output tensor.
    """
    assert (
        conv_mode.lower() == "cross_correlation"
        or conv_mode.name == "CROSS_CORRELATION"
    )

    stride_h, stride_w = expand_hw(stride)
    pad_h, pad_w = expand_hw(padding)
    dilate_h, dilate_w = expand_hw(dilation)

    compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
    sparse_type = "dense" if groups == 1 else "group"
    op = builtin.ConvolutionBackwardData(
        stride_h=stride_h,
        stride_w=stride_w,
        pad_h=pad_h,
        pad_w=pad_w,
        dilate_h=dilate_h,
        dilate_w=dilate_w,
        strategy=get_execution_strategy(),
        compute_mode=compute_mode,
        sparse=sparse_type,
    )
    (output,) = apply(op, weight, inp)
    if bias is not None:
        if amp._enabled:
            bias = cast_tensors(bias)
        output += bias
    return output


def deformable_conv2d(
    inp: Tensor,
    weight: Tensor,
    offset: Tensor,
    mask: Tensor,
    bias: Optional[Tensor] = None,
    stride: Union[int, Tuple[int, int]] = 1,
    padding: Union[int, Tuple[int, int]] = 0,
    dilation: Union[int, Tuple[int, int]] = 1,
    groups: int = 1,
    conv_mode="cross_correlation",
    compute_mode="default",
) -> Tensor:
    r"""Deformable Convolution.

    Args:
        inp: input feature map.
        weight: convolution kernel.
            weight usually has shape ``(out_channels, in_channels, height, width)``.
        offset: input offset to kernel, channel of this tensor should match the deformable settings.
        mask: input mask to kernel, channel of this tensor should match the deformable settings.
        bias: bias added to the result of convolution (if given).
        stride: stride of the 2D convolution operation. Default: 1
        padding: size of the paddings added to the input on both sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: dilation of the 2D convolution operation. Default: 1
        groups: number of groups into which the input and output channels are divided,
            so as to perform a ``grouped convolution``. When ``groups`` is not 1,
            ``in_channels`` and ``out_channels`` must be divisible by groups,
            and the shape of weight should be ``(groups, out_channel // groups,
            in_channels // groups, height, width)``. Default: 1
        conv_mode: supports "cross_correlation". Default: "cross_correlation"
        compute_mode: when set to "default", no special requirements will be
            placed on the precision of intermediate results. When set to "float32",
            "float32" would be used for accumulator and intermediate result, but only
            effective when input and output are of float16 dtype.

    Returns:
        output tensor.
    """
    assert (
        conv_mode.lower() == "cross_correlation"
        or conv_mode.name == "CROSS_CORRELATION"
    )
    if amp._enabled:
        compute_mode = "float32"
        inp, weight, offset, mask, bias = cast_tensors(inp, weight, offset, mask, bias)
    else:
        offset = offset.astype("float32")
        mask = mask.astype("float32")

    stride_h, stride_w = expand_hw(stride)
    pad_h, pad_w = expand_hw(padding)
    dilate_h, dilate_w = expand_hw(dilation)

    compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
    sparse_type = "dense" if groups == 1 else "group"
    op = builtin.DeformableConv(
        stride_h=stride_h,
        stride_w=stride_w,
        pad_h=pad_h,
        pad_w=pad_w,
        dilate_h=dilate_h,
        dilate_w=dilate_w,
        strategy=get_execution_strategy(),
        mode=conv_mode,
        compute_mode=compute_mode,
        sparse=sparse_type,
    )
    (output,) = apply(op, inp, weight, offset, mask)
    if bias is not None:
        output += bias
    return output


def local_conv2d(
    inp: Tensor,
    weight: Tensor,
    bias: Optional[Tensor] = None,
    stride: Union[int, Tuple[int, int]] = 1,
    padding: Union[int, Tuple[int, int]] = 0,
    dilation: Union[int, Tuple[int, int]] = 1,
    conv_mode="cross_correlation",
):
    r"""Applies a spatial convolution with untied kernels over an groupped channeled input 4D tensor.
    It is also known as the locally connected layer.

    Args:
        inp: input feature map.
        weight: convolution kernel.
            weight usually has shape ``(out_channels, in_channels, height, width)``.
        bias: bias added to the result of convolution (if given).
        stride: stride of the 2D convolution operation. Default: 1
        padding: size of the paddings added to the input on both sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: dilation of the 2D convolution operation. Default: 1

    Returns:
        output tensor.
    """
    assert (
        conv_mode.lower() == "cross_correlation"
        or conv_mode.name == "CROSS_CORRELATION"
    )

    stride_h, stride_w = expand_hw(stride)
    pad_h, pad_w = expand_hw(padding)
    dilate_h, dilate_w = expand_hw(dilation)

    dtype = dtype_promotion(inp, weight)
    if inp.dtype != dtype:
        inp = inp.astype(dtype)
    if weight.dtype != dtype:
        weight = weight.astype(dtype)

    # local conv only support "dense" mode, but weight could contain group dimension.
    op = builtin.GroupLocal(
        stride_h=stride_h,
        stride_w=stride_w,
        pad_h=pad_h,
        pad_w=pad_w,
        dilate_h=dilate_h,
        dilate_w=dilate_w,
        mode=conv_mode,
        sparse="dense",
    )
    (output,) = apply(op, inp, weight)
    if bias is not None:
        output += bias
    return output


def conv_transpose3d(
    inp: Tensor,
    weight: Tensor,
    bias: Optional[Tensor] = None,
    stride: Union[int, Tuple[int, int, int]] = 1,
    padding: Union[int, Tuple[int, int, int]] = 0,
    dilation: Union[int, Tuple[int, int, int]] = 1,
    groups: int = 1,
) -> Tensor:
    r"""3D transposed convolution operation. Only support the case that groups = 1
    and conv_mode = "cross_correlation".

    Refer to :class:`~.ConvTranspose3d` for more information.

    Args:
        inp: feature map of the convolution operation.
        weight: convolution kernel.
            weight usually has shape ``(in_channels, out_channels, depth, height, width)``.
        bias: bias added to the result of convolution (if given).
        stride: stride of the 3D convolution operation. Default: 1
        padding: size of the paddings added to the input on all sides of its
            spatial dimensions. Only zero-padding is supported. Default: 0
        dilation: dilation of the 3D convolution operation. Default: 1
        groups: number of groups into which the input and output channels are divided,
            so as to perform a ``grouped convolution``. When ``groups`` is not 1,
            ``in_channels`` and ``out_channels`` must be divisible by groups,
            and the shape of weight should be ``(groups, in_channels // groups,
            out_channels // groups, depth, height, width)``. Default: 1

    Returns:
        output tensor.
    """
    D, H, W = 0, 1, 2
    pad = expand_dhw(padding)
    stride = expand_dhw(stride)
    dilate = expand_dhw(dilation)

    sparse_type = "dense" if groups == 1 else "group"
    op = builtin.Convolution3DBackwardData(
        pad_d=pad[D],
        pad_h=pad[H],
        pad_w=pad[W],
        stride_d=stride[D],
        stride_h=stride[H],
        stride_w=stride[W],
        dilate_d=dilate[D],
        dilate_h=dilate[H],
        dilate_w=dilate[W],
        strategy=get_execution_strategy(),
        sparse=sparse_type,
    )
    (output,) = apply(op, weight, inp)
    if bias is not None:
        output += bias
    return output


def max_pool2d(
    inp: Tensor,
    kernel_size: Union[int, Tuple[int, int]],
    stride: Optional[Union[int, Tuple[int, int]]] = None,
    padding: Union[int, Tuple[int, int]] = 0,
) -> Tensor:
    r"""Applies a 2D max pooling over an input tensor.

    Refer to :class:`~.MaxPool2d` for more information.

    Args:
        inp: input tensor.
        kernel_size: size of the window.
        stride: stride of the window. If not provided, its value is set to kernel_size.
            Default: None
        padding: implicit zero padding added on both sides. Default: 0

    Returns:
        output tensor.
    """
    if stride is None:
        stride = kernel_size
    window_h, window_w = expand_hw(kernel_size)
    stride_h, stride_w = expand_hw(stride)
    padding_h, padding_w = expand_hw(padding)
    conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)

    op = builtin.Pooling(
        window_h=window_h,
        window_w=window_w,
        stride_h=stride_h,
        stride_w=stride_w,
        pad_h=padding_h,
        pad_w=padding_w,
        mode="max",
        format=conv_format,
    )
    (output,) = apply(op, inp)
    return output


def avg_pool2d(
    inp: Tensor,
    kernel_size: Union[int, Tuple[int, int]],
    stride: Optional[Union[int, Tuple[int, int]]] = None,
    padding: Union[int, Tuple[int, int]] = 0,
    mode: str = "average_count_exclude_padding",
) -> Tensor:
    r"""Applies 2D average pooling over an input tensor.

    Refer to :class:`~.AvgPool2d` for more information.

    Args:
        inp: input tensor.
        kernel_size: size of the window.
        stride: stride of the window. If not provided, its value is set to ``kernel_size``.
            Default: None
        padding: implicit zero padding added on both sides. Default: 0
        mode: whether to count padding values, set to "average" will do counting.
            Default: "average_count_exclude_padding"

    Returns:
        output tensor.
    """
    if stride is None:
        stride = kernel_size
    window_h, window_w = expand_hw(kernel_size)
    stride_h, stride_w = expand_hw(stride)
    padding_h, padding_w = expand_hw(padding)
    conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)

    op = builtin.Pooling(
        window_h=window_h,
        window_w=window_w,
        stride_h=stride_h,
        stride_w=stride_w,
        pad_h=padding_h,
        pad_w=padding_w,
        mode=mode,
        format=conv_format,
    )
    (output,) = apply(op, inp)
    return output


def adaptive_max_pool2d(
    inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
) -> Tensor:
    r"""Applies a 2D max adaptive pooling over an input.

    Refer to :class:`~.MaxAdaptivePool2d` for more information.

    Args:
        inp: input tensor.
        oshp: OH, OW)` size of the output shape.

    Returns:
        output tensor.
    """
    if isinstance(oshp, int):
        oshp = (oshp, oshp)
    conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)

    op = builtin.AdaptivePooling(mode="max", format=conv_format,)
    oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
    (output,) = apply(op, inp, oshp)
    return output


def adaptive_avg_pool2d(
    inp: Tensor, oshp: Union[Tuple[int, int], int, Tensor],
) -> Tensor:
    r"""Applies a 2D average adaptive pooling over an input.

    Refer to :class:`~.AvgAdaptivePool2d` for more information.

    Args:
        inp: input tensor.
        oshp: OH, OW)` size of the output shape.

    Returns:
        output tensor.
    """
    if isinstance(oshp, int):
        oshp = (oshp, oshp)

    op = builtin.AdaptivePooling(mode="average", format="NCHW",)
    oshp = astensor1d(oshp, inp, dtype="int32", device=inp.device)
    (output,) = apply(op, inp, oshp)
    return output


def deformable_psroi_pooling(
    inp: Tensor,
    rois: Tensor,
    trans: Tensor,
    no_trans: bool,
    part_size: int,
    pooled_h: int,
    pooled_w: int,
    sample_per_part: int,
    spatial_scale: float,
    trans_std: float = 0.1,
):
    r"""Deformable PSROI(Position Sensitive Region of Interest) Pooling.

    Args:
        inp: input feature map.
        rois: the rois for feature pooling.
        trans: input offset to psroi_pooling.
        no_trans: check the phase of DeformablePSROIPooling. False to the
            1st phase, True to the 2nd phase.
        part_size: part size.
        sample_per_part: sample points of each part.
        pooled_shape: kernel shape of convolution.
        spatial_scale: the spatial_scale w.r.t input image.
        trans_std: multiplier used in 2nd phase.
    """
    op = builtin.DeformablePSROIPooling(
        no_trans=no_trans,
        part_size=part_size,
        pooled_h=pooled_h,
        pooled_w=pooled_w,
        sample_per_part=sample_per_part,
        spatial_scale=spatial_scale,
        trans_std=trans_std,
    )
    output, _ = apply(op, inp, rois, trans)
    return output


def hswish(x):
    r"""Element-wise `x * relu6(x + 3) / 6`.

    Example:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(5).astype(np.float32))
            out = F.hswish(x)
            print(out.numpy().round(decimals=4))

        .. testoutput::

            [0.     0.6667 1.6667 3.     4.    ]

    """
    return _elwise(x, mode=Elemwise.Mode.H_SWISH)


def sigmoid(x):
    r"""Element-wise `1 / ( 1 + exp( -x ) )`."""
    return _elwise(x, mode=Elemwise.Mode.SIGMOID)


@lru_cache(maxsize=None)
def _get_hsigmoid_op(dtype=None, device=None):
    @subgraph_fn(
        "Hsigmoid",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=True,
        custom_grad=True,
    )
    def hsigmoid(inputs, f, c):
        (inp,) = inputs[0:1]
        inp = f("+", inp, c(3))
        max_0 = f("max", inp, c(0))
        min_6 = f("min", max_0, c(6))
        oup = f("/", min_6, c(6))
        (oup_grad,) = yield (oup,)
        inp_grad = f("/", oup_grad, c(6))
        inp_grad = f("cond_leq_mov", max_0, c(6), inp_grad)
        inp_grad = f("cond_leq_mov", c(0), inp, inp_grad)
        yield (inp_grad,)

    return hsigmoid


def hsigmoid(x):
    r"""Element-wise `relu6(x + 3) / 6`."""
    hsigmoid = _get_hsigmoid_op(x.dtype, x.device)
    (x,) = hsigmoid(x)
    return x
    # return relu6(x + 3) / 6


def relu(x):
    r"""Element-wise `max(x, 0)`."""
    return _elwise(x, mode=Elemwise.Mode.RELU)


@lru_cache(maxsize=None)
def _get_relu6_op(dtype=None, device=None):
    @subgraph_fn(
        "ReLU6",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=True,
        custom_grad=True,
    )
    def relu6(inputs, f, c):
        (inp,) = inputs[0:1]
        max_0 = f("max", inp, c(0))
        min_6 = f("min", max_0, c(6))
        oup = min_6
        (oup_grad,) = yield (oup,)
        inp_grad = f("cond_leq_mov", max_0, c(6), oup_grad)
        inp_grad = f("cond_leq_mov", c(0), inp, inp_grad)
        yield (inp_grad,)

    return relu6


def relu6(x):
    r"""Element-wise `min(max(x, 0), 6)`."""
    relu6 = _get_relu6_op(x.dtype, x.device)
    (x,) = relu6(x)
    return x


@lru_cache(maxsize=None)
def _get_prelu_op(dtype=None, device=None):
    @subgraph_fn(
        "PReLU",
        dtype=dtype,
        device=device,
        nr_inputs=2,
        jit_fusion=True,
        custom_grad=True,
    )
    def prelu(inputs, f, c):
        (inp, weight) = inputs[0:2]
        max_0 = f("max", inp, c(0))
        min_0 = f("min", inp, c(0))
        oup = f("fma3", min_0, weight, max_0)
        (oup_grad,) = yield (oup,)
        inp_grad_0 = f("cond_leq_mov", c(0), inp, oup_grad)
        inp_grad_1 = f("*", oup_grad, weight)
        inp_grad_1 = f("cond_leq_mov", inp, c(0), inp_grad_1)
        inp_grad = f("+", inp_grad_0, inp_grad_1)
        weight_grad = f("*", oup_grad, min_0)
        yield (inp_grad, weight_grad)

    return prelu


def prelu(inp: Tensor, weight: Tensor) -> Tensor:
    r"""Element-wise PReLU function.

    Refer to :class:`~.PReLU` for more information.
    """
    prelu = _get_prelu_op(dtype=inp.dtype, device=inp.device)
    (oup,) = prelu(inp, broadcast_to(weight, inp.shape))
    return oup


@lru_cache(maxsize=None)
def _get_leaky_relu_op(negative_slope, *, dtype=None, device=None):
    @subgraph_fn(
        "LeakyReLU",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=True,
        custom_grad=True,
    )
    def leakyReLU(inputs, f, c):
        (inp,) = inputs[0:1]
        max_0 = f("max", inp, c(0))
        min_0 = f("min", inp, c(0))
        oup = f("+", max_0, f("*", min_0, c(negative_slope)))
        (oup_grad,) = yield (oup,)
        inp_grad_0 = f("cond_leq_mov", c(0), inp, oup_grad)
        inp_grad_1 = f("*", oup_grad, c(negative_slope))
        inp_grad_1 = f("cond_leq_mov", inp, c(0), inp_grad_1)
        inp_grad = f("+", inp_grad_0, inp_grad_1)
        yield (inp_grad,)

    return leakyReLU


def leaky_relu(inp: Tensor, negative_slope: float = 0.01) -> Tensor:
    r"""Element-wise LeakyReLU function

    Refer to :class:`~.LeakyReLU` for more information.
    """
    leakyReLU = _get_leaky_relu_op(negative_slope, dtype=inp.dtype, device=inp.device)
    (oup,) = leakyReLU(inp)
    return oup


def silu(x):
    r"""Applies the element-wise Sigmoid Linear Unit function, i.e. `x * sigmoid(x)`."""
    return _elwise(x, mode=Elemwise.Mode.SILU)


def gelu(x):
    r"""Applies the element-wise function:

    .. math::
        \text{gelu}(x) = x\Phi(x)

    where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
    """
    return _elwise(x, mode=Elemwise.Mode.GELU)


@lru_cache(maxsize=None)
def _get_softplus_op(dtype=None, device=None):
    @subgraph_fn(
        "Softplus",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=True,
        custom_grad=True,
    )
    def softplus(inputs, f, c):
        (inp,) = inputs[0:1]
        neg_abs = f("-", f("abs", inp))
        exp = f("exp", neg_abs)
        oup0 = f("log1p", exp)
        oup1 = f("relu", inp)
        oup = f("+", oup0, oup1)
        (oup_grad,) = yield (oup,)
        inp_grad_0 = f("switch_gt0", oup1, oup_grad)
        inp_grad_1 = oup_grad
        inp_grad_1 = f("/", oup_grad, f("+", exp, c(1)))
        inp_grad_1 = f("*", inp_grad_1, exp)
        inp_grad_1 = f("-", inp_grad_1)
        inp_grad_1 = f("abs_grad", inp, inp_grad_1)
        inp_grad = f("+", inp_grad_0, inp_grad_1)
        yield (inp_grad,)

    return softplus


def softplus(inp: Tensor) -> Tensor:
    r"""Applies the element-wise function:

    .. math::
        \text{softplus}(x) = \log(1 + \exp(x))

    softplus is a smooth approximation to the ReLU function and can be used
    to constrain the output to be always positive.
    For numerical stability the implementation follows this transformation:

    .. math::
        \text{softplus}(x) = \log(1 + \exp(x))
                           = \log(1 + \exp(-\text{abs}(x))) + \max(x, 0)
                           = \log1p(\exp(-\text{abs}(x))) + \text{relu}(x)

   Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(-3, 3, dtype=np.float32))
            y = F.softplus(x)
            print(y.numpy().round(decimals=4))

        Outputs:

        .. testoutput::

            [0.0486 0.1269 0.3133 0.6931 1.3133 2.1269]
    """
    softplus = _get_softplus_op(inp.dtype, inp.device)
    (oup,) = softplus(inp)
    return oup


def logsoftmax(inp: Tensor, axis: Union[int, Sequence[int]]) -> Tensor:
    r"""Applies the :math:`\log(\text{softmax}(x))` function to an n-dimensional
    input tensor. The :math:`\text{logsoftmax}(x)` formulation can be simplified as:

    .. math::
        \text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )

    For numerical stability the implementation follows this transformation:

    .. math::
        \text{logsoftmax}(x)
        = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))})
        = x - \log (\sum_{i}(\exp (x_{i})))
        = x - \text{logsumexp}(x)

    Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
            y = F.logsoftmax(x, axis=1)
            print(y.numpy().round(decimals=4))

        Outputs:

        .. testoutput::

            [[-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]
             [-4.4519 -3.4519 -2.4519 -1.4519 -0.4519]]
    """
    return inp - logsumexp(inp, axis, keepdims=True)


@lru_cache(maxsize=None)
def _get_logsigmoid_op(dtype=None, device=None):
    @subgraph_fn(
        "LogSigmoid",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=True,
        custom_grad=True,
    )
    def logsigmoid(inputs, f, c):
        (inp,) = inputs[0:1]
        neg_abs = f("-", f("abs", inp))
        exp = f("exp", neg_abs)
        oup0 = f("log1p", exp)
        oup1 = f("relu", f("-", inp))
        oup = f("+", oup0, oup1)
        oup = f("-", oup)
        (oup_grad,) = yield (oup,)
        oup_grad = f("-", oup_grad)
        inp_grad_0 = f("switch_gt0", oup1, oup_grad)
        inp_grad_0 = f("-", inp_grad_0)
        inp_grad_1 = oup_grad
        inp_grad_1 = f("/", inp_grad_1, f("+", exp, c(1)))
        inp_grad_1 = f("*", inp_grad_1, exp)
        inp_grad_1 = f("-", inp_grad_1)
        inp_grad_1 = f("abs_grad", inp, inp_grad_1)
        inp_grad = f("+", inp_grad_0, inp_grad_1)
        yield (inp_grad,)

    return logsigmoid


def logsigmoid(inp: Tensor) -> Tensor:
    r"""Applies the element-wise function:

    .. math::
        \text{logsigmoid}(x) = \log(\frac{ 1 }{ 1 + \exp(-x)})
        = \log(1/(1 + \exp(-x)))
        = - \log(1 + \exp(-x))
        = - \text{softplus}(-x)

    Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(-5, 5, dtype=np.float32))
            y = F.logsigmoid(x)
            print(y.numpy().round(decimals=4))

        Outputs:

        .. testoutput::

            [-5.0067 -4.0182 -3.0486 -2.1269 -1.3133 -0.6931 -0.3133 -0.1269 -0.0486
            -0.0181]
    """
    logsigmoid = _get_logsigmoid_op(inp.dtype, inp.device)
    (oup,) = logsigmoid(inp)
    return oup


def logsumexp(
    inp: Tensor, axis: Union[int, Sequence[int]], keepdims: bool = False
) -> Tensor:
    r"""Calculates the logarithm of the inputs' exponential sum along the given :attr:`axis`.

    .. math::

        \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)

    For numerical stability, the implementation follows this transformation:

    .. math::

        \text{logsumexp}(x)= \log \sum_{j=1}^{n} \exp \left(x_{j}\right)
        = \text{logsumexp}(x)=b+\log \sum_{j=1}^{n} \exp \left(x_{j}-b\right)

    where

    .. math::
        b = \max(x_j)

    Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
            y = F.logsumexp(x, axis=1, keepdims=False)
            print(y.numpy().round(decimals=4))

        Outputs:

        .. testoutput::

            [-0.5481  4.4519]
    """
    max_value = max(inp.detach(), axis, keepdims=True)
    if keepdims:
        return max_value + log(sum(exp(inp - max_value), axis, keepdims))
    else:
        return squeeze(max_value, axis=None) + log(
            sum(exp(inp - max_value), axis, keepdims)
        )


def _get_softmax_axis(ndim: int) -> int:
    if ndim in (0, 1, 3):
        return 0
    return 1


def softmax(inp: Tensor, axis: Optional[int] = None) -> Tensor:
    r"""Applies a :math:`\text{softmax}(x)` function. :math:`\text{softmax}(x)` is defined as:

    .. math::
            \text{softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}

    It is applied to all elements along axis, and rescales elements so that
    they stay in the range `[0, 1]` and sum to 1.

    See :class:`~.module.Softmax` for more details.

    Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5)
            out = F.softmax(x)
            print(out.numpy().round(decimals=4))

        Outputs:

        .. testoutput::

            [[0.0117 0.0317 0.0861 0.2341 0.6364]
            [0.0117 0.0317 0.0861 0.2341 0.6364]]
    """
    if axis is None:
        axis = _get_softmax_axis(len(inp.shape))
    if isinstance(axis, list):
        offset = inp.max(axis=axis, keepdims=True).detach()
        cached = exp(inp - offset)
        down = sum(cached, axis=axis, keepdims=True)
        return cached / down
    else:
        op = builtin.Softmax(axis=axis,)
        (output,) = apply(op, inp)
        return output


def layer_norm(
    inp: Tensor,
    normalized_shape: tuple,
    affine: bool,
    weight: Optional[Tensor] = None,
    bias: Optional[Tensor] = None,
    eps: float = 1e-5,
):
    r"""Applies layer normalization to the input. Support tensor of any shape as input.
    Reference: https://arxiv.org/pdf/1803.08494.pdf.
    
    Args:
        inp: input tensor.
        normalized_shape: the shape that you want to be normalizated 
        affine: whether to use weight and bias
        weight: must not be None when the affine is true
        bias: must not be None when the affine is true
        eps: a value added to the denominator for numerical stability. Default: 1e-5
    """
    if amp._enabled:
        inp, weight, bias = cast_tensors(inp, weight, bias, promote=True)

    if isinstance(normalized_shape, int):
        normalized_shape = [normalized_shape]

    normalized_dim = len(normalized_shape)
    assert normalized_dim > 0

    normalized_size = 1
    for i in range(normalized_dim):
        normalized_size = normalized_size * normalized_shape[i]

    op = builtin.LayerNorm(
        affine=affine,
        eps=eps,
        normalized_dim=normalized_dim,
        normalized_size=normalized_size,
    )
    if affine:
        assert weight is not None and bias is not None
        return apply(op, inp, weight, bias)[0]
    else:
        # assert weight is None and bias is None
        return apply(op, inp)[0]


def batch_norm(
    inp: Tensor,
    running_mean: Tensor = None,
    running_var: Tensor = None,
    weight: Optional[Tensor] = None,
    bias: Optional[Tensor] = None,
    *,
    training: bool = False,
    momentum: float = 0.9,
    eps: float = 1e-5,
    inplace: bool = True,
    compute_mode="default",
    param_dim="dim_1c11"
):
    r"""Applies batch normalization to the input.

    Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.

    Args:
        inp: input tensor.
        running_mean: tensor to store running mean.
        running_var: tensor to store running variance.
        weight: scaling tensor in the learnable affine parameters.
            See :math:`\gamma` in :class:`~.BatchNorm2d`.
        bias: bias tensor in the learnable affine parameters.
            See :math:`\beta` in :class:`~.BatchNorm2d`.
        training: a boolean value to indicate whether batch norm is performed
            in training mode. Default: False
        momentum: value used for the ``running_mean`` and ``running_var``
            computation. Default: 0.9
        eps: a value added to the denominator for numerical stability. Default: 1e-5
        inplace: whether to update ``running_mean`` and ``running_var``
            inplace or return new tensors. Default: True
    """

    def make_full_if_none(x, value):
        x_ndim = None if x is None else x.ndim
        # in general case, x will be returned here directly
        if x_ndim is not None and x_ndim != 1:
            return x

        if param_dim == "dim_1c11":
            C = inp.shape[1]
            pshape = (1, C, 1, 1)
        elif param_dim == "dim_111c":
            C = inp.shape[3]
            pshape = (1, 1, 1, C)
        else:
            raise ValueError("Invalid param_dim {}".format(param_dim))

        if x is None:
            x = Const(value, inp.dtype, inp.device, None)
            shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
            (result,) = apply(builtin.Broadcast(), x, shape)
            return result
        else:
            assert x_ndim == 1
            shape = astensor1d(pshape, inp, dtype="int32", device=inp.device)
            (result,) = apply(builtin.Reshape(), x, shape)
            return result

    has_mean = running_mean is not None
    has_var = running_var is not None

    if not training:
        assert has_mean, "running_mean must be provided in inference mode"
        assert has_var, "running_var must be provided in inference mode"

    weight = make_full_if_none(weight, 1)
    bias = make_full_if_none(bias, 0)

    if not training:
        op = builtin.BatchNorm(
            fwd_mode=BatchNorm.FwdMode.INFERENCE, epsilon=eps, param_dim=param_dim
        )
        ret = apply(op, inp, weight, bias, running_mean, running_var)[-1]
        return ret

    else:
        op = builtin.BatchNorm(
            avg_factor=1 - momentum, epsilon=eps, param_dim=param_dim
        )
        if has_mean or has_var:
            running_mean = make_full_if_none(running_mean, 0)
            running_var = make_full_if_none(running_var, 1)
            new_mean, new_var, *_, inp = apply(
                op, inp, weight, bias, running_mean, running_var
            )
            if not has_mean:
                new_mean = None
            if not has_var:
                new_var = None

            if inplace:
                if has_mean:
                    running_mean[...] = new_mean
                if has_var:
                    running_var[...] = new_var

                return inp
            else:
                return inp, new_mean, new_var
        else:
            inp = apply(op, inp, weight, bias)[-1]
            return inp


@lru_cache(maxsize=None)
def _get_sync_bn_ops(device, dtype, eps_mode, ndim, channels):
    # fmt: off
    @subgraph("SyncBnStage0", dtype, device, 1)
    def syncbn_stage0(inputs, f, c):
        input = inputs[0]
        reduce_shape = c((1, channels) + (1,) * (ndim - 2), dtype="int32", device=device)
        input_shape = f(GetVarShape(), input)
        input_elems = f(Reduce(mode="product", axis=0), input_shape)
        reduce_elems = f(Reduce(mode="product", axis=0), reduce_shape)
        reduce_size = f("//", input_elems, reduce_elems)
        channel_x1s = f(Reduce(mode="sum"), input, reduce_shape)
        channel_x2s = f(Reduce(mode="sum_sqr"), input, reduce_shape)
        reduce_size_f = f(TypeCvt(dtype=dtype), reduce_size)
        return (reduce_shape, reduce_size_f, channel_x1s, channel_x2s), (False, False, True, True)

    @subgraph("SyncBnStage1", dtype, device, 7)
    def syncbn_stage1(inputs, f, c):
        input, reduce_size, channel_x1s, channel_x2s, eps = inputs[0:5]
        weight, bias = inputs[5:7]
        channel_mean = f("/", channel_x1s, reduce_size)
        channel_var =\
            f("+",  f("/",  f("**", channel_x1s, c(2)),
                            f("-",  f("*", reduce_size, reduce_size))),
                    f("/", channel_x2s, reduce_size))
        invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
        inv_var_wt = f("*", invsqrt_channel_var, weight)
        neg_channel_mean = f("-", channel_mean)
        outvar =\
            f("fma3",  input, inv_var_wt,
                    f("+",  f("*", neg_channel_mean, inv_var_wt),
                            bias))
        return (outvar, channel_mean, channel_var), (True, True, True)

    @subgraph("SyncBnStage1Inference", dtype, device, 6)
    def syncbn_stage1_inference(inputs, f, c):
        input, channel_mean, channel_var, eps = inputs[0:4]
        weight, bias = inputs[4:6]
        invsqrt_channel_var = f("**", f(eps_mode, channel_var, eps), c(-0.5))
        inv_var_wt = f("*", invsqrt_channel_var, weight)
        neg_channel_mean = f("-", channel_mean)
        outvar =\
            f("+",  f("*", input, inv_var_wt),
                    f("+",  f("*", neg_channel_mean, inv_var_wt),
                            bias))
        return (outvar,), (True,)

    @subgraph("SyncBnStage2", dtype, device, 7)
    def syncbn_stage2(inputs, f, c):
        running_mean, running_var, momentum = inputs[0:3]
        reduce_size, channel_x1s, channel_x2s, channel_mean = inputs[3:7]
        c1_minus_momentum = f("-", c(1), momentum)
        reduce_size_minus_c1 = f("-", reduce_size, c(1))
        running_mean = f("fma4",
            running_mean, momentum,
            c1_minus_momentum, channel_mean,
        )
        channel_variance_unbiased =\
            f("+",  f("/",  f("**", channel_x1s, c(2)),
                            f("*",  f("-", reduce_size),
                                    reduce_size_minus_c1)),
                    f("/",  channel_x2s,
                            reduce_size_minus_c1))
        running_var = f("fma4",
            running_var, momentum,
            c1_minus_momentum, channel_variance_unbiased
        )
        return (running_mean, running_var), (True, True)

    @subgraph("SyncBnConcatStats", dtype, device, 3)
    def syncbn_concat_stats(inputs, f, c):
        reduce_size, channel_x1s, channel_x2s = inputs[0:3]
        reduce_size = f(builtin.Broadcast(), reduce_size, c([1]*ndim, dtype="int32"))
        stats = f(builtin.Concat(axis=1, comp_node=device), reduce_size, channel_x1s, channel_x2s)
        return (stats,), (True,)

    @subgraph("SyncBnSplitStats", dtype, device, 1)
    def syncbn_split_stats(inputs, f, c):
        stats = inputs[0]
        c_1 = c(1, dtype="int32")
        channel_x1s_end = c(channels+1, dtype="int32")
        def _subtensor(src, axis, begin, end):
            items = (axis, (begin is not None), (end is not None), False, False),
            args = ()
            if begin is not None:
                args += begin,
            if end is not None:
                args += end,
            return f(builtin.Subtensor(items=items), src, *args)
        reduce_size = _subtensor(stats, 1, None, c_1)
        channel_x1s = _subtensor(stats, 1, c_1, channel_x1s_end)
        channel_x2s = _subtensor(stats, 1, channel_x1s_end, None)
        reduce_size = f(builtin.Reshape(), reduce_size, c_1)
        return (reduce_size, channel_x1s, channel_x2s), (False, True, True)
    # fmt: on
    return (
        syncbn_stage0,
        syncbn_stage1,
        syncbn_stage1_inference,
        syncbn_stage2,
        syncbn_concat_stats,
        syncbn_split_stats,
    )


def sync_batch_norm(
    inp: Tensor,
    running_mean: Tensor,
    running_var: Tensor,
    weight: Optional[Tensor] = None,
    bias: Optional[Tensor] = None,
    training: bool = False,
    momentum: Union[float, Tensor] = 0.9,
    eps: float = 1e-5,
    eps_mode="additive",
    group=WORLD,
) -> Tensor:
    r"""Applies synchronized batch normalization to the input.

    Refer to :class:`~.BatchNorm2d` and :class:`~.BatchNorm1d` for more information.

    Args:
        inp: input tensor.
        running_mean: tensor to store running mean.
        running_var: tensor to store running variance.
        weight: scaling tensor in the learnable affine parameters.
            See :math:`\gamma` in :class:`~.BatchNorm2d`.
        bias: bias tensor in the learnable affine parameters.
            See :math:`\beta` in :class:`~.BatchNorm2d`.
        training: a boolean value to indicate whether batch norm is performed
            in traning mode. Default: False
        momentum: value used for the ``running_mean`` and ``running_var``
            computation. Default: 0.9
        eps: a value added to the denominator for numerical stability.
            Default: 1e-5
        eps_mode: mode of calculation for eps, "max" or "additive".
            Default: "additive"
        group: communication group, caculate mean and variance between this group.
            Default: :obj:`~megengine.distributed.WORLD`
    """
    _eps_mode = eps_mode.lower()
    assert _eps_mode in {"max", "additive"}, "unknown eps_mode: {}".format(eps_mode)
    if _eps_mode == "additive" and not (is_distributed() or training):
        return batch_norm(
            inp,
            running_mean,
            running_var,
            weight,
            bias,
            training=training,
            momentum=momentum,
            eps=eps,
        )
    if amp._enabled:
        inp, weight, bias, running_mean, running_var = cast_tensors(
            inp, weight, bias, running_mean, running_var, promote=True
        )

    _channels = make_shape_tuple(inp.shape)[1]
    _ndim = inp.ndim
    _device = inp.device
    _dtype = inp.dtype

    if _ndim != 4:
        raise NotImplementedError("sync_batch_norm for ndim != 4")

    def _make_full_if_none(x, value):
        if x is None:
            x = Const(value, inp.dtype, _device, None)
            (result,) = apply(builtin.Broadcast(), x, reduce_shape)
            return result
        elif x.ndim == 1:
            (result,) = apply(builtin.Reshape(), x, reduce_shape)
            return result
        return x

    (
        syncbn_stage0,
        syncbn_stage1,
        syncbn_stage1_inference,
        syncbn_stage2,
        syncbn_concat_stats,
        syncbn_split_stats,
    ) = _get_sync_bn_ops(_device, _dtype, eps_mode, _ndim, _channels)

    reduce_shape, reduce_size, channel_x1s, channel_x2s = apply(syncbn_stage0(), inp)

    eps = convert_single_value(eps, dtype=inp.dtype, device=inp.device)

    weight = _make_full_if_none(weight, 1)
    bias = _make_full_if_none(bias, 0)

    if training:
        if is_distributed():
            # reduce all nodes' data to calculate mean and variance
            (stat,) = apply(
                syncbn_concat_stats(), reduce_size, channel_x1s, channel_x2s
            )
            stat = all_reduce_sum(stat, group)
            reduce_size, channel_x1s, channel_x2s = apply(syncbn_split_stats(), stat)

        outvar, channel_mean, *_ = apply(
            syncbn_stage1(),
            inp,
            reduce_size,
            channel_x1s,
            channel_x2s,
            eps,
            weight,
            bias,
        )
    else:
        assert running_var is not None and running_mean is not None
        channel_mean = running_mean
        channel_var = running_var
        outvar, *_ = apply(
            syncbn_stage1_inference(), inp, channel_mean, channel_var, eps, weight, bias
        )

    # outvar = output * weight + bias
    # where output = inp * invsqrt_channel_variance + (
    #    -channel_mean * invsqrt_channel_variance
    # )
    # Manually expand output for gopt

    if training and running_var is not None and running_mean is not None:
        momentum = convert_single_value(momentum, dtype=inp.dtype, device=inp.device)
        running_mean[...], running_var[...] = apply(
            syncbn_stage2(),
            running_mean,
            running_var,
            momentum,
            reduce_size,
            channel_x1s,
            channel_x2s,
            channel_mean,
        )
    if amp._enabled:
        outvar = outvar.astype("float16")
    return outvar


def dropout(inp: Tensor, drop_prob: float, training: bool = True) -> Tensor:
    r"""Returns a new tensor where each of the elements are randomly set to zero
    with probability P = ``drop_prob``. Optionally rescale the output tensor if ``training`` is True.

    Args:
        inp: input tensor.
        drop_prob: probability to drop (set to zero) a single element.
        training: the default behavior of ``dropout`` during training is to rescale the output,
            then it can be replaced by an :class:`~.module.identify.Identity` during inference. Default: True
    Returns:
        the ouput tensor

    Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            # test training mode
            data = tensor(np.ones(10000000, dtype=np.float32))
            out = F.nn.dropout(data, 1.0 / 3.0, training=True)
            assert not out.numpy().all()

            # test eval mode
            out = F.nn.dropout(data, 1.0 / 3.0, training=False)
            assert out.numpy().all()

        Outputs:

        .. testoutput::
            :options: +SKIP

            [1.5 1.5 0.  1.5 1.5 1.5 1.5 1.5 1.5 1.5]
    """
    assert 0 <= drop_prob < 1
    if not training or drop_prob == 0:
        return inp

    # model in training mode, e.g. model.train()
    op = Dropout(drop_prob=drop_prob, seed=_get_global_rng_seed(), handle=0)
    outputs = apply(op, inp)
    return outputs[0]


def one_hot(inp: Tensor, num_classes: int) -> Tensor:
    r"""Performs one-hot encoding for the input tensor.

    Args:
        inp: input tensor.
        num_classes: number of classes denotes the last dimension of the output tensor.

    Examples:

        .. testcode::

            import numpy as np
            from megengine import tensor
            import megengine.functional as F

            x = tensor(np.arange(1, 4, dtype=np.int32))
            out = F.one_hot(x, num_classes=4)
            print(out.numpy())

        Outputs:

        .. testoutput::

            [[0 1 0 0]
             [0 0 1 0]
             [0 0 0 1]]
    """
    zeros_tensor = zeros(
        list(inp.shape) + [num_classes], dtype=inp.dtype, device=inp.device
    )
    ones_tensor = ones(list(inp.shape) + [1], dtype=inp.dtype, device=inp.device)

    op = builtin.IndexingSetOneHot(axis=inp.ndim)
    (result,) = apply(op, zeros_tensor, inp, ones_tensor)
    return result


def embedding(
    inp: Tensor,
    weight: Tensor,
    padding_idx: Optional[int] = None,
    max_norm: Optional[float] = None,
    norm_type: Optional[float] = None,
):
    r"""Applies lookup table for embedding.

    Args:
        inp: tensor with indices.
        weight: learnable weights which embeds from.
        padding_idx: should be set to None, not supported now.
        max_norm: should be set to None, not supported now.
        norm_type: should be set to None, not supported now.

    Refer to :class:`~.module.Embedding` for more information.
    """
    if padding_idx is not None:
        raise ValueError("Not support padding_idx Now!")
    if max_norm is not None or norm_type is not None:
        raise ValueError("Not support weight normlization Now!")

    dest_shp = list(inp.shape) + [weight.shape[-1]]
    return weight[inp.reshape(-1)].reshape(dest_shp)


def indexing_one_hot(
    src: Tensor, index: Tensor, axis: int = 1, keepdims=False
) -> Tensor:
    r"""One-hot indexing for some axes.

    Args:
        src: input tensor.
        index: index tensor.
        axis: axis on src for which values in index index. Default: 1
        keepdims: whether not to remove the axis in result. Default: False

    Examples:

        .. testcode::

            import megengine.functional as F
            from megengine import tensor

            src = tensor([[1.0, 2.0]])
            index = tensor([0])
            val = F.indexing_one_hot(src, index)
            print(val.numpy())

        Outputs:

        .. testoutput::

            [1.]
    """
    assert isinstance(src, Tensor), "src must be of Tensor type"
    op = builtin.IndexingOneHot(axis=axis)
    index = convert_single_value(index, dtype="int32", device=src.device)
    (result,) = apply(op, src, index)
    if not keepdims:
        result = squeeze(result, axis)
    return result


def sliding_window(
    inp: Tensor,
    kernel_size: Union[int, Tuple[int, int]],
    padding: Union[int, Tuple[int, int]] = 0,
    stride: Union[int, Tuple[int, int]] = 1,
    dilation: Union[int, Tuple[int, int]] = 1,
) -> Tensor:
    r"""Extracts sliding local blocks from a batched input tensor.

    Refer to :class:`~.module.sliding_window.SlidingWindow` for more information.

    Args:
        inp: input tensor.
        kernel_size: size of the window.
        padding: implicit zero padding added on both sides of input. Default: 0
        stride: stride of the window. Default: 1
        dilation: dilation of the window. Default: 1
    """
    padding_h, padding_w = expand_hw(padding)
    stride_h, stride_w = expand_hw(stride)
    dilation_h, dilation_w = expand_hw(dilation)
    window_h, window_w = expand_hw(kernel_size)

    op = builtin.Images2Neibs(
        pad_h=padding_h,
        pad_w=padding_w,
        stride_h=stride_h,
        stride_w=stride_w,
        dilate_h=dilation_h,
        dilate_w=dilation_w,
        window_h=window_h,
        window_w=window_w,
    )
    (output,) = apply(op, inp)
    return output


def sliding_window_transpose(
    inp: Tensor,
    output_size: Union[int, Tuple[int, int]],
    kernel_size: Union[int, Tuple[int, int]],
    padding: Union[int, Tuple[int, int]] = 0,
    stride: Union[int, Tuple[int, int]] = 1,
    dilation: Union[int, Tuple[int, int]] = 1,
) -> Tensor:
    r"""Sum over the sliding windows on the corresponding input location.

    Refer to :class:`~.module.sliding_window.SlidingWindowTranspose` for more information.

    Args:
        inp: input tensor.
        output_size: shape of output tensor.
        kernel_size: size of the window.
        padding: implicit zero padding added on both sides of input. Default: 0
        stride: stride of the window. Default: 1
        dilation: dilation of the window. Default: 1
    """
    output_h, output_w = expand_hw(output_size)
    padding_h, padding_w = expand_hw(padding)
    stride_h, stride_w = expand_hw(stride)
    dilation_h, dilation_w = expand_hw(dilation)
    window_h, window_w = expand_hw(kernel_size)

    expected_h = (
        output_h + 2 * padding_h - dilation_h * (window_h - 1) - 1
    ) // stride_h + 1
    expected_w = (
        output_w + 2 * padding_w - dilation_w * (window_w - 1) - 1
    ) // stride_w + 1
    assert inp.ndim == 6, "the input dimension of sliding_window_transpose should be 6"
    assert (
        inp.shape[2] == expected_h and inp.shape[3] == expected_w
    ), "the input shape and output size do not match"

    op = builtin.SlidingWindowTranspose(
        out_h=output_h,
        out_w=output_w,
        pad_h=padding_h,
        pad_w=padding_w,
        stride_h=stride_h,
        stride_w=stride_w,
        dilate_h=dilation_h,
        dilate_w=dilation_w,
        window_h=window_h,
        window_w=window_w,
    )
    (output,) = apply(op, inp)
    return output


def pad(
    src: Tensor,
    pad_width: Tuple[Tuple[int, int], ...],
    mode: str = "constant",
    constant_value: float = 0.0,
) -> Tensor:
    r"""Pads the input tensor.

    Args:
        pad_width: A tuple. Each element in the tuple is the tuple of 2-elements,
            the 2 elements represent the padding size on both sides of the current dimension, ``(front_offset, back_offset)``
        mode: One of the following string values. Default: ``'constant'``

            * ``'constant'``: Pads with a constant value.
            * ``'reflect'``: Pads with the edge values of tensor.
            * ``'replicate'``: Pads with the reflection of the tensor mirrored on the first and last values of the tensor along each axis.
        constant_val: Fill value for ``'constant'`` padding. Default: 0

    Examples:

        >>> import numpy as np
        >>> inp = Tensor([[1., 2., 3.],[4., 5., 6.]])
        >>> inp
        Tensor([[1. 2. 3.]
         [4. 5. 6.]], device=xpux:0)
        >>> F.nn.pad(inp, pad_width=((1, 1),), mode="constant")
        Tensor([[0. 0. 0.]
         [1. 2. 3.]
         [4. 5. 6.]
         [0. 0. 0.]], device=xpux:0)
        >>> F.nn.pad(inp, pad_width=((1, 1),), mode="constant", constant_value=9)
        Tensor([[9. 9. 9.]
         [1. 2. 3.]
         [4. 5. 6.]
         [9. 9. 9.]], device=xpux:0)
        >>> F.nn.pad(inp, pad_width=((1, 1), (1, 2)), mode="reflect")
        Tensor([[5. 4. 5. 6. 5. 4.]
         [2. 1. 2. 3. 2. 1.]
         [5. 4. 5. 6. 5. 4.]
         [2. 1. 2. 3. 2. 1.]], device=xpux:0)
        >>> F.nn.pad(inp, pad_width=((1, 1), (1, 2)), mode="replicate")
        Tensor([[1. 1. 2. 3. 3. 3.]
         [1. 1. 2. 3. 3. 3.]
         [4. 4. 5. 6. 6. 6.]
         [4. 4. 5. 6. 6. 6.]], device=xpux:0)

    """
    p_offsets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    assert mode.lower() in ["constant", "edge", "replicate", "reflect"]

    if mode.lower() == "edge":
        mode = "replicate"

    for i in range(0, len(pad_width)):
        p_offsets[i * 2] = pad_width[i][0]
        p_offsets[i * 2 + 1] = pad_width[i][1]

    op = builtin.Padding(
        front_offset_dim0=p_offsets[0],
        front_offset_dim1=p_offsets[2],
        front_offset_dim2=p_offsets[4],
        front_offset_dim3=p_offsets[6],
        front_offset_dim4=p_offsets[8],
        front_offset_dim5=p_offsets[10],
        front_offset_dim6=p_offsets[12],
        back_offset_dim0=p_offsets[1],
        back_offset_dim1=p_offsets[3],
        back_offset_dim2=p_offsets[5],
        back_offset_dim3=p_offsets[7],
        back_offset_dim4=p_offsets[9],
        back_offset_dim5=p_offsets[11],
        back_offset_dim6=p_offsets[13],
        padding_val=constant_value,
        padding_mode=mode.upper(),
    )
    (output,) = apply(op, src)
    return output


def local_response_norm(
    inp: Tensor,
    kernel_size: int = 5,
    k: float = 2.0,
    alpha: float = 1e-4,
    beta: float = 0.75,
) -> Tensor:
    r"""
    Apply local response normalization to the input tensor.

    Args:
        kernel_size: the size of the kernel to apply LRN on.
        k: hyperparameter k. The default vaule is 2.0.
        alpha: hyperparameter alpha. The default value is 1e-4.
        beta: hyperparameter beta. The default value is 0.75.

    Example:

    .. testcode::

        from megengine import tensor
        import megengine.functional as f
        import numpy as np

        inp = tensor(np.arange(25, dtype=np.float32).reshape(1,1,5,5))
        GT = np.array([[[[ 0.,         0.999925,   1.9994003,  2.9979765,  3.9952066],
           [ 4.9906454,  5.983851,   6.974385,   7.961814,   8.945709 ],
           [ 9.925651,  10.90122,   11.872011,  12.837625,  13.7976675],
           [14.751757,  15.699524,  16.640602,  17.574642,  18.501305 ],
           [19.420258,  20.331186,  21.233786,  22.127764,  23.012836 ]]]])

        out = f.local_response_norm(inp, kernel_size=3, k=1.0, alpha=1e-4, beta=0.75)
        np.testing.assert_allclose(GT, out.numpy(), rtol=1e-6, atol=1e-6)
        print('pass')

    Outputs:

    .. testoutput::

        pass

    """
    op = builtin.LRN(n=kernel_size, k=k, alpha=alpha, beta=beta,)
    (output,) = apply(op, inp)
    return output


@lru_cache(maxsize=None)
def _get_layerPixelShuffle(device, dtype, dim_order):
    @subgraph("LayerPixelShuffle", dtype, device, 3)
    def layerPixelShuffle(inputs, f, c):
        inp, shape_0, shape_1 = inputs
        inp = f(Reshape(), inp, shape_0)
        inp = f(Dimshuffle(dim_order), inp)
        oup = f(Reshape(), inp, shape_1)
        return (oup,), (True,)

    return layerPixelShuffle


def pixel_shuffle(inp: Tensor, upscale_factor: int) -> Tensor:
    """
    Rearranges elements in a tensor of shape (*, C x r^2, H, W) to a tensor of
    shape (*, C, H x r, W x r), where r is an upscale factor, where * is zero
    or more batch dimensions.

    :param inp: input tensor.
    :param upscale_factor: upscale factor of pixel_shuffle.
    :return: output tensor.
    """
    assert upscale_factor > 0, "upscale_factor should larger than 0"
    assert inp.ndim >= 3, "the input dimension of pixel_shuffle should be larger than 3"
    assert (
        inp.shape[-3] % (upscale_factor ** 2) == 0
    ), "the -3 dimension should be divided by (upscale_factor ** 2)"

    _device = inp.device
    _dtype = inp.dtype
    shape_ori = inp.shape
    high_dim = shape_ori[:-3]
    square = upscale_factor ** 2
    n = 1
    for item in high_dim:
        n *= item
    shape_0 = (
        n,
        int(shape_ori[-3] / square),
        upscale_factor,
        upscale_factor,
        shape_ori[-2],
        shape_ori[-1],
    )
    shape_1 = (
        *high_dim,
        int(shape_ori[-3] / square),
        shape_ori[-2] * upscale_factor,
        shape_ori[-1] * upscale_factor,
    )

    dim_order = (0, 1, 4, 2, 5, 3)

    layerPixelShuffle = _get_layerPixelShuffle(_device, _dtype, dim_order)

    shape_0 = convert_single_value(shape_0, device=inp.device)
    shape_1 = convert_single_value(shape_1, device=inp.device)
    outvar, *_ = apply(layerPixelShuffle(), inp, shape_0, shape_1)

    return outvar


from .quantized import conv_bias_activation  # isort:skip
from .loss import *  # isort:skip
from .metric import *  # isort:skip
from .vision import *  # isort:skip